diff --git a/weed/kms/local/local_kms.go b/weed/kms/local/local_kms.go index 05bff532e5..2910ab0cf0 100644 --- a/weed/kms/local/local_kms.go +++ b/weed/kms/local/local_kms.go @@ -8,6 +8,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "sort" @@ -400,7 +401,7 @@ func (p *LocalKMSProvider) GenerateDataKey(ctx context.Context, req *kms.Generat } // Resolve the key - key, err := p.getKey(req.KeyID) + key, err := p.getOrCreateKey(req.KeyID) if err != nil { return nil, err } @@ -534,7 +535,7 @@ func (p *LocalKMSProvider) Close() error { return nil } -// getKey retrieves a key by ID, alias or ARN, creating it on-demand if it doesn't exist +// getKey retrieves a key by ID, alias or ARN. func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) { name := keyName(keyIdentifier) // A key ARN names a key ID, never an alias its ID happens to spell. @@ -562,22 +563,6 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) { p.mu.RUnlock() - // Key doesn't exist - create on-demand if enabled and key identifier is reasonable - if keyIdentifier != "" && p.enableOnDemandCreate && p.isReasonableKeyIdentifier(name) { - glog.V(1).Infof("Creating on-demand local KMS key: %s", name) - key, err := p.createOnDemandKey(name) - if err != nil { - return nil, &kms.KMSError{ - Code: kms.ErrCodeKMSInternalFailure, - Message: fmt.Sprintf("Failed to create on-demand key %s: %v", name, err), - KeyID: keyIdentifier, - } - } - if namedKey(key) { - return key, nil - } - } - return nil, &kms.KMSError{ Code: kms.ErrCodeNotFoundException, Message: fmt.Sprintf("Key not found: %s", keyIdentifier), @@ -585,6 +570,31 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) { } } +// getOrCreateKey is getKey that creates a missing key on demand if enabled. Only new data +// keys create keys, as no other request can succeed with a key that didn't exist before it. +func (p *LocalKMSProvider) getOrCreateKey(keyIdentifier string) (*LocalKey, error) { + key, err := p.getKey(keyIdentifier) + name := keyName(keyIdentifier) + // A key ARN spelling an alias names no key, so it can't create one either. + keyARNOfAlias := strings.HasPrefix(keyIdentifier, localARNPrefix+"key/") && strings.HasPrefix(name, "alias/") + var kmsErr *kms.KMSError + if !errors.As(err, &kmsErr) || kmsErr.Code != kms.ErrCodeNotFoundException || + !p.enableOnDemandCreate || keyARNOfAlias || !p.isReasonableKeyIdentifier(name) { + return key, err + } + + glog.V(1).Infof("Creating on-demand local KMS key: %s", name) + key, err = p.createOnDemandKey(name) + if err != nil { + return nil, &kms.KMSError{ + Code: kms.ErrCodeKMSInternalFailure, + Message: fmt.Sprintf("Failed to create on-demand key %s: %v", name, err), + KeyID: name, + } + } + return key, nil +} + // isReasonableKeyIdentifier determines if a key identifier is reasonable for on-demand creation func (p *LocalKMSProvider) isReasonableKeyIdentifier(keyIdentifier string) bool { // Basic validation: reasonable length and character set @@ -776,23 +786,38 @@ func (p *LocalKMSProvider) addKey(key *LocalKey) (*LocalKey, error) { return key, nil } -// 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) { +// createOnDemandKey creates a key for a name no key has yet. An alias gets a key with a +// generated ID, as it would in AWS, rather than one whose ID is the alias. +func (p *LocalKMSProvider) createOnDemandKey(name string) (*LocalKey, error) { + keyID, aliases := name, []string{} + if strings.HasPrefix(name, "alias/") { + var err error + if keyID, err = generateKeyID(); err != nil { + return nil, err + } + aliases = []string{name} + } 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{}) + return p.storeKey(name, newLocalKey(keyID, fmt.Sprintf("Auto-created local KMS key: %s", name), keyMaterial, kms.KeyOriginLocal, aliases)) +} +// storeKey returns the key already stored under name rather than replacing it, as two +// on-demand requests for a new name can race and the first may have wrapped a data key +// already. +func (p *LocalKMSProvider) storeKey(name string, key *LocalKey) (*LocalKey, error) { p.mu.Lock() defer p.mu.Unlock() - if existing := p.keys[keyID]; existing != nil { - kms.ClearSensitiveData(keyMaterial) + + if existing := p.keys[name]; existing != nil { + kms.ClearSensitiveData(key.KeyMaterial) return existing, nil } - p.keys[keyID] = key + for _, n := range append([]string{key.KeyID}, key.Aliases...) { + p.keys[n] = key + } return key, nil } diff --git a/weed/kms/local/local_kms_test.go b/weed/kms/local/local_kms_test.go index 23d585259c..7317435493 100644 --- a/weed/kms/local/local_kms_test.go +++ b/weed/kms/local/local_kms_test.go @@ -165,6 +165,25 @@ key_material = "` + keyA + `" } } +func TestLookupsCreateNoKeys(t *testing.T) { + lost := wrap(t, newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)), "lost-key") + p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)).(*LocalKMSProvider) + before := len(p.keys) + + ctx := context.Background() + _, decryptErr := p.Decrypt(ctx, &kms.DecryptRequest{CiphertextBlob: lost.CiphertextBlob, EncryptionContext: testContext}) + _, describeErr := p.DescribeKey(ctx, &kms.DescribeKeyRequest{KeyID: "unknown"}) + _, keyIDErr := p.GetKeyID(ctx, "unknown") + for name, err := range map[string]error{"Decrypt": decryptErr, "DescribeKey": describeErr, "GetKeyID": keyIDErr} { + if !hasCode(err, kms.ErrCodeNotFoundException) { + t.Errorf("%s of an unknown key = %v, want NotFoundException", name, err) + } + } + if n := len(p.keys); n != before { + t.Errorf("lookups of unknown keys added %d keys", n-before) + } +} + type plainConfig struct{} func (plainConfig) GetString(string) string { return "" } @@ -395,6 +414,22 @@ func TestOnDemandKeyIsNotReplaced(t *testing.T) { } } +func TestOnDemandAliasGetsAGeneratedKeyID(t *testing.T) { + p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)) + for created, other := range map[string]string{ + "alias/bucket": "arn:aws:kms:local:000000000000:alias/bucket", + "arn:aws:kms:local:000000000000:alias/bucket-arn": "alias/bucket-arn", + } { + resp := wrap(t, p, created) + if strings.Contains(resp.KeyID, "bucket") { + t.Fatalf("%s created a key whose ID is taken from the alias: %s", created, resp.KeyID) + } + if got := wrap(t, p, other).KeyID; got != resp.KeyID { + t.Fatalf("%s names %s, want the key %s created, %s", other, got, created, resp.KeyID) + } + } +} + func TestCreateKeyAliases(t *testing.T) { p := newProvider(t, jsonConfig(t, `{}`)).(*LocalKMSProvider) created, err := p.CreateKey("test", []string{"arn:aws:kms:local:000000000000:alias/x"}) @@ -428,13 +463,22 @@ func TestCreateKeyWithIDTakesAnARN(t *testing.T) { } func TestKeyARNNamesNoAlias(t *testing.T) { - p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["a"]}]}`)) - _, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{ - KeyID: "arn:aws:kms:local:000000000000:key/alias/a", - KeySpec: kms.KeySpecAES256, - }) - if !hasCode(err, kms.ErrCodeNotFoundException) { - t.Fatalf("GenerateDataKey of a key ARN spelling an alias = %v, want NotFoundException", err) + for _, cfg := range []string{ + `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["a"]}]}`, + `{"enableOnDemandCreate": true}`, + } { + p := newProvider(t, jsonConfig(t, cfg)).(*LocalKMSProvider) + before := len(p.keys) + _, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{ + KeyID: "arn:aws:kms:local:000000000000:key/alias/a", + KeySpec: kms.KeySpecAES256, + }) + if !hasCode(err, kms.ErrCodeNotFoundException) { + t.Fatalf("%s: GenerateDataKey of a key ARN spelling an alias = %v, want NotFoundException", cfg, err) + } + if len(p.keys) != before { + t.Fatalf("%s: a key ARN spelling an alias created a key", cfg) + } } }