diff --git a/weed/s3api/auth_signature_v4.go b/weed/s3api/auth_signature_v4.go index 1c593aa4bb..9e9a04986b 100644 --- a/weed/s3api/auth_signature_v4.go +++ b/weed/s3api/auth_signature_v4.go @@ -613,18 +613,24 @@ func (iam *IdentityAccessManagement) vendedSessionKeyLive(owner, accessKey, fing // calculateAndVerifySignature contains the core logic for creating the canonical request, // string-to-sign, and comparing the final signature. func calculateAndVerifySignature(secretKey, method, urlPath, queryStr string, extractedSignedHeaders http.Header, authInfo *v4AuthInfo) (string, s3err.ErrorCode) { - canonicalRequest := getCanonicalRequest(extractedSignedHeaders, authInfo.HashedPayload, queryStr, urlPath, method) - stringToSign := getStringToSign(canonicalRequest, authInfo.Date, authInfo.Scope) signingKey := getSigningKey(secretKey, authInfo.Date.Format(yyyymmdd), authInfo.Region, authInfo.Service) - newSignature := getSignature(signingKey, stringToSign) - - if !compareSignatureV4(newSignature, authInfo.Signature) { - glog.V(4).Infof("Signature mismatch. Details:\n- CanonicalRequest: %q\n- StringToSign: %q\n- Calculated: %s, Provided: %s", - canonicalRequest, stringToSign, newSignature, authInfo.Signature) - return "", s3err.ErrSignatureDoesNotMatch + var canonicalRequest, stringToSign, newSignature string + for i, trim := range signV4HeaderValueTrims { + cr := getCanonicalRequest(extractedSignedHeaders, authInfo.HashedPayload, queryStr, urlPath, method, trim) + if i > 0 && cr == canonicalRequest { + continue // same canonical request, same signature + } + canonicalRequest = cr + stringToSign = getStringToSign(canonicalRequest, authInfo.Date, authInfo.Scope) + newSignature = getSignature(signingKey, stringToSign) + if compareSignatureV4(newSignature, authInfo.Signature) { + return newSignature, s3err.ErrNone + } } - return newSignature, s3err.ErrNone + glog.V(4).Infof("Signature mismatch. Details:\n- CanonicalRequest: %q\n- StringToSign: %q\n- Calculated: %s, Provided: %s", + canonicalRequest, stringToSign, newSignature, authInfo.Signature) + return "", s3err.ErrSignatureDoesNotMatch } func extractV4AuthInfo(r *http.Request) (*v4AuthInfo, s3err.ErrorCode) { @@ -1224,14 +1230,14 @@ func getScope(t time.Time, region string, service string) string { // \n // \n // -func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string) string { +func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string, trim func(string) string) string { rawQuery := strings.Replace(queryStr, "+", "%20", -1) encodedPath := encodePath(urlPath) canonicalRequest := strings.Join([]string{ method, encodedPath, rawQuery, - getCanonicalHeaders(extractedSignedHeaders), + getCanonicalHeaders(extractedSignedHeaders, trim), getSignedHeaders(extractedSignedHeaders), payload, }, "\n") @@ -1269,7 +1275,7 @@ func getSigningKey(secretKey string, time string, region string, service string) } // getCanonicalHeaders generate a list of request headers with their values -func getCanonicalHeaders(signedHeaders http.Header) string { +func getCanonicalHeaders(signedHeaders http.Header, trim func(string) string) string { var headers []string vals := make(http.Header) for k, vv := range signedHeaders { @@ -1288,18 +1294,32 @@ func getCanonicalHeaders(signedHeaders http.Header) string { if idx > 0 { buf.WriteByte(',') } - buf.WriteString(signV4TrimAll(v)) + buf.WriteString(trim(v)) } buf.WriteByte('\n') } return buf.String() } -// signV4TrimAll trims leading and trailing spaces from each string in the slice, and trims sequential spaces. +// SigV4 clients disagree on Trimall for whitespace other than the ASCII space, +// so a signature is checked against each client's form in turn. +var signV4HeaderValueTrims = []func(string) string{signV4TrimAll, signV4TrimAllASCIIWhitespace, signV4TrimAllWhitespace} + +// signV4TrimAll compresses sequential ASCII spaces in a header value to one and +// trims leading and trailing whitespace, as the AWS SDK for Go v2 does. func signV4TrimAll(input string) string { - // Compress adjacent spaces (a space is determined by - // unicode.IsSpace() internally here) to a single space and trim - // leading and trailing spaces. + return strings.TrimSpace(strings.Join(strings.FieldsFunc(input, func(r rune) bool { return r == ' ' }), " ")) +} + +// signV4TrimAllASCIIWhitespace turns every run of spaces and tabs into a single +// space and keeps other whitespace, as the AWS SDK for Java does. +func signV4TrimAllASCIIWhitespace(input string) string { + return strings.Join(strings.FieldsFunc(input, func(r rune) bool { return r == ' ' || r == '\t' }), " ") +} + +// signV4TrimAllWhitespace turns every run of whitespace into a single space and +// trims the edges, as botocore does. +func signV4TrimAllWhitespace(input string) string { return strings.Join(strings.Fields(input), " ") } diff --git a/weed/s3api/auth_signature_v4_test.go b/weed/s3api/auth_signature_v4_test.go index e5abf46606..6da6ceaf94 100644 --- a/weed/s3api/auth_signature_v4_test.go +++ b/weed/s3api/auth_signature_v4_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "slices" + "strings" "sync" "testing" "time" @@ -674,7 +675,7 @@ func TestExtractSignedHeadersCase(t *testing.T) { if errCode != s3err.ErrNone { t.Fatalf("extractSignedHeaders failed: %v", errCode) } - actual := getCanonicalHeaders(extracted) + actual := getCanonicalHeaders(extracted, signV4TrimAll) if actual != tt.expected { t.Errorf("%s: expected %q, got %q", tt.name, tt.expected, actual) } @@ -693,7 +694,7 @@ func TestExtractSignedHeadersContentLength(t *testing.T) { if errCode != s3err.ErrNone { t.Fatalf("extractSignedHeaders failed: %v", errCode) } - if got := getCanonicalHeaders(extracted); got != "content-length:0\nhost:bucket.domain.com\n" { + if got := getCanonicalHeaders(extracted, signV4TrimAll); got != "content-length:0\nhost:bucket.domain.com\n" { t.Fatalf("unexpected canonical headers %q", got) } } @@ -768,3 +769,59 @@ func TestSignatureV4WithForwardedPrefixUnicodeKey(t *testing.T) { t.Fatalf("signature verification failed for unicode key behind forwarded prefix: code %d", int(errCode)) } } + +func TestSignV4TrimAll(t *testing.T) { + tests := []struct { + in, sdkGoV2, sdkJava, botocore string + }{ + {" a b ", "a b", "a b", "a b"}, + {"plain", "plain", "plain", "plain"}, + {"tab\tkept", "tab\tkept", "tab kept", "tab kept"}, + {"at 2.20.09\u202fPM.png", "at 2.20.09\u202fPM.png", "at 2.20.09\u202fPM.png", "at 2.20.09 PM.png"}, + {"news\u00a0| headline.txt", "news\u00a0| headline.txt", "news\u00a0| headline.txt", "news | headline.txt"}, + {" report.txt\u00a0 ", "report.txt", "report.txt\u00a0", "report.txt"}, + {"at 2.20.09\u202fPM\tcopy.png", "at 2.20.09\u202fPM\tcopy.png", "at 2.20.09\u202fPM copy.png", "at 2.20.09 PM copy.png"}, + } + for _, tt := range tests { + if got := signV4TrimAll(tt.in); got != tt.sdkGoV2 { + t.Errorf("signV4TrimAll(%q) = %q, want %q", tt.in, got, tt.sdkGoV2) + } + if got := signV4TrimAllASCIIWhitespace(tt.in); got != tt.sdkJava { + t.Errorf("signV4TrimAllASCIIWhitespace(%q) = %q, want %q", tt.in, got, tt.sdkJava) + } + if got := signV4TrimAllWhitespace(tt.in); got != tt.botocore { + t.Errorf("signV4TrimAllWhitespace(%q) = %q, want %q", tt.in, got, tt.botocore) + } + } +} + +func TestCalculateAndVerifySignatureTrimVariants(t *testing.T) { + headers := http.Header{} + headers.Set("Host", "bucket.domain.com") + headers.Set("X-Amz-Meta-Filename", "at 2.20.09\u202fPM\tcopy.png") + date := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + const secret, payload = "secret", "UNSIGNED-PAYLOAD" + scope := getScope(date, "us-east-1", "s3") + signingKey := getSigningKey(secret, date.Format(yyyymmdd), "us-east-1", "s3") + + for name, trim := range map[string]func(string) string{ + "sdk-go-v2": signV4TrimAll, + "sdk-java-v2": signV4TrimAllASCIIWhitespace, + "botocore": signV4TrimAllWhitespace, + } { + t.Run(name, func(t *testing.T) { + canonical := getCanonicalRequest(headers, payload, "", "/bucket/key", http.MethodPut, trim) + signature := getSignature(signingKey, getStringToSign(canonical, date, scope)) + authInfo := &v4AuthInfo{HashedPayload: payload, Date: date, Scope: scope, Region: "us-east-1", Service: "s3", Signature: signature} + got, errCode := calculateAndVerifySignature(secret, http.MethodPut, "/bucket/key", "", headers, authInfo) + if errCode != s3err.ErrNone || got != signature { + t.Fatalf("got %q, %v; want %q", got, errCode, signature) + } + }) + } + + authInfo := &v4AuthInfo{HashedPayload: payload, Date: date, Scope: scope, Region: "us-east-1", Service: "s3", Signature: strings.Repeat("0", 64)} + if _, errCode := calculateAndVerifySignature(secret, http.MethodPut, "/bucket/key", "", headers, authInfo); errCode != s3err.ErrSignatureDoesNotMatch { + t.Fatalf("wrong signature: got %v, want ErrSignatureDoesNotMatch", errCode) + } +} diff --git a/weed/s3api/auth_signature_v4_unsigned_headers_test.go b/weed/s3api/auth_signature_v4_unsigned_headers_test.go index 49827a367b..540d449aa5 100644 --- a/weed/s3api/auth_signature_v4_unsigned_headers_test.go +++ b/weed/s3api/auth_signature_v4_unsigned_headers_test.go @@ -358,7 +358,7 @@ func preSignV4WithHeaders(_ *IdentityAccessManagement, req *http.Request, access } } - canonicalRequest := getCanonicalRequest(extracted, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method) + canonicalRequest := getCanonicalRequest(extracted, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method, signV4TrimAll) stringToSign := getStringToSign(canonicalRequest, now, scope) signingKey := getSigningKey(secretKey, now.Format(yyyymmdd), "us-east-1", "s3") signature := getSignature(signingKey, stringToSign) diff --git a/weed/s3api/auto_signature_v4_test.go b/weed/s3api/auto_signature_v4_test.go index 9d7c5a2729..1c86d773c9 100644 --- a/weed/s3api/auto_signature_v4_test.go +++ b/weed/s3api/auto_signature_v4_test.go @@ -271,7 +271,7 @@ func preSignV4(iam *IdentityAccessManagement, req *http.Request, accessKey, secr extractedSignedHeaders["host"] = []string{req.Host} // Get canonical request - canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method) + canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method, signV4TrimAll) // Get string to sign stringToSign := getStringToSign(canonicalRequest, now, scope) @@ -1033,7 +1033,7 @@ func preSignV4WithPath(iam *IdentityAccessManagement, req *http.Request, accessK extractedSignedHeaders["host"] = []string{extractHostHeader(req, "")} // Get canonical request with custom path - canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method) + canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method, signV4TrimAll) // Get string to sign stringToSign := getStringToSign(canonicalRequest, now, scope) @@ -1076,7 +1076,7 @@ func signV4WithPath(req *http.Request, accessKey, secretKey, urlPath string) { hashedPayload := getContentSha256Cksum(req) // Get canonical request with custom path - canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method) + canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method, signV4TrimAll) // Get string to sign stringToSign := getStringToSign(canonicalRequest, now, scope) diff --git a/weed/s3api/request_body_test.go b/weed/s3api/request_body_test.go index 673fdc3bc9..c0e2666888 100644 --- a/weed/s3api/request_body_test.go +++ b/weed/s3api/request_body_test.go @@ -245,7 +245,7 @@ func TestPrebufferedSignedBodyChecksContentMd5(t *testing.T) { "x-amz-date": {req.Header.Get("X-Amz-Date")}, } sum := sha256.Sum256(body) - canonical := getCanonicalRequest(signed, hex.EncodeToString(sum[:]), "", "/", http.MethodPost) + canonical := getCanonicalRequest(signed, hex.EncodeToString(sum[:]), "", "/", http.MethodPost, signV4TrimAll) signature := getSignature(getSigningKey("secret_key_1", now.Format(yyyymmdd), "us-east-1", "iam"), getStringToSign(canonical, now, scope)) req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=access_key_1/"+scope+", SignedHeaders=content-md5;content-type;host;x-amz-date, Signature="+signature) return req