open-vault/builtin/logical/transit/path_wrapping_key_test.go
Matt Schultz 5aabe4a5f8
Add Transit BYOK wrapping key endpoint (#15271)
* add wrapping key endpoint

* change how wrapping key is stored

* move wrapping key func to backend

* refactor wrapping key generation

* Initial unit tests for Transit wrapping key endpoint

* Wire up wrapping key unit tests to actual implementation.

* Clean up Transit BYOK wrapping key tests and imports.

* Fix Transit wrapping key endpoint formatting.

* Update transit wrapping key to use lock manager for safe concurrent use.

* Rename some Transit wrapping key variables. Ensure the Transit wrapping key is correctly typed and formatted in a unit test.

* Fix spacing issue in Transit wrapping key endpoint help string.

Co-authored-by: rculpepper <rculpepper@hashicorp.com>
2022-05-11 11:28:32 -05:00

73 lines
1.9 KiB
Go

package transit
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"testing"
"github.com/hashicorp/vault/sdk/logical"
)
const (
storagePath = "policy/import/" + WrappingKeyName
)
func TestTransit_WrappingKey(t *testing.T) {
// Set up shared backend for subtests
b, s := createBackendWithStorage(t)
// Ensure the key does not exist before requesting it.
keyEntry, err := s.Get(context.Background(), storagePath)
if err != nil {
t.Fatalf("error retrieving wrapping key from storage: %s", err)
}
if keyEntry != nil {
t.Fatal("wrapping key unexpectedly exists")
}
// Generate the key pair by requesting the public key.
req := &logical.Request{
Storage: s,
Operation: logical.ReadOperation,
Path: "wrapping_key",
}
resp, err := b.HandleRequest(context.Background(), req)
if err != nil {
t.Fatalf("unexpected request error: %s", err)
}
if resp == nil || resp.Data == nil || resp.Data["public_key"] == nil {
t.Fatal("expected non-nil response")
}
pubKeyPEM := resp.Data["public_key"]
// Ensure the returned key is a 4096-bit RSA key.
pubKeyBlock, _ := pem.Decode([]byte(pubKeyPEM.(string)))
rawPubKey, err := x509.ParsePKIXPublicKey(pubKeyBlock.Bytes)
if err != nil {
t.Fatalf("failed to parse public wrapping key: %s", err)
}
wrappingKey, ok := rawPubKey.(*rsa.PublicKey)
if !ok || wrappingKey.Size() != 512 {
t.Fatal("public wrapping key is not a 4096-bit RSA key")
}
// Request the wrapping key again to ensure it isn't regenerated.
req = &logical.Request{
Storage: s,
Operation: logical.ReadOperation,
Path: "wrapping_key",
}
resp, err = b.HandleRequest(context.Background(), req)
if err != nil {
t.Fatalf("unexpected request error: %s", err)
}
if resp == nil || resp.Data == nil || resp.Data["public_key"] == nil {
t.Fatal("expected non-nil response")
}
if resp.Data["public_key"] != pubKeyPEM {
t.Fatal("wrapping key public component changed between requests")
}
}