mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
kms/local: load master keys from the provider config (#13312)
* kms/local: load master keys from the provider config The local provider generated its master keys in memory, so a restart or a reload lost them, and with them every object they encrypted. It now reads a keys list from its config. Each entry has a key_id, 32 bytes of key_material in hex or base64, and optional aliases and description. A reload reads the list again, so objects encrypted under a listed key stay readable. A name that's already taken, key material that isn't 32 bytes, or enableOnDemandCreate together with keys fails the provider, and the keys it loaded before the error are cleared. No default key is generated when keys are listed, since whatever it wrapped would be lost on a restart. CreateKey and CreateKeyWithID refuse a name that's taken instead of replacing that key. GetStringMap copies a list of tables like the other nested values it hands out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * kms/local: give a racing on-demand request the key the first one created CreateKeyWithID refuses a key ID that's taken now, and the on-demand path looked the key up and created it under separate locks. Two requests for the same new key could both miss it, and the second then failed with KMSInternalFailure. The on-demand path checks for the key under the lock it stores it with, and returns the one stored in the meantime, so the first request's data key stays readable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * kms/local: serve requests that name no key with the configured aws/s3 key With keys configured there is no generated default key, so an SSE-KMS request without a key ID failed even when the bucket-default path (which already resolves to alias/aws/s3) would work. Resolve an empty key ID to alias/aws/s3, as AWS does, so an operator picks the default by giving a configured key that alias instead of a new setting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * kms/local: refuse a master key that Close cleared mid-request A reload replaces the provider and closes the old one, which zeroes its key material in place. A request that looked up a key before the close could then build its cipher from zeros and store a data key no provider can unwrap. Build the cipher under the provider lock and refuse a key that is no longer registered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
6 files changed
+729
-99
No files matched your search
@@ -386,8 +386,10 @@ filer:
|
||||
need one, and so do changes to the values the chart generates its own Secret from, such
|
||||
as `s3.credentials`.
|
||||
- Every reload also re-creates the KMS providers configured in the identities file. The
|
||||
`local` provider keeps its keys in memory, so a reload replaces them, as a restart does;
|
||||
use another provider for objects that must stay readable.
|
||||
`local` provider reads its `keys` list again, so objects encrypted under those keys stay
|
||||
readable. The keys it generates in memory are lost on a reload, as on a restart, so list
|
||||
every key that protects objects you need to keep, and give the alias `aws/s3` to the one
|
||||
that should serve requests naming no key.
|
||||
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
|
||||
so the sidecar can see SeaweedFS. It uses the component's image and container security
|
||||
context, because it must run as the same user as SeaweedFS to signal it. If it can't
|
||||
|
||||
@@ -69,6 +69,11 @@ func (c *configAdapter) value(key string) (interface{}, bool) {
|
||||
return c.config[match], true
|
||||
}
|
||||
|
||||
func (c *configAdapter) Get(key string) interface{} {
|
||||
val, _ := c.value(key)
|
||||
return val
|
||||
}
|
||||
|
||||
// typed reads key as a T. TOML decodes integers as int64 and JSON as float64, so a whole
|
||||
// number of either reads as an int.
|
||||
func typed[T any](c *configAdapter, key string) (T, error) {
|
||||
|
||||
+327
-97
@@ -5,6 +5,8 @@ import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -18,8 +20,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// LocalKMSProvider implements a local, in-memory KMS for development and testing
|
||||
// WARNING: This is NOT suitable for production use - keys are stored in memory
|
||||
// LocalKMSProvider's master keys are listed under "keys" or generated in memory. Generated
|
||||
// keys are lost on a reload or restart, along with every data key they wrapped.
|
||||
type LocalKMSProvider struct {
|
||||
mu sync.RWMutex
|
||||
keys map[string]*LocalKey
|
||||
@@ -41,11 +43,50 @@ type LocalKey struct {
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
}
|
||||
|
||||
// LocalKMSConfig contains configuration for the local KMS provider
|
||||
type LocalKMSConfig struct {
|
||||
DefaultKeyID string `json:"defaultKeyId"`
|
||||
Keys map[string]*LocalKey `json:"keys"`
|
||||
EnableOnDemandCreate bool `json:"enableOnDemandCreate"`
|
||||
const localARNPrefix = "arn:aws:kms:local:000000000000:"
|
||||
|
||||
// awsS3KeyAlias names the key a request that names no key gets when keys are configured, as
|
||||
// AWS answers those with its aws/s3 managed key.
|
||||
const awsS3KeyAlias = "alias/aws/s3"
|
||||
|
||||
func keyARN(keyID string) string {
|
||||
return localARNPrefix + "key/" + keyID
|
||||
}
|
||||
|
||||
func aliasName(alias string) string {
|
||||
if strings.HasPrefix(alias, "alias/") {
|
||||
return alias
|
||||
}
|
||||
return "alias/" + alias
|
||||
}
|
||||
|
||||
func newLocalKey(keyID, description string, material []byte, origin kms.KeyOrigin, aliases []string) *LocalKey {
|
||||
return &LocalKey{
|
||||
KeyID: keyID,
|
||||
ARN: keyARN(keyID),
|
||||
Description: description,
|
||||
KeyMaterial: material,
|
||||
KeyUsage: kms.KeyUsageEncryptDecrypt,
|
||||
KeyState: kms.KeyStateEnabled,
|
||||
Origin: origin,
|
||||
CreatedAt: time.Now(),
|
||||
Aliases: aliases,
|
||||
Metadata: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func randomKeyMaterial() ([]byte, error) {
|
||||
material := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, material); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
||||
}
|
||||
return material, nil
|
||||
}
|
||||
|
||||
// util.Configuration has no getter for a list of tables, so the keys are read through Get,
|
||||
// which the manager's adapter and Viper both have.
|
||||
type configGetter interface {
|
||||
Get(key string) interface{}
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -67,7 +108,8 @@ func NewLocalKMSProvider(config util.Configuration) (kms.KMSProvider, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Create a default key if none exists
|
||||
// Skipped when keys are configured, or a request naming no key would be wrapped by a
|
||||
// key that's gone after a restart.
|
||||
if len(provider.keys) == 0 {
|
||||
defaultKey, err := provider.createDefaultKey()
|
||||
if err != nil {
|
||||
@@ -81,17 +123,229 @@ func NewLocalKMSProvider(config util.Configuration) (kms.KMSProvider, error) {
|
||||
}
|
||||
|
||||
// loadConfig loads configuration from the provided config
|
||||
func (p *LocalKMSProvider) loadConfig(config util.Configuration) error {
|
||||
func (p *LocalKMSProvider) loadConfig(config util.Configuration) (err error) {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
// The provider is dropped on error, so clear the keys loaded before it.
|
||||
defer func() {
|
||||
if err != nil {
|
||||
p.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
p.enableOnDemandCreate = config.GetBool("enableOnDemandCreate")
|
||||
|
||||
// TODO: Load pre-existing keys from configuration if provided
|
||||
// For now, rely on default key creation in constructor
|
||||
getter, ok := config.(configGetter)
|
||||
if !ok {
|
||||
return fmt.Errorf("can't read keys from a %T configuration", config)
|
||||
}
|
||||
configured, err := p.loadKeys(getter.Get("keys"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if configured > 0 && p.enableOnDemandCreate {
|
||||
return fmt.Errorf("enableOnDemandCreate can't be combined with keys: a mistyped key ID would get a key that's lost on restart, with every object it encrypted")
|
||||
}
|
||||
|
||||
glog.V(2).Infof("Local KMS: enableOnDemandCreate = %v", p.enableOnDemandCreate)
|
||||
if configured > 0 && p.keys[awsS3KeyAlias] == nil {
|
||||
glog.Warningf("Local KMS: no configured key has the alias aws/s3, so requests that name no key fail, including S3 writes to a bucket whose default encryption names no key")
|
||||
}
|
||||
|
||||
glog.V(2).Infof("Local KMS: %d configured keys, enableOnDemandCreate = %v", configured, p.enableOnDemandCreate)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The keys are a list rather than a map keyed by ID because Viper lowercases map keys, which
|
||||
// would change the IDs read from TOML and orphan every data key wrapped under the original ones.
|
||||
func (p *LocalKMSProvider) loadKeys(raw interface{}) (int, error) {
|
||||
var entries []map[string]interface{}
|
||||
switch v := raw.(type) {
|
||||
case nil:
|
||||
return 0, nil
|
||||
case []map[string]interface{}:
|
||||
entries = v
|
||||
case []interface{}:
|
||||
for i, entry := range v {
|
||||
fields, ok := entry.(map[string]interface{})
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("keys[%d]: expected a table, got %T", i, entry)
|
||||
}
|
||||
entries = append(entries, fields)
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("keys: expected a list, got %T", raw)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
return 0, fmt.Errorf("keys is empty")
|
||||
}
|
||||
|
||||
for i, fields := range entries {
|
||||
key, err := configuredKey(fields)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("keys[%d]: %w", i, err)
|
||||
}
|
||||
if err := p.registerKey(key); err != nil {
|
||||
return 0, fmt.Errorf("keys[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
return len(entries), nil
|
||||
}
|
||||
|
||||
// The errors leave the key_id out, as the caller names the entry by its index: fields
|
||||
// swapped by mistake put the key material in key_id.
|
||||
func configuredKey(fields map[string]interface{}) (*LocalKey, error) {
|
||||
keyID, err := stringField(fields, "key_id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if keyID == "" {
|
||||
return nil, fmt.Errorf("key_id is required")
|
||||
}
|
||||
if keyID, err = keyIDName("key_id", keyID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aliases, err := stringList(fields["aliases"])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("aliases: %w", err)
|
||||
}
|
||||
if aliases, err = aliasNames(aliases); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
description, err := stringField(fields, "description")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
material, err := stringField(fields, "key_material")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyMaterial, err := decodeKeyMaterial(material)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newLocalKey(keyID, description, keyMaterial, kms.KeyOriginExternal, aliases), nil
|
||||
}
|
||||
|
||||
func aliasNames(aliases []string) ([]string, error) {
|
||||
names := make([]string, len(aliases))
|
||||
for i, alias := range aliases {
|
||||
names[i] = aliasName(alias)
|
||||
if err := checkName(fmt.Sprintf("aliases[%d]", i), strings.TrimPrefix(names[i], "alias/")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func keyIDName(field, keyID string) (string, error) {
|
||||
if err := checkName(field, keyID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if strings.HasPrefix(keyID, "alias/") {
|
||||
return "", fmt.Errorf("%s is an alias, not a key ID", field)
|
||||
}
|
||||
return keyID, nil
|
||||
}
|
||||
|
||||
// checkName refuses a blank name or one with spaces around it. A templating slip produces
|
||||
// these, and only a request carrying the same spaces would ever match them.
|
||||
func checkName(field, name string) error {
|
||||
switch trimmed := strings.TrimSpace(name); {
|
||||
case trimmed == "":
|
||||
return fmt.Errorf("%s is empty", field)
|
||||
case trimmed != name:
|
||||
return fmt.Errorf("%s has spaces around it", field)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stringField(fields map[string]interface{}, name string) (string, error) {
|
||||
return stringValue(name, fields[name])
|
||||
}
|
||||
|
||||
func stringValue(name string, value interface{}) (string, error) {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return "", nil
|
||||
case string:
|
||||
return v, nil
|
||||
default:
|
||||
return "", fmt.Errorf("%s must be a string, got %T", name, v)
|
||||
}
|
||||
}
|
||||
|
||||
// decodeKeyMaterial reads 64 hex characters or standard base64, which takes 44 for 32 bytes,
|
||||
// so the two can't be confused. Spaces around it, like a Secret file's trailing newline, are
|
||||
// dropped. Errors leave the material out.
|
||||
func decodeKeyMaterial(s string) ([]byte, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil, fmt.Errorf("key_material is required")
|
||||
}
|
||||
if len(s) == hex.EncodedLen(32) {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
kms.ClearSensitiveData(b)
|
||||
return nil, fmt.Errorf("key_material of 64 characters must be hex")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
b, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
kms.ClearSensitiveData(b)
|
||||
return nil, fmt.Errorf("key_material must be 64 hex characters or standard base64")
|
||||
}
|
||||
if len(b) != 32 {
|
||||
kms.ClearSensitiveData(b)
|
||||
return nil, fmt.Errorf("key_material must be 32 bytes, got %d", len(b))
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func stringList(raw interface{}) ([]string, error) {
|
||||
switch v := raw.(type) {
|
||||
case nil:
|
||||
return nil, nil
|
||||
case []string:
|
||||
return append([]string(nil), v...), nil
|
||||
case []interface{}:
|
||||
list := make([]string, 0, len(v))
|
||||
for _, item := range v {
|
||||
s, ok := item.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected strings, got %T", item)
|
||||
}
|
||||
list = append(list, s)
|
||||
}
|
||||
return list, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("expected a list, got %T", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// registerKey refuses a name that's already taken, so a typo can't point an alias at another
|
||||
// key. A refused key has its material cleared.
|
||||
func (p *LocalKMSProvider) registerKey(key *LocalKey) error {
|
||||
names := append([]string{key.KeyID}, key.Aliases...)
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
seen := make(map[string]bool, len(names))
|
||||
for i, name := range names {
|
||||
if p.keys[name] != nil || seen[name] {
|
||||
kms.ClearSensitiveData(key.KeyMaterial)
|
||||
if i == 0 {
|
||||
return fmt.Errorf("key_id is already taken")
|
||||
}
|
||||
return fmt.Errorf("aliases[%d] is already taken", i-1)
|
||||
}
|
||||
seen[name] = true
|
||||
}
|
||||
for _, name := range names {
|
||||
p.keys[name] = key
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -101,33 +355,15 @@ func (p *LocalKMSProvider) createDefaultKey() (*LocalKey, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate key ID: %w", err)
|
||||
}
|
||||
keyMaterial := make([]byte, 32) // 256-bit key
|
||||
if _, err := io.ReadFull(rand.Reader, keyMaterial); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key := &LocalKey{
|
||||
KeyID: keyID,
|
||||
ARN: fmt.Sprintf("arn:aws:kms:local:000000000000:key/%s", keyID),
|
||||
Description: "Default local KMS key for SeaweedFS",
|
||||
KeyMaterial: keyMaterial,
|
||||
KeyUsage: kms.KeyUsageEncryptDecrypt,
|
||||
KeyState: kms.KeyStateEnabled,
|
||||
Origin: kms.KeyOriginLocal,
|
||||
CreatedAt: time.Now(),
|
||||
Aliases: []string{"alias/seaweedfs-default"},
|
||||
Metadata: make(map[string]string),
|
||||
key := newLocalKey(keyID, "Default local KMS key for SeaweedFS", keyMaterial, kms.KeyOriginLocal, []string{"alias/seaweedfs-default"})
|
||||
if err := p.registerKey(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.keys[keyID] = key
|
||||
|
||||
// Also register aliases
|
||||
for _, alias := range key.Aliases {
|
||||
p.keys[alias] = key
|
||||
}
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -155,9 +391,8 @@ func (p *LocalKMSProvider) GenerateDataKey(ctx context.Context, req *kms.Generat
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a random 256-bit data key
|
||||
dataKey := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, dataKey); err != nil {
|
||||
dataKey, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, &kms.KMSError{
|
||||
Code: kms.ErrCodeKMSInternalFailure,
|
||||
Message: "Failed to generate data key",
|
||||
@@ -282,9 +517,12 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// Try with default key if no identifier provided
|
||||
if keyIdentifier == "" && p.defaultKeyID != "" {
|
||||
if key, exists := p.keys[p.defaultKeyID]; exists {
|
||||
if keyIdentifier == "" {
|
||||
defaultKeyID := p.defaultKeyID
|
||||
if defaultKeyID == "" {
|
||||
defaultKeyID = awsS3KeyAlias
|
||||
}
|
||||
if key, exists := p.keys[defaultKeyID]; exists {
|
||||
p.mu.RUnlock()
|
||||
return key, nil
|
||||
}
|
||||
@@ -295,7 +533,7 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
||||
// Key doesn't exist - create on-demand if enabled and key identifier is reasonable
|
||||
if keyIdentifier != "" && p.enableOnDemandCreate && p.isReasonableKeyIdentifier(keyIdentifier) {
|
||||
glog.V(1).Infof("Creating on-demand local KMS key: %s", keyIdentifier)
|
||||
key, err := p.CreateKeyWithID(keyIdentifier, fmt.Sprintf("Auto-created local KMS key: %s", keyIdentifier))
|
||||
key, err := p.createOnDemandKey(keyIdentifier)
|
||||
if err != nil {
|
||||
return nil, &kms.KMSError{
|
||||
Code: kms.ErrCodeKMSInternalFailure,
|
||||
@@ -346,14 +584,25 @@ type encryptedDataKeyMetadata struct {
|
||||
Nonce []byte `json:"nonce"` // Renamed from IV to be more explicit about AES-GCM usage
|
||||
}
|
||||
|
||||
// encryptDataKey encrypts a data key using the master key with AES-GCM for authenticated encryption
|
||||
func (p *LocalKMSProvider) encryptDataKey(dataKey []byte, masterKey *LocalKey, encryptionContext map[string]string) ([]byte, error) {
|
||||
// masterKeyGCM builds the cipher under the lock Close clears key material with. A reload
|
||||
// closes the provider it replaces while requests may still hold its keys, and a cleared key
|
||||
// would wrap data keys under zeros that no provider can unwrap.
|
||||
func (p *LocalKMSProvider) masterKeyGCM(masterKey *LocalKey) (cipher.AEAD, error) {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
if p.keys[masterKey.KeyID] != masterKey {
|
||||
return nil, fmt.Errorf("key %s was closed", masterKey.KeyID)
|
||||
}
|
||||
block, err := aes.NewCipher(masterKey.KeyMaterial)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
// encryptDataKey encrypts a data key using the master key with AES-GCM for authenticated encryption
|
||||
func (p *LocalKMSProvider) encryptDataKey(dataKey []byte, masterKey *LocalKey, encryptionContext map[string]string) ([]byte, error) {
|
||||
gcm, err := p.masterKeyGCM(masterKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -392,12 +641,7 @@ func (p *LocalKMSProvider) encryptDataKey(dataKey []byte, masterKey *LocalKey, e
|
||||
|
||||
// decryptDataKey decrypts a data key using the master key with AES-GCM for authenticated decryption
|
||||
func (p *LocalKMSProvider) decryptDataKey(metadata *encryptedDataKeyMetadata, masterKey *LocalKey) ([]byte, error) {
|
||||
block, err := aes.NewCipher(masterKey.KeyMaterial)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
gcm, err := p.masterKeyGCM(masterKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -466,65 +710,51 @@ func (p *LocalKMSProvider) CreateKey(description string, aliases []string) (*Loc
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate key ID: %w", err)
|
||||
}
|
||||
keyMaterial := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, keyMaterial); err != nil {
|
||||
names, err := aliasNames(aliases)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key := &LocalKey{
|
||||
KeyID: keyID,
|
||||
ARN: fmt.Sprintf("arn:aws:kms:local:000000000000:key/%s", keyID),
|
||||
Description: description,
|
||||
KeyMaterial: keyMaterial,
|
||||
KeyUsage: kms.KeyUsageEncryptDecrypt,
|
||||
KeyState: kms.KeyStateEnabled,
|
||||
Origin: kms.KeyOriginLocal,
|
||||
CreatedAt: time.Now(),
|
||||
Aliases: aliases,
|
||||
Metadata: make(map[string]string),
|
||||
return p.addKey(newLocalKey(keyID, description, keyMaterial, kms.KeyOriginLocal, names))
|
||||
}
|
||||
|
||||
// CreateKeyWithID creates a key with a specific keyID, refusing one that's already taken.
|
||||
func (p *LocalKMSProvider) CreateKeyWithID(keyID, description string) (*LocalKey, error) {
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.addKey(newLocalKey(keyID, description, keyMaterial, kms.KeyOriginLocal, []string{}))
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
p.keys[keyID] = key
|
||||
for _, alias := range aliases {
|
||||
// Ensure alias has proper format
|
||||
if !strings.HasPrefix(alias, "alias/") {
|
||||
alias = "alias/" + alias
|
||||
}
|
||||
p.keys[alias] = key
|
||||
func (p *LocalKMSProvider) addKey(key *LocalKey) (*LocalKey, error) {
|
||||
if err := p.registerKey(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// CreateKeyWithID creates a key with a specific keyID (for testing only)
|
||||
func (p *LocalKMSProvider) CreateKeyWithID(keyID, description string) (*LocalKey, error) {
|
||||
keyMaterial := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, keyMaterial); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
||||
}
|
||||
|
||||
key := &LocalKey{
|
||||
KeyID: keyID,
|
||||
ARN: fmt.Sprintf("arn:aws:kms:local:000000000000:key/%s", keyID),
|
||||
Description: description,
|
||||
KeyMaterial: keyMaterial,
|
||||
KeyUsage: kms.KeyUsageEncryptDecrypt,
|
||||
KeyState: kms.KeyStateEnabled,
|
||||
Origin: kms.KeyOriginLocal,
|
||||
CreatedAt: time.Now(),
|
||||
Aliases: []string{}, // No aliases by default
|
||||
Metadata: make(map[string]string),
|
||||
// createOnDemandKey returns the key already stored under keyID rather than replacing it, as
|
||||
// two on-demand requests for a new key can race and the first may have wrapped a data key
|
||||
// already.
|
||||
func (p *LocalKMSProvider) createOnDemandKey(keyID string) (*LocalKey, error) {
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := newLocalKey(keyID, fmt.Sprintf("Auto-created local KMS key: %s", keyID), keyMaterial, kms.KeyOriginLocal, []string{})
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
// Register key with the exact keyID provided
|
||||
if existing := p.keys[keyID]; existing != nil {
|
||||
kms.ClearSensitiveData(keyMaterial)
|
||||
return existing, nil
|
||||
}
|
||||
p.keys[keyID] = key
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
package local
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type mapConfig map[string]interface{}
|
||||
|
||||
func (c mapConfig) Get(key string) interface{} { return c[key] }
|
||||
func (c mapConfig) GetString(key string) string { s, _ := c[key].(string); return s }
|
||||
func (c mapConfig) GetBool(key string) bool { b, _ := c[key].(bool); return b }
|
||||
func (c mapConfig) GetInt(key string) int { i, _ := c[key].(int); return i }
|
||||
func (c mapConfig) GetStringSlice(key string) []string { return nil }
|
||||
func (c mapConfig) SetDefault(key string, value interface{}) {}
|
||||
|
||||
const (
|
||||
keyA = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
|
||||
keyB = "1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100"
|
||||
)
|
||||
|
||||
var testContext = map[string]string{"aws:s3:arn": "arn:aws:s3:::bucket/object"}
|
||||
|
||||
func jsonConfig(t *testing.T, s string) mapConfig {
|
||||
t.Helper()
|
||||
s = strings.NewReplacer("KEY_A", keyA, "KEY_B", keyB).Replace(s)
|
||||
var c mapConfig
|
||||
if err := json.Unmarshal([]byte(s), &c); err != nil {
|
||||
t.Fatalf("parse %s: %v", s, err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func newProvider(t *testing.T, c mapConfig) kms.KMSProvider {
|
||||
t.Helper()
|
||||
p, err := NewLocalKMSProvider(c)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLocalKMSProvider: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func wrap(t *testing.T, p kms.KMSProvider, keyID string) *kms.GenerateDataKeyResponse {
|
||||
t.Helper()
|
||||
resp, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{
|
||||
KeyID: keyID,
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
EncryptionContext: testContext,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDataKey(%q): %v", keyID, err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func hasCode(err error, code string) bool {
|
||||
var kmsErr *kms.KMSError
|
||||
return errors.As(err, &kmsErr) && kmsErr.Code == code
|
||||
}
|
||||
|
||||
func unwrap(t *testing.T, p kms.KMSProvider, resp *kms.GenerateDataKeyResponse) []byte {
|
||||
t.Helper()
|
||||
out, err := p.Decrypt(context.Background(), &kms.DecryptRequest{
|
||||
CiphertextBlob: resp.CiphertextBlob,
|
||||
EncryptionContext: testContext,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
return out.Plaintext
|
||||
}
|
||||
|
||||
func TestConfiguredKeySurvivesRestart(t *testing.T) {
|
||||
cfg := `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["customer-a"]}]}`
|
||||
|
||||
before := newProvider(t, jsonConfig(t, cfg))
|
||||
resp := wrap(t, before, "alias/customer-a")
|
||||
if resp.KeyID != "customer-a" {
|
||||
t.Fatalf("data key wrapped by %q, want customer-a", resp.KeyID)
|
||||
}
|
||||
plaintext := append([]byte(nil), resp.Plaintext...)
|
||||
before.Close()
|
||||
|
||||
after := newProvider(t, jsonConfig(t, cfg))
|
||||
if got := unwrap(t, after, resp); !bytes.Equal(got, plaintext) {
|
||||
t.Fatal("a new provider from the same config unwrapped a different data key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredKeysFromTOMLKeepTheirCase(t *testing.T) {
|
||||
v := viper.New()
|
||||
v.SetConfigType("toml")
|
||||
raw, _ := hex.DecodeString(keyB)
|
||||
toml := `
|
||||
[kms.providers.local]
|
||||
type = "local"
|
||||
|
||||
[[kms.providers.local.keys]]
|
||||
key_id = "Customer-A"
|
||||
key_material = "` + keyA + `"
|
||||
|
||||
[[kms.providers.local.keys]]
|
||||
key_id = "Customer-B"
|
||||
key_material = "` + base64.StdEncoding.EncodeToString(raw) + `"
|
||||
aliases = ["Customer-B"]
|
||||
`
|
||||
if err := v.ReadConfig(strings.NewReader(toml)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
providers := v.GetStringMap("kms")["providers"].(map[string]interface{})
|
||||
p := newProvider(t, mapConfig(providers["local"].(map[string]interface{})))
|
||||
|
||||
fromSub, err := NewLocalKMSProvider(v.Sub("kms.providers.local"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewLocalKMSProvider(viper): %v", err)
|
||||
}
|
||||
fromProxy, err := NewLocalKMSProvider(util.NewViperProxy(v.Sub("kms.providers.local")))
|
||||
if err != nil {
|
||||
t.Fatalf("NewLocalKMSProvider(proxy): %v", err)
|
||||
}
|
||||
|
||||
for name, p := range map[string]kms.KMSProvider{"map": p, "viper": fromSub, "proxy": fromProxy} {
|
||||
id, err := p.GetKeyID(context.Background(), "Customer-A")
|
||||
if err != nil || id != "Customer-A" {
|
||||
t.Fatalf("%s: GetKeyID(Customer-A) = %q, %v", name, id, err)
|
||||
}
|
||||
if resp := wrap(t, p, "alias/Customer-B"); resp.KeyID != "Customer-B" {
|
||||
t.Fatalf("%s: alias/Customer-B names %q, want Customer-B", name, resp.KeyID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandWithKeysIsRejectedFromTOML(t *testing.T) {
|
||||
v := viper.New()
|
||||
v.SetConfigType("toml")
|
||||
toml := `
|
||||
[kms.providers.local]
|
||||
type = "local"
|
||||
enableOnDemandCreate = true
|
||||
|
||||
[[kms.providers.local.keys]]
|
||||
key_id = "a"
|
||||
key_material = "` + keyA + `"
|
||||
`
|
||||
if err := v.ReadConfig(strings.NewReader(toml)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := v.GetStringMap("kms")["providers"].(map[string]interface{})["local"].(map[string]interface{})
|
||||
|
||||
manager := kms.GetKMSManager()
|
||||
const name = "local-toml-on-demand-test"
|
||||
if err := manager.AddKMSProvider(name, &kms.KMSConfig{Provider: "local", Config: cfg}); err == nil {
|
||||
manager.RemoveKMSProvider(name)
|
||||
t.Fatal("enableOnDemandCreate with keys accepted from TOML")
|
||||
}
|
||||
}
|
||||
|
||||
type plainConfig struct{}
|
||||
|
||||
func (plainConfig) GetString(string) string { return "" }
|
||||
func (plainConfig) GetBool(string) bool { return false }
|
||||
func (plainConfig) GetInt(string) int { return 0 }
|
||||
func (plainConfig) GetStringSlice(string) []string { return nil }
|
||||
func (plainConfig) SetDefault(key string, value interface{}) {}
|
||||
|
||||
func TestConfigWithoutKeyLookupIsRejected(t *testing.T) {
|
||||
if _, err := NewLocalKMSProvider(plainConfig{}); err == nil {
|
||||
t.Fatal("a configuration the keys can't be read from was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredKeysThroughKMSManager(t *testing.T) {
|
||||
cfg := jsonConfig(t, `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A"}]}`)
|
||||
manager := kms.GetKMSManager()
|
||||
const name = "local-configured-keys-test"
|
||||
if err := manager.AddKMSProvider(name, &kms.KMSConfig{Provider: "local", Config: cfg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer manager.RemoveKMSProvider(name)
|
||||
|
||||
p, err := manager.GetKMSProviderByName(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp := wrap(t, p, "customer-a"); resp.KeyID != "customer-a" {
|
||||
t.Fatalf("customer-a names %q", resp.KeyID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHexAndBase64NameTheSameKey(t *testing.T) {
|
||||
raw, _ := hex.DecodeString(keyA)
|
||||
fromHex := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}]}`))
|
||||
fromBase64 := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "`+base64.StdEncoding.EncodeToString(raw)+`"}]}`))
|
||||
|
||||
fromSecretFile := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A\n"}]}`))
|
||||
|
||||
resp := wrap(t, fromHex, "a")
|
||||
if got := unwrap(t, fromBase64, resp); !bytes.Equal(got, resp.Plaintext) {
|
||||
t.Fatal("hex and base64 forms of the same material gave different keys")
|
||||
}
|
||||
if got := unwrap(t, fromSecretFile, resp); !bytes.Equal(got, resp.Plaintext) {
|
||||
t.Fatal("hex material ending in a newline gave a different key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredKeysLeaveNoGeneratedFallback(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}]}`))
|
||||
|
||||
for _, keyID := range []string{"", "unknown"} {
|
||||
_, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{
|
||||
KeyID: keyID,
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
})
|
||||
if !hasCode(err, kms.ErrCodeNotFoundException) {
|
||||
t.Errorf("GenerateDataKey(%q) = %v, want NotFoundException", keyID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredAWSS3AliasServesRequestsNamingNoKey(t *testing.T) {
|
||||
cfg := `{"keys": [{"key_id": "a", "key_material": "KEY_A"}, {"key_id": "b", "key_material": "KEY_B", "aliases": ["aws/s3"]}]}`
|
||||
p := newProvider(t, jsonConfig(t, cfg))
|
||||
|
||||
for _, keyID := range []string{"", "alias/aws/s3"} {
|
||||
resp := wrap(t, p, keyID)
|
||||
if resp.KeyID != "b" {
|
||||
t.Errorf("GenerateDataKey(%q) wrapped by %q, want b", keyID, resp.KeyID)
|
||||
}
|
||||
if got := unwrap(t, newProvider(t, jsonConfig(t, cfg)), resp); !bytes.Equal(got, resp.Plaintext) {
|
||||
t.Errorf("GenerateDataKey(%q): a new provider from the same config unwrapped a different data key", keyID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClosedKeyWrapsNothing(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}]}`)).(*LocalKMSProvider)
|
||||
key, err := p.getKey("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Close()
|
||||
|
||||
if blob, err := p.encryptDataKey(make([]byte, 32), key, testContext); err == nil {
|
||||
t.Fatalf("a key closed after its lookup wrapped a data key: %s", blob)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidKeyConfig(t *testing.T) {
|
||||
short := base64.StdEncoding.EncodeToString(make([]byte, 16))
|
||||
cases := map[string]string{
|
||||
"missing key_id": `{"keys": [{"key_material": "KEY_A"}]}`,
|
||||
"alias as key_id": `{"keys": [{"key_id": "alias/a", "key_material": "KEY_A"}]}`,
|
||||
"missing key_material": `{"keys": [{"key_id": "a"}]}`,
|
||||
"short key_material": `{"keys": [{"key_id": "a", "key_material": "` + short + `"}]}`,
|
||||
"64 characters, not hex": `{"keys": [{"key_id": "a", "key_material": "` + strings.Repeat("g", 64) + `"}]}`,
|
||||
"not base64": `{"keys": [{"key_id": "a", "key_material": "not a key"}]}`,
|
||||
"duplicate key_id": `{"keys": [{"key_id": "a", "key_material": "KEY_A"}, {"key_id": "a", "key_material": "KEY_B"}]}`,
|
||||
"alias of another key": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": ["x"]}, {"key_id": "b", "key_material": "KEY_B", "aliases": ["alias/x"]}]}`,
|
||||
"alias listed twice": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": ["x", "alias/x"]}]}`,
|
||||
"keys not a list": `{"keys": {"a": "KEY_A"}}`,
|
||||
"aliases not strings": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": [1]}]}`,
|
||||
"empty alias": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": [""]}]}`,
|
||||
"blank alias": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": [" "]}]}`,
|
||||
"alias with spaces": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": ["x "]}]}`,
|
||||
"blank key_id": `{"keys": [{"key_id": " ", "key_material": "KEY_A"}]}`,
|
||||
"key_id with spaces": `{"keys": [{"key_id": " a", "key_material": "KEY_A"}]}`,
|
||||
"key_id not a string": `{"keys": [{"key_id": 1, "key_material": "KEY_A"}]}`,
|
||||
"material not a string": `{"keys": [{"key_id": "a", "key_material": 1}]}`,
|
||||
"on-demand with keys": `{"enableOnDemandCreate": true, "keys": [{"key_id": "a", "key_material": "KEY_A"}]}`,
|
||||
"empty keys": `{"keys": []}`,
|
||||
"material as key_id": `{"keys": [{"key_id": "KEY_A"}]}`,
|
||||
"material as key_id, newline": `{"keys": [{"key_id": "KEY_A\n", "key_material": "KEY_B"}]}`,
|
||||
"material as key_id, twice": `{"keys": [{"key_id": "KEY_A", "key_material": "KEY_B"}, {"key_id": "KEY_A", "key_material": "KEY_B"}]}`,
|
||||
"material as alias, twice": `{"keys": [{"key_id": "a", "key_material": "KEY_B", "aliases": ["KEY_A", "KEY_A"]}]}`,
|
||||
"material as alias key_id": `{"keys": [{"key_id": "alias/KEY_A", "key_material": "KEY_B"}]}`,
|
||||
}
|
||||
for name, cfg := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := NewLocalKMSProvider(jsonConfig(t, cfg))
|
||||
if err == nil {
|
||||
t.Fatal("config accepted")
|
||||
}
|
||||
if strings.Contains(err.Error(), keyA) || strings.Contains(err.Error(), keyB) {
|
||||
t.Fatalf("error carries key material: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedLoadClearsLoadedKeys(t *testing.T) {
|
||||
p := &LocalKMSProvider{keys: make(map[string]*LocalKey)}
|
||||
if err := p.loadConfig(jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}, {"key_id": "b", "key_material": "typo"}]}`)); err == nil {
|
||||
t.Fatal("config accepted")
|
||||
}
|
||||
if len(p.keys) != 0 {
|
||||
t.Fatalf("a failed load left %d keys in the provider", len(p.keys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusedKeyIsCleared(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}]}`)).(*LocalKMSProvider)
|
||||
material, _ := hex.DecodeString(keyB)
|
||||
if err := p.registerKey(newLocalKey("a", "", material, kms.KeyOriginExternal, nil)); err == nil {
|
||||
t.Fatal("a second key a was registered")
|
||||
}
|
||||
if !bytes.Equal(material, make([]byte, 32)) {
|
||||
t.Fatal("the refused key's material wasn't cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateKeyKeepsConfiguredAliases(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["a"]}]}`)).(*LocalKMSProvider)
|
||||
if _, err := p.CreateKey("test", []string{"a"}); err == nil {
|
||||
t.Fatal("CreateKey took an alias of a configured key")
|
||||
}
|
||||
if resp := wrap(t, p, "alias/a"); resp.KeyID != "customer-a" {
|
||||
t.Fatalf("alias/a names %q, want customer-a", resp.KeyID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateKeyWithIDRefusesTakenIDs(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "configured", "key_material": "KEY_A", "aliases": ["a"]}]}`)).(*LocalKMSProvider)
|
||||
if _, err := p.CreateKeyWithID("generated", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, keyID := range []string{"configured", "generated"} {
|
||||
if _, err := p.CreateKeyWithID(keyID, "test"); err == nil {
|
||||
t.Errorf("CreateKeyWithID took the key ID %q, which a key already has", keyID)
|
||||
}
|
||||
}
|
||||
if key, err := p.getKey("configured"); err != nil || key.Origin != kms.KeyOriginExternal {
|
||||
t.Fatalf("CreateKeyWithID replaced a configured key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandKeyIsNotReplaced(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)).(*LocalKMSProvider)
|
||||
resp := wrap(t, p, "bucket-key")
|
||||
|
||||
if _, err := p.createOnDemandKey("bucket-key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := unwrap(t, p, resp); !bytes.Equal(got, resp.Plaintext) {
|
||||
t.Fatal("a second create replaced the key a data key was wrapped under")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateKeyAliases(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{}`)).(*LocalKMSProvider)
|
||||
created, err := p.CreateKey("test", []string{"x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp := wrap(t, p, "alias/x"); resp.KeyID != created.KeyID {
|
||||
t.Fatalf("alias/x names %s, want %s", resp.KeyID, created.KeyID)
|
||||
}
|
||||
for _, alias := range []string{"", " ", "alias/"} {
|
||||
if _, err := p.CreateKey("test", []string{alias}); err == nil {
|
||||
t.Errorf("CreateKey took the alias %q", alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,6 +256,12 @@ func deepCopyValue(v interface{}) interface{} {
|
||||
out[i] = deepCopyValue(item)
|
||||
}
|
||||
return out
|
||||
case []map[string]interface{}:
|
||||
out := make([]map[string]interface{}, len(nested))
|
||||
for i, item := range nested {
|
||||
out[i] = deepCopyStringMap(item)
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return v
|
||||
}
|
||||
|
||||
@@ -45,6 +45,21 @@ func TestViperProxySerializesMapReadsAgainstWrites(t *testing.T) {
|
||||
assert.Contains(t, got, "a")
|
||||
}
|
||||
|
||||
// A list of tables set from code, rather than read from a file, must come back as a copy too.
|
||||
func TestGetStringMapCopiesListsOfTables(t *testing.T) {
|
||||
p := NewViperProxy(viper.New())
|
||||
p.Set("kms.keys", []map[string]interface{}{{"key_id": "a"}})
|
||||
|
||||
keys, ok := p.GetStringMap("kms")["keys"].([]map[string]interface{})
|
||||
if !assert.True(t, ok) {
|
||||
return
|
||||
}
|
||||
keys[0]["key_id"] = "b"
|
||||
|
||||
again := p.GetStringMap("kms")["keys"].([]map[string]interface{})
|
||||
assert.Equal(t, "a", again[0]["key_id"])
|
||||
}
|
||||
|
||||
// A proxy over its own viper serves the wrapped instance, for configuration
|
||||
// loaded from a source other than the shared one.
|
||||
func TestNewViperProxyWrapsGivenViper(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user