Files
seaweedfs/weed/s3api/s3_sse_kms_default_key_test.go
T
d84235e74f s3api: encrypt SSE-KMS requests that name no key with alias/aws/s3 (#13378)
* s3api: encrypt SSE-KMS requests that name no key with alias/aws/s3

AWS encrypts an SSE-KMS request that sends no key ID with the aws/s3
managed key. PutObject, UploadPart and CreateMultipartUpload passed the
empty key ID on, and the KMS call rejected it, so the request failed
with 500. A bucket default of aws:kms without a key failed the same way
for multipart uploads.

CopyObject was worse: its copy paths read an empty key ID as no
SSE-KMS, stored the data unencrypted or under the source key, and
marked the object as SSE-KMS, so reading it back returned garbage.

Resolve an empty key ID to alias/aws/s3 wherever a request or a bucket
default is read, with the helper the bucket default uploads and copies
already had inline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: re-encrypt an in-place SSE-KMS copy that changes the key

The key-rotation strategy handed back the source chunks for an in-place
SSE-KMS copy, so an object copied onto itself under another key, or
under alias/aws/s3 when the request names none, stayed encrypted under
the old key. Route it through the re-encrypt copy, which already keeps
the same-key case direct.

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>
2026-12-04 11:33:51 -08:00

148 lines
6.5 KiB
Go

package s3api
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/kms"
"github.com/seaweedfs/seaweedfs/weed/kms/local"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/stretchr/testify/require"
)
// setupAWSManagedKMSKey loads a local KMS with a key aliased aws/s3 and returns its ID.
func setupAWSManagedKMSKey(t *testing.T) string {
t.Helper()
provider, err := local.NewLocalKMSProvider(nil)
require.NoError(t, err)
kms.SetGlobalKMSProvider(provider)
t.Cleanup(func() {
kms.SetGlobalKMSProvider(nil)
require.NoError(t, provider.Close())
})
key, err := provider.(*local.LocalKMSProvider).CreateKey("aws/s3", []string{"aws/s3"})
require.NoError(t, err)
return key.KeyID
}
func requireSSEKMSPlaintext(t *testing.T, ciphertext []byte, sseKey *SSEKMSKey, want string) {
t.Helper()
decrypted, err := CreateSSEKMSDecryptedReader(bytes.NewReader(ciphertext), sseKey)
require.NoError(t, err)
plaintext, err := io.ReadAll(decrypted)
require.NoError(t, err)
require.Equal(t, want, string(plaintext))
}
func TestSSEKMSPutWithoutAKeyIDUsesTheAWSManagedKey(t *testing.T) {
keyID := setupAWSManagedKMSKey(t)
r := httptest.NewRequest(http.MethodPut, "/b/o", nil)
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "o"})
r.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms")
encrypted, sseKey, _, code := (&S3ApiServer{}).handleSSEKMSEncryption(r, strings.NewReader("data"), 0)
require.Equal(t, s3err.ErrNone, code)
require.Equal(t, keyID, sseKey.KeyID)
ciphertext, err := io.ReadAll(encrypted)
require.NoError(t, err)
requireSSEKMSPlaintext(t, ciphertext, sseKey, "data")
}
func TestSSEKMSMultipartUploadWithoutAKeyIDUsesTheAWSManagedKey(t *testing.T) {
s3a := &S3ApiServer{bucketConfigCache: NewBucketConfigCache(time.Minute)}
s3a.bucketConfigCache.Set("default", &BucketConfig{Name: "default", Encryption: &s3_pb.EncryptionConfiguration{SseAlgorithm: "aws:kms"}})
explicit := httptest.NewRequest(http.MethodPost, "/explicit/o?uploads", nil)
explicit.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms")
for bucket, r := range map[string]*http.Request{
"explicit": explicit,
"default": httptest.NewRequest(http.MethodPost, "/default/o?uploads", nil),
} {
config, err := s3a.prepareMultipartEncryptionConfig(r, bucket, "upload")
require.NoError(t, err, bucket)
require.True(t, config.IsSSEKMS, bucket)
require.Equal(t, s3_constants.SSEKMSDefaultKeyID, config.KMSKeyID, bucket)
}
}
func TestSSEKMSCopyWithoutAKeyIDEncryptsWithTheAWSManagedKey(t *testing.T) {
keyID := setupAWSManagedKMSKey(t)
util_http.InitGlobalHttpClient()
put := httptest.NewRequest(http.MethodPut, "/b/source", nil)
put = mux.SetURLVars(put, map[string]string{"bucket": "b", "object": "source"})
put.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms")
put.Header.Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, "other-key")
encrypted, otherKey, otherKeyMetadata, code := (&S3ApiServer{}).handleSSEKMSEncryption(put, strings.NewReader("data"), 0)
require.Equal(t, s3err.ErrNone, code)
ciphertext, err := io.ReadAll(encrypted)
require.NoError(t, err)
sourceFid := fmt.Sprintf("3,%016x%08x", 100, 100)
underOtherKey := map[string][]byte{
s3_constants.SeaweedFSSSEKMSKey: otherKeyMetadata,
s3_constants.AmzServerSideEncryption: []byte(s3_constants.SSEAlgorithmKMS),
s3_constants.AmzServerSideEncryptionAwsKmsKeyId: []byte(otherKey.KeyID),
}
otherKeyChunk := &filer_pb.FileChunk{FileId: sourceFid, Size: 4, SseType: filer_pb.SSEType_SSE_KMS, SseMetadata: otherKeyMetadata}
for name, source := range map[string]struct {
data []byte
chunk *filer_pb.FileChunk
extended map[string][]byte
destination string
}{
"plain source": {data: []byte("data"), chunk: &filer_pb.FileChunk{FileId: sourceFid, Size: 4}, destination: "destination"},
"source under another key": {data: ciphertext, chunk: otherKeyChunk, extended: underOtherKey, destination: "destination"},
"source under another key, in place": {data: ciphertext, chunk: otherKeyChunk, extended: underOtherKey, destination: "source"},
} {
t.Run(name, func(t *testing.T) {
volume := startFakeVolumeServer(t)
volume.stored[sourceFid] = source.data
filer := &copyACLFiler{ambiguousPutFiler: &ambiguousPutFiler{volume: volume, apply: true, entries: map[string]*filer_pb.Entry{}}}
s3a := newPutTestServer(t, startFakeFiler(t, filer))
s3a.iam = NewIdentityAccessManagementWithStore(s3a.option, nil, "memory")
t.Cleanup(s3a.iam.Shutdown)
filer.entries["/buckets/b"] = &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
filer.entries["/buckets/b/source"] = &filer_pb.Entry{Name: "source", Chunks: []*filer_pb.FileChunk{source.chunk}, Extended: source.extended,
Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4, Mime: "text/plain"}}
req := httptest.NewRequest(http.MethodPut, "http://s3/b/"+source.destination, nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": source.destination})
req.Header.Set("X-Amz-Copy-Source", "/b/source")
req.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms")
if source.destination == "source" {
req.Header.Set(s3_constants.AmzUserMetaDirective, DirectiveReplace)
}
rr := httptest.NewRecorder()
s3a.CopyObjectHandler(rr, req)
require.Equal(t, http.StatusOK, rr.Code, rr.Body.String())
filer.mu.Lock()
stored := filer.entries["/buckets/b/"+source.destination]
filer.mu.Unlock()
require.NotNil(t, stored)
require.Len(t, stored.GetChunks(), 1)
sseKey, err := DeserializeSSEKMSMetadata(stored.Extended[s3_constants.SeaweedFSSSEKMSKey])
require.NoError(t, err)
require.Equal(t, keyID, sseKey.KeyID)
fid := stored.GetChunks()[0].GetFid()
volume.mu.Lock()
body := volume.stored[fmt.Sprintf("%d,%016x%08x", fid.GetVolumeId(), fid.GetFileKey(), fid.GetCookie())]
volume.mu.Unlock()
// The fake volume server keeps the raw multipart upload body.
boundary, _, _ := bytes.Cut(bytes.TrimPrefix(body, []byte("--")), []byte("\r\n"))
requireSSEKMSPlaintext(t, uploadedFile("multipart/form-data; boundary="+string(boundary), body), sseKey, "data")
})
}
}