From ba4370183ac5da3b4763f20c8334e5e6e828fc82 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sat, 5 Dec 2026 11:01:40 -0800 Subject: [PATCH] s3api: keep the derived aws:s3:arn in a CopyObject SSE-KMS context (#13451) * s3api: keep the derived aws:s3:arn in a CopyObject SSE-KMS context ParseSSEKMSCopyHeaders took the destination context header verbatim, so a copy could carry no aws:s3:arn or name another bucket's ARN, and a KMS key policy conditioned on aws:s3:arn could be met that way. Without the header, the default context was built from the filer path, which made the ARN arn:aws:s3:::b//buckets/b/key. Build the destination context the way PutObject does: the derived ARN of the destination object plus the client's extra keys. Co-Authored-By: Claude Opus 5.5 * s3api: reject a CopyObject SSE-KMS context the KMS would refuse The copy validation only checked that the context header was non-empty, so a malformed context failed later, after the copy had started, with InternalError. Apply the same checks PutObject applies and answer InvalidRequest up front. Co-Authored-By: Claude Opus 5.5 * s3api: answer InvalidRequest when the destination KMS context is refused The derived aws:s3:arn of a destination key with a control character fails the KMS context checks, and the copy answered InternalError. Return it as a CopyValidationError and let the copy error mapping honor that type, so the client gets InvalidRequest as PutObject does. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/s3api/s3_sse_kms.go | 18 +-- weed/s3api/s3api_copy_validation.go | 9 +- ...i_object_handlers_copy_kms_context_test.go | 129 ++++++++++++++++++ .../s3api_object_handlers_copy_unified.go | 5 + 4 files changed, 144 insertions(+), 17 deletions(-) create mode 100644 weed/s3api/s3api_object_handlers_copy_kms_context_test.go diff --git a/weed/s3api/s3_sse_kms.go b/weed/s3api/s3_sse_kms.go index 1bd5526660..bf5f40e4b6 100644 --- a/weed/s3api/s3_sse_kms.go +++ b/weed/s3api/s3_sse_kms.go @@ -781,23 +781,17 @@ func ParseSSEKMSCopyHeaders(r *http.Request) (destKeyID string, encryptionContex return "", nil, false, fmt.Errorf("invalid KMS key ID: %s", destKeyID) } - // Parse encryption context if provided - if contextHeader := r.Header.Get(s3_constants.AmzServerSideEncryptionContext); contextHeader != "" { - contextBytes, decodeErr := base64.StdEncoding.DecodeString(contextHeader) - if decodeErr != nil { - return "", nil, false, fmt.Errorf("invalid encryption context encoding: %v", decodeErr) - } - - if unmarshalErr := json.Unmarshal(contextBytes, &encryptionContext); unmarshalErr != nil { - return "", nil, false, fmt.Errorf("invalid encryption context JSON: %v", unmarshalErr) - } - } - // Parse bucket key enabled flag if bucketKeyHeader := r.Header.Get(s3_constants.AmzServerSideEncryptionBucketKeyEnabled); bucketKeyHeader != "" { bucketKeyEnabled = strings.ToLower(bucketKeyHeader) == "true" } + dstBucket, dstObject := s3_constants.GetBucketAndObject(r) + encryptionContext, err = buildRequestEncryptionContext(dstBucket, dstObject, bucketKeyEnabled, r.Header.Get(s3_constants.AmzServerSideEncryptionContext)) + if err != nil { + return "", nil, false, &CopyValidationError{Code: s3err.ErrInvalidRequest, Message: err.Error()} + } + return destKeyID, encryptionContext, bucketKeyEnabled, nil } diff --git a/weed/s3api/s3api_copy_validation.go b/weed/s3api/s3api_copy_validation.go index 8c4cf47be3..430be30683 100644 --- a/weed/s3api/s3api_copy_validation.go +++ b/weed/s3api/s3api_copy_validation.go @@ -300,15 +300,14 @@ func hasSSECHeaders(headers http.Header) bool { s3_constants.AmzServerSideEncryptionCustomerKeyMD5) } -// validateEncryptionContext validates the encryption context header format +// validateEncryptionContext applies the checks the destination KMS call +// would apply to the context header. func validateEncryptionContext(contextHeader string) error { - // This would validate base64 encoding and JSON format - // Implementation would decode base64 and parse JSON - // For now, just check it's not empty if contextHeader == "" { return fmt.Errorf("encryption context cannot be empty") } - return nil + _, err := buildRequestEncryptionContext("", "", false, contextHeader) + return err } // ValidateCopySource validates the copy source path. diff --git a/weed/s3api/s3api_object_handlers_copy_kms_context_test.go b/weed/s3api/s3api_object_handlers_copy_kms_context_test.go new file mode 100644 index 0000000000..85899404ea --- /dev/null +++ b/weed/s3api/s3api_object_handlers_copy_kms_context_test.go @@ -0,0 +1,129 @@ +package s3api + +import ( + "encoding/base64" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + util_http "github.com/seaweedfs/seaweedfs/weed/util/http" + "github.com/stretchr/testify/require" +) + +func newCopyKMSContextTestServer(t *testing.T, source *filer_pb.Entry, bucketEncryption *s3_pb.EncryptionConfiguration) (*S3ApiServer, *copyACLFiler) { + t.Helper() + util_http.InitGlobalHttpClient() + volume := startFakeVolumeServer(t) + for _, chunk := range source.GetChunks() { + volume.stored[chunk.GetFileIdString()] = []byte("data") + } + filer := ©ACLFiler{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) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b", Encryption: bucketEncryption}) + filer.entries["/buckets/b"] = &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + filer.entries["/buckets/b/source"] = source + return s3a, filer +} + +func copyToDestination(s3a *S3ApiServer, destination string, headers map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPut, "http://s3/b/"+url.PathEscape(destination), nil) + req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": destination}) + req.Header.Set("X-Amz-Copy-Source", "/b/source") + for k, v := range headers { + req.Header.Set(k, v) + } + rr := httptest.NewRecorder() + s3a.CopyObjectHandler(rr, req) + return rr +} + +func TestCopyObjectSSEKMSContextKeepsTheDestinationARN(t *testing.T) { + kmsKey := SetupTestKMS(t) + t.Cleanup(kmsKey.Cleanup) + attributes := func() *filer_pb.FuseAttributes { + return &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4, Mime: "text/plain"} + } + chunked := func() *filer_pb.Entry { + return &filer_pb.Entry{Name: "source", Attributes: attributes(), + Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("3,%016x%08x", 100, 100), Size: 4}}} + } + explicit := map[string]string{ + s3_constants.AmzServerSideEncryption: "aws:kms", + s3_constants.AmzServerSideEncryptionAwsKmsKeyId: kmsKey.KeyID, + s3_constants.AmzServerSideEncryptionContext: base64.StdEncoding.EncodeToString([]byte(`{"aws:s3:arn":"arn:aws:s3:::other/o","team":"a"}`)), + } + for name, tc := range map[string]struct { + source *filer_pb.Entry + headers map[string]string + bucketEncryption *s3_pb.EncryptionConfiguration + want map[string]string + }{ + "chunked source": { + source: chunked(), + headers: explicit, + want: map[string]string{"aws:s3:arn": "arn:aws:s3:::b/destination", "team": "a"}, + }, + "inline source": { + source: &filer_pb.Entry{Name: "source", Attributes: attributes(), Content: []byte("data")}, + headers: explicit, + want: map[string]string{"aws:s3:arn": "arn:aws:s3:::b/destination", "team": "a"}, + }, + "bucket default": { + source: chunked(), + bucketEncryption: &s3_pb.EncryptionConfiguration{SseAlgorithm: "aws:kms", KmsKeyId: kmsKey.KeyID}, + want: map[string]string{"aws:s3:arn": "arn:aws:s3:::b/destination"}, + }, + } { + t.Run(name, func(t *testing.T) { + s3a, filer := newCopyKMSContextTestServer(t, tc.source, tc.bucketEncryption) + rr := copyToDestination(s3a, "destination", tc.headers) + require.Equal(t, http.StatusOK, rr.Code, rr.Body.String()) + + filer.mu.Lock() + stored := filer.entries["/buckets/b/destination"] + filer.mu.Unlock() + require.NotNil(t, stored) + sseKey, err := DeserializeSSEKMSMetadata(stored.Extended[s3_constants.SeaweedFSSSEKMSKey]) + require.NoError(t, err) + require.Equal(t, kmsKey.KeyID, sseKey.KeyID) + require.Equal(t, tc.want, sseKey.EncryptionContext) + }) + } +} + +func TestCopyObjectRejectsAContextTheKeyServiceRefuses(t *testing.T) { + kmsKey := SetupTestKMS(t) + t.Cleanup(kmsKey.Cleanup) + for name, tc := range map[string]struct { + destination string + contextHeader string + }{ + "not base64": {"destination", "not base64!"}, + "not JSON": {"destination", base64.StdEncoding.EncodeToString([]byte("team=a"))}, + "control character": {"destination", base64.StdEncoding.EncodeToString([]byte(`{"team":"a\tb"}`))}, + "control character in the destination key": {"dst\tkey", base64.StdEncoding.EncodeToString([]byte(`{"team":"a"}`))}, + } { + t.Run(name, func(t *testing.T) { + s3a, filer := newCopyKMSContextTestServer(t, &filer_pb.Entry{Name: "source", Content: []byte("data"), + Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4, Mime: "text/plain"}}, nil) + rr := copyToDestination(s3a, tc.destination, map[string]string{ + s3_constants.AmzServerSideEncryption: "aws:kms", + s3_constants.AmzServerSideEncryptionAwsKmsKeyId: kmsKey.KeyID, + s3_constants.AmzServerSideEncryptionContext: tc.contextHeader, + }) + require.Equal(t, http.StatusBadRequest, rr.Code, rr.Body.String()) + require.Contains(t, rr.Body.String(), "InvalidRequest") + filer.mu.Lock() + defer filer.mu.Unlock() + require.NotContains(t, filer.entries, "/buckets/b/"+tc.destination) + }) + } +} diff --git a/weed/s3api/s3api_object_handlers_copy_unified.go b/weed/s3api/s3api_object_handlers_copy_unified.go index 3cfa54257f..6bf9d36460 100644 --- a/weed/s3api/s3api_object_handlers_copy_unified.go +++ b/weed/s3api/s3api_object_handlers_copy_unified.go @@ -99,6 +99,11 @@ func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode { return ssecErr } + var validationErr *CopyValidationError + if errors.As(err, &validationErr) { + return validationErr.Code + } + // Default to internal error for unknown errors return s3err.ErrInternalError }