From b69076476b2d296657918df21749ec3f0a0dd2ae Mon Sep 17 00:00:00 2001 From: Tiago Posse Date: Fri, 4 Dec 2026 20:06:26 +0100 Subject: [PATCH] s3api: return KMS errors on SSE-KMS writes as their S3 error codes (#13379) * s3api: return KMS errors on SSE-KMS writes as their S3 error codes An SSE-KMS PutObject, UploadPart, UploadPartCopy or CopyObject naming a key the KMS doesn't have failed with 500 InternalError, and so did a plain upload to a bucket whose default encryption names one. MapKMSErrorToS3Error never saw these errors. The put path returned InternalError for every encryption failure. The copy path compared the mapper's result against InvalidRequest, which it never returns, so it answered InternalError for every error and its SSE-C check after it never ran. And the KMS calls wrapped the provider's error with %v, so its type was gone before any of them looked. Wrap the provider errors with %w, find the KMS error with errors.As, and map encryption failures on the put path, the bucket default put and the inline copy path. A missing key is now 400 KMSKeyNotFoundException, a disabled one 400 KMSKeyDisabledException, and errors that don't come from KMS stay 500. Co-Authored-By: Claude Opus 5.5 * s3api: map wrapped SSE-C errors to their S3 codes A destination SSE-C parse error reaches the copy error mapper wrapped with %w, so the exact-match switch missed it and the copy answered 500. Co-Authored-By: Claude Opus 5.5 * s3err: answer KMS key errors with the codes AWS S3 uses AWS S3 reports a missing SSE-KMS key as KMS.NotFoundException, a disabled one as KMS.DisabledException, and a denied KMS call as AccessDenied. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- weed/s3api/s3_sse_c.go | 14 +-- weed/s3api/s3_sse_kms.go | 12 +- weed/s3api/s3_sse_kms_error_codes_test.go | 107 ++++++++++++++++++ weed/s3api/s3_sse_kms_utils.go | 2 +- weed/s3api/s3api_object_handlers_copy.go | 2 +- .../s3api_object_handlers_copy_unified.go | 7 +- weed/s3api/s3api_object_handlers_put.go | 4 +- weed/s3api/s3api_put_handlers.go | 2 +- weed/s3api/s3err/s3api_errors.go | 6 +- 9 files changed, 132 insertions(+), 24 deletions(-) create mode 100644 weed/s3api/s3_sse_kms_error_codes_test.go diff --git a/weed/s3api/s3_sse_c.go b/weed/s3api/s3_sse_c.go index f1a647963d..24563674eb 100644 --- a/weed/s3api/s3_sse_c.go +++ b/weed/s3api/s3_sse_c.go @@ -328,18 +328,18 @@ func DetermineSSECCopyStrategy(srcMetadata map[string][]byte, copySourceKey *SSE // MapSSECErrorToS3Error maps SSE-C custom errors to S3 API error codes func MapSSECErrorToS3Error(err error) s3err.ErrorCode { - switch err { - case ErrInvalidEncryptionAlgorithm: + switch { + case errors.Is(err, ErrInvalidEncryptionAlgorithm): return s3err.ErrInvalidEncryptionAlgorithm - case ErrInvalidEncryptionKey: + case errors.Is(err, ErrInvalidEncryptionKey): return s3err.ErrInvalidEncryptionKey - case ErrSSECustomerKeyMD5Mismatch: + case errors.Is(err, ErrSSECustomerKeyMD5Mismatch): return s3err.ErrSSECustomerKeyMD5Mismatch - case ErrSSECustomerKeyMissing: + case errors.Is(err, ErrSSECustomerKeyMissing): return s3err.ErrSSECustomerKeyMissing - case ErrSSECustomerKeyNotNeeded: + case errors.Is(err, ErrSSECustomerKeyNotNeeded): return s3err.ErrSSECustomerKeyNotNeeded - case ErrSSECNotSupportedFIPS140: + case errors.Is(err, ErrSSECNotSupportedFIPS140): return s3err.ErrNotImplemented default: return s3err.ErrInvalidRequest diff --git a/weed/s3api/s3_sse_kms.go b/weed/s3api/s3_sse_kms.go index b79154c85d..59ed3f83d2 100644 --- a/weed/s3api/s3_sse_kms.go +++ b/weed/s3api/s3_sse_kms.go @@ -9,6 +9,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -199,7 +200,7 @@ func getBucketDataKey(bucketName, keyID string, encryptionContext map[string]str ctx := context.Background() dataKeyResp, err := kmsProvider.GenerateDataKey(ctx, dataKeyReq) if err != nil { - return nil, fmt.Errorf("failed to generate bucket data key: %v", err) + return nil, fmt.Errorf("failed to generate bucket data key: %w", err) } // Cache the data key for future use if cache is available @@ -251,7 +252,7 @@ func (s3a *S3ApiServer) CreateSSEKMSEncryptedReaderForBucket(r io.Reader, bucket ctx := context.Background() dataKeyResp, err = kmsProvider.GenerateDataKey(ctx, dataKeyReq) if err != nil { - return nil, nil, fmt.Errorf("failed to generate data key: %v", err) + return nil, nil, fmt.Errorf("failed to generate data key: %w", err) } } @@ -360,7 +361,7 @@ func CreateSSEKMSDecryptedReader(r io.Reader, sseKey *SSEKMSKey) (io.Reader, err ctx := context.Background() decryptResp, err := kmsProvider.Decrypt(ctx, decryptReq) if err != nil { - return nil, fmt.Errorf("failed to decrypt data key: %v", err) + return nil, fmt.Errorf("failed to decrypt data key: %w", err) } // Ensure we clear the plaintext data key from memory when done @@ -653,9 +654,8 @@ func MapKMSErrorToS3Error(err error) s3err.ErrorCode { return s3err.ErrNone } - // Check if it's a KMS error - kmsErr, ok := err.(*kms.KMSError) - if !ok { + var kmsErr *kms.KMSError + if !errors.As(err, &kmsErr) { return s3err.ErrInternalError } diff --git a/weed/s3api/s3_sse_kms_error_codes_test.go b/weed/s3api/s3_sse_kms_error_codes_test.go new file mode 100644 index 0000000000..59b63e028e --- /dev/null +++ b/weed/s3api/s3_sse_kms_error_codes_test.go @@ -0,0 +1,107 @@ +package s3api + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "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/spf13/viper" + "github.com/stretchr/testify/require" +) + +// setupKMSWithoutOnDemandKeys loads a local KMS that refuses key IDs it doesn't hold. +func setupKMSWithoutOnDemandKeys(t *testing.T) { + t.Helper() + config := viper.New() + config.Set("enableOnDemandCreate", false) + provider, err := local.NewLocalKMSProvider(config) + require.NoError(t, err) + kms.SetGlobalKMSProvider(provider) + t.Cleanup(func() { + kms.SetGlobalKMSProvider(nil) + require.NoError(t, provider.Close()) + }) +} + +func TestSSEKMSPutWithAnUnknownKeyIsKMSKeyNotFound(t *testing.T) { + setupKMSWithoutOnDemandKeys(t) + util_http.InitGlobalHttpClient() + filer := &ambiguousPutFiler{volume: startFakeVolumeServer(t), apply: true, entries: map[string]*filer_pb.Entry{}} + s3a := newPutTestServer(t, startFakeFiler(t, filer)) + s3a.bucketConfigCache.Set("default", &BucketConfig{Name: "default", + Encryption: &s3_pb.EncryptionConfiguration{SseAlgorithm: "aws:kms", KmsKeyId: "unknown"}}) + explicit := httptest.NewRequest(http.MethodPut, "/b/o", nil) + explicit.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms") + explicit.Header.Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, "unknown") + + for bucket, r := range map[string]*http.Request{ + "b": explicit, + "default": httptest.NewRequest(http.MethodPut, "/default/o", nil), + } { + r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "o"}) + _, code, _ := s3a.putToFiler(r, "/buckets/"+bucket+"/o", strings.NewReader("data"), bucket, "o", 1, 0, nil, false, "") + require.Equal(t, s3err.ErrKMSKeyNotFound, code, bucket) + } +} + +func TestSSEKMSCopyWithAnUnknownKeyIsKMSKeyNotFound(t *testing.T) { + setupKMSWithoutOnDemandKeys(t) + util_http.InitGlobalHttpClient() + sourceFid := fmt.Sprintf("3,%016x%08x", 100, 100) + for name, source := range map[string]*filer_pb.Entry{ + "chunked source": {Name: "source", Chunks: []*filer_pb.FileChunk{{FileId: sourceFid, Size: 4}}, + Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4}}, + "empty source": {Name: "source", Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode}}, + } { + t.Run(name, func(t *testing.T) { + volume := startFakeVolumeServer(t) + volume.stored[sourceFid] = []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) + filer.entries["/buckets/b"] = &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + filer.entries["/buckets/b/source"] = source + + req := httptest.NewRequest(http.MethodPut, "http://s3/b/destination", nil) + req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": "destination"}) + req.Header.Set("X-Amz-Copy-Source", "/b/source") + req.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms") + req.Header.Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, "unknown") + rr := httptest.NewRecorder() + s3a.CopyObjectHandler(rr, req) + + require.Contains(t, rr.Body.String(), "KMS.NotFoundException") + filer.mu.Lock() + defer filer.mu.Unlock() + require.Nil(t, filer.entries["/buckets/b/destination"]) + }) + } +} + +func TestMapCopyErrorMapsKMSAndSSECErrors(t *testing.T) { + s3a := &S3ApiServer{} + for _, tt := range []struct { + err error + want s3err.ErrorCode + }{ + {fmt.Errorf("copy chunk: %w", &kms.KMSError{Code: kms.ErrCodeNotFoundException}), s3err.ErrKMSKeyNotFound}, + {fmt.Errorf("copy chunk: %w", &kms.KMSError{Code: kms.ErrCodeKeyUnavailable}), s3err.ErrKMSDisabled}, + {fmt.Errorf("copy chunk: %w", &kms.KMSError{Code: kms.ErrCodeKMSInternalFailure}), s3err.ErrInternalError}, + {ErrSSECustomerKeyMissing, s3err.ErrSSECustomerKeyMissing}, + {fmt.Errorf("failed to parse destination SSE-C headers: %w", ErrInvalidEncryptionKey), s3err.ErrInvalidEncryptionKey}, + {fmt.Errorf("copy chunk: failed"), s3err.ErrInternalError}, + } { + require.Equal(t, tt.want, s3a.mapCopyErrorToS3Error(tt.err), tt.err.Error()) + } +} diff --git a/weed/s3api/s3_sse_kms_utils.go b/weed/s3api/s3_sse_kms_utils.go index 41c9a45627..3ef41e7869 100644 --- a/weed/s3api/s3_sse_kms_utils.go +++ b/weed/s3api/s3_sse_kms_utils.go @@ -62,7 +62,7 @@ func generateKMSDataKey(keyID string, encryptionContext map[string]string) (*KMS // Generate the data key dataKeyResp, err := kmsProvider.GenerateDataKey(context.Background(), generateDataKeyReq) if err != nil { - return nil, fmt.Errorf("failed to generate KMS data key: %v", err) + return nil, fmt.Errorf("failed to generate KMS data key: %w", err) } // Create AES cipher with the plaintext data key diff --git a/weed/s3api/s3api_object_handlers_copy.go b/weed/s3api/s3api_object_handlers_copy.go index 6d19287d02..a1949a4802 100644 --- a/weed/s3api/s3api_object_handlers_copy.go +++ b/weed/s3api/s3api_object_handlers_copy.go @@ -642,7 +642,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request dstWantsSSEC, dstWantsSSEKMS, dstWantsSSES3) if inlineErr != nil { glog.Errorf("CopyObjectHandler inline content error: %v", inlineErr) - keepAlive.writeError(s3err.ErrInternalError) + keepAlive.writeError(s3a.mapCopyErrorToS3Error(inlineErr)) return } dstEntry.Content = inlineContent diff --git a/weed/s3api/s3api_object_handlers_copy_unified.go b/weed/s3api/s3api_object_handlers_copy_unified.go index c47d21a3f5..88cdfdf625 100644 --- a/weed/s3api/s3api_object_handlers_copy_unified.go +++ b/weed/s3api/s3api_object_handlers_copy_unified.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/kms" "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" @@ -93,9 +94,9 @@ func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode { return s3err.ErrTooManyRequest } - // Check for KMS errors first - if kmsErr := MapKMSErrorToS3Error(err); kmsErr != s3err.ErrInvalidRequest { - return kmsErr + var kmsErr *kms.KMSError + if errors.As(err, &kmsErr) { + return MapKMSErrorToS3Error(err) } // Check for SSE-C errors diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index ce15744bf8..cd0115dae8 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -786,7 +786,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader encryptionResult, applyErr := s3a.applyBucketDefaultEncryption(bucket, r, dataReader) if applyErr != nil { glog.Errorf("Failed to apply bucket default encryption: %v", applyErr) - return "", s3err.ErrInternalError, SSEResponseMetadata{} + return "", MapKMSErrorToS3Error(applyErr), SSEResponseMetadata{} } // Update variables based on the result @@ -2644,7 +2644,7 @@ func (s3a *S3ApiServer) applySSEKMSDefaultEncryption(bucket string, r *http.Requ // Create SSE-KMS encrypted reader encryptedReader, sseKey, encErr := CreateSSEKMSEncryptedReaderWithBucketKey(dataReader, keyID, encryptionContext, bucketKeyEnabled) if encErr != nil { - return nil, fmt.Errorf("failed to create SSE-KMS encrypted reader for default encryption: %v", encErr) + return nil, fmt.Errorf("failed to create SSE-KMS encrypted reader for default encryption: %w", encErr) } glog.V(3).Infof("applySSEKMSDefaultEncryption: applied SSE-KMS default encryption with key ID: %s", keyID) diff --git a/weed/s3api/s3api_put_handlers.go b/weed/s3api/s3api_put_handlers.go index 0b3a0b5f40..2ec8a87c08 100644 --- a/weed/s3api/s3api_put_handlers.go +++ b/weed/s3api/s3api_put_handlers.go @@ -106,7 +106,7 @@ func (s3a *S3ApiServer) handleSSEKMSEncryption(r *http.Request, dataReader io.Re if encErr != nil { glog.Errorf("handleSSEKMSEncryption: encryption failed: %v", encErr) - return nil, nil, nil, s3err.ErrInternalError + return nil, nil, nil, MapKMSErrorToS3Error(encErr) } glog.V(3).Infof("handleSSEKMSEncryption: encryption successful, keyID=%s", keyID) diff --git a/weed/s3api/s3err/s3api_errors.go b/weed/s3api/s3err/s3api_errors.go index 1509daadd4..342f846b76 100644 --- a/weed/s3api/s3err/s3api_errors.go +++ b/weed/s3api/s3err/s3api_errors.go @@ -720,17 +720,17 @@ var errorCodeResponse = map[ErrorCode]APIError{ // SSE-KMS error responses ErrKMSKeyNotFound: { - Code: "KMSKeyNotFoundException", + Code: "KMS.NotFoundException", Description: "The specified KMS key does not exist.", HTTPStatusCode: http.StatusBadRequest, }, ErrKMSAccessDenied: { - Code: "KMSAccessDeniedException", + Code: "AccessDenied", Description: "Access denied to the specified KMS key.", HTTPStatusCode: http.StatusForbidden, }, ErrKMSDisabled: { - Code: "KMSKeyDisabledException", + Code: "KMS.DisabledException", Description: "The specified KMS key is disabled.", HTTPStatusCode: http.StatusBadRequest, },