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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <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:
authored and GitHub committed 2026-12-04 11:06:26 -08:00
1 parent 731431af72
commit b69076476b
9 files changed
+132 -24

No files matched your search

+7 -7
View File
@@ -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
+6 -6
View File
@@ -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
}
+107
View File
@@ -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 := &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"] = 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(), "<Code>KMS.NotFoundException</Code>")
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())
}
}
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
@@ -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
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
+3 -3
View File
@@ -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,
},