Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5617: fix(storage): disable request checksum in buffered S3 Upload (#6261)
it235eb14e73a20a6
diff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.goindex 74cd163519..ff9e0b6d48 100644--- a/server/internal/storage/s3.go+++ b/server/internal/storage/s3.go@@ -136,6 +136,65 @@ func parseBoolEnv(raw string) (bool, error) {}}+// awsEndpointDomains are the parent domains AWS serves S3 from. VPC, dualstack+// and FIPS hostnames all live under them, as does the China partition.+var awsEndpointDomains = []string{"amazonaws.com", "amazonaws.com.cn"}++// usesAWSEndpoint reports whether uploads go to real AWS S3 — either the+// default endpoint or an explicitly configured AWS one. The match is on the+// host label boundary, so "notamazonaws.com" and "s3.amazonaws.com.evil.net"+// are correctly treated as third-party endpoints.+func (s *S3Storage) usesAWSEndpoint() bool {+ if s.endpointURL == "" {+ return true+ }+ host := endpointHostname(s.endpointURL)+ for _, domain := range awsEndpointDomains {+ if host == domain || strings.HasSuffix(host, "."+domain) {+ return true+ }+ }+ return false+}++// endpointHostname extracts the comparable hostname from a configured+// endpoint: lowercased, without the port, and without a trailing root dot.+// A value written without a scheme is retried as an https URL, since+// url.Parse otherwise reads the whole thing as a path.+func endpointHostname(endpointURL string) string {+ parsed, err := url.Parse(endpointURL)+ if err != nil {+ return ""+ }+ if parsed.Hostname() == "" {+ parsed, err = url.Parse("https://" + endpointURL)+ if err != nil {+ return ""+ }+ }+ return strings.TrimSuffix(strings.ToLower(parsed.Hostname()), ".")+}++// uploadChecksumOptions returns the per-request options for the buffered+// upload path. The SDK defaults RequestChecksumCalculation to WhenSupported,+// which sends the body as aws-chunked with a CRC32 trailer; Aliyun OSS and+// Tencent COS do not implement that encoding and reject the request outright.+//+// Downgrading to WhenRequired drops the trailer, but it also drops the+// client-side checksum entirely, so it is applied only to non-AWS endpoints.+// Real AWS S3 accepts the trailer today, and buckets carrying a default Object+// Lock retention actually require a checksum, so those requests are left+// exactly as the SDK built them — including any AWS_REQUEST_CHECKSUM_CALCULATION+// the operator configured.+func (s *S3Storage) uploadChecksumOptions() []func(*s3.Options) {+ if s.usesAWSEndpoint() {+ return nil+ }+ return []func(*s3.Options){func(opts *s3.Options) {+ opts.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired+ }}+}+// storageClass returns the appropriate S3 storage class.// Custom endpoints (e.g. MinIO) only support STANDARD; real AWS defaults to INTELLIGENT_TIERING.func (s *S3Storage) storageClass() types.StorageClass {@@ -281,7 +340,7 @@ func (s *S3Storage) Upload(ctx context.Context, key string, data []byte, contentContentDisposition: aws.String(ContentDisposition(contentType, filename)),CacheControl: aws.String("max-age=432000,public"),StorageClass: s.storageClass(),- })+ }, s.uploadChecksumOptions()...)if err != nil {return "", fmt.Errorf("s3 PutObject: %w", err)}diff --git a/server/internal/storage/s3_test.go b/server/internal/storage/s3_test.goindex 58ecc029ad..af6f2d891f 100644--- a/server/internal/storage/s3_test.go+++ b/server/internal/storage/s3_test.go@@ -76,6 +76,192 @@ func TestS3StorageUploadStreamRejectsUnknownLength(t *testing.T) {}}+type observedChecksumRequest struct {+ contentSHA256 string+ trailer string+ checksumCRC32 string+ encoding string+ body string+}++// newChecksumRecordingServer records the checksum-relevant wire details of a+// single upload. TLS matters: the SDK only switches to a trailing checksum when+// the request is HTTPS (see the IsHTTPS gate in the checksum middleware), and+// production talks to OSS/S3 over HTTPS. A plain HTTP server would take the+// header-checksum branch instead and never reproduce the trailer.+func newChecksumRecordingServer(t *testing.T, observed chan<- observedChecksumRequest) *httptest.Server {+ t.Helper()+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("read request body: %v", err)+ }+ observed <- observedChecksumRequest{+ contentSHA256: r.Header.Get("X-Amz-Content-Sha256"),+ trailer: r.Header.Get("X-Amz-Trailer"),+ checksumCRC32: r.Header.Get("X-Amz-Checksum-Crc32"),+ encoding: r.Header.Get("Content-Encoding"),+ body: string(body),+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(server.Close)+ return server+}++// newChecksumTestStore points a store at the recording server. endpointURL is+// the field Upload branches on, so pass "" to exercise the default AWS shape+// and server.URL to exercise an S3-compatible backend.+func newChecksumTestStore(server *httptest.Server, endpointURL string) *S3Storage {+ return &S3Storage{+ client: s3.New(s3.Options{+ Region: "us-east-1",+ Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("AKID", "SECRET", "")),+ BaseEndpoint: aws.String(server.URL),+ UsePathStyle: true,+ HTTPClient: server.Client(),+ // NewS3StorageFromEnv builds its client through+ // config.LoadDefaultConfig, which resolves this to+ // WhenSupported. s3.New leaves it unset, and an unset value+ // emits no checksum at all — so without pinning the production+ // default here the test passes even with the fix removed.+ RequestChecksumCalculation: aws.RequestChecksumCalculationWhenSupported,+ }),+ bucket: "test-bucket",+ region: "us-east-1",+ endpointURL: endpointURL,+ usePathStyle: true,+ }+}++func TestS3StorageUploadPathsAvoidChecksumTrailer(t *testing.T) {+ newStore := func(server *httptest.Server) *S3Storage {+ return newChecksumTestStore(server, server.URL)+ }++ // S3-compatible backends such as Aliyun OSS and Tencent COS reject+ // aws-chunked framing outright, so neither upload path may emit a+ // trailing checksum.+ assertNoTrailer := func(t *testing.T, got observedChecksumRequest, payload string) {+ t.Helper()+ if got.contentSHA256 == "STREAMING-UNSIGNED-PAYLOAD-TRAILER" {+ t.Fatalf("x-amz-content-sha256 = %q, want a non-chunked value", got.contentSHA256)+ }+ if got.trailer != "" {+ t.Fatalf("x-amz-trailer = %q, want empty", got.trailer)+ }+ if got.checksumCRC32 != "" {+ t.Fatalf("x-amz-checksum-crc32 = %q, want empty", got.checksumCRC32)+ }+ if strings.Contains(got.encoding, "aws-chunked") {+ t.Fatalf("content-encoding = %q, want no aws-chunked framing", got.encoding)+ }+ if got.body != payload {+ t.Fatalf("request body = %q, want %q", got.body, payload)+ }+ }++ t.Run("buffered upload", func(t *testing.T) {+ observed := make(chan observedChecksumRequest, 1)+ server := newChecksumRecordingServer(t, observed)+ payload := "buffered payload"++ if _, err := newStore(server).Upload(+ context.Background(), "uploads/media.bin", []byte(payload),+ "application/octet-stream", "media.bin",+ ); err != nil {+ t.Fatalf("Upload: %v", err)+ }+ assertNoTrailer(t, <-observed, payload)+ })++ t.Run("streaming upload", func(t *testing.T) {+ observed := make(chan observedChecksumRequest, 1)+ server := newChecksumRecordingServer(t, observed)+ payload := "streamed payload"+ nonSeekable := io.LimitReader(strings.NewReader(payload), int64(len(payload)))++ if _, err := newStore(server).UploadStream(+ context.Background(), "uploads/media.bin", nonSeekable, int64(len(payload)),+ "application/octet-stream", "media.bin",+ ); err != nil {+ t.Fatalf("UploadStream: %v", err)+ }+ assertNoTrailer(t, <-observed, payload)+ })+}++// usesAWSEndpoint decides whether a request keeps the SDK's checksum trailer,+// so a wrong answer either reintroduces the OSS/COS failure or strips the+// checksum from an AWS bucket that requires one. Both directions have to hold+// on the host label boundary.+func TestS3StorageUsesAWSEndpoint(t *testing.T) {+ for _, tc := range []struct {+ endpointURL string+ want bool+ }{+ {"", true}, // unset: the SDK resolves the default AWS endpoint+ {"https://s3.us-east-1.amazonaws.com", true},+ {"https://S3.US-EAST-1.AMAZONAWS.COM", true},+ {"https://bucket.s3.us-east-1.amazonaws.com:443", true},+ {"https://bucket.s3.amazonaws.com.", true},+ {"https://bucket.vpce-0abc-xyz.s3.us-east-1.vpce.amazonaws.com", true},+ {"https://s3-fips.us-gov-west-1.amazonaws.com", true},+ {"https://s3.dualstack.us-east-1.amazonaws.com", true},+ {"https://s3.cn-north-1.amazonaws.com.cn", true},+ {"s3.us-east-1.amazonaws.com", true}, // scheme-less but still AWS++ {"https://oss-cn-shanghai-internal.aliyuncs.com", false},+ {"https://cos.ap-shanghai.myqcloud.com", false},+ {"https://notamazonaws.com", false},+ {"https://s3.amazonaws.com.example.net", false},+ {"https://minio.internal:9000?probe=amazonaws.com", false},+ {"https://minio.internal:9000/amazonaws.com", false},+ {"oss-cn-shanghai-internal.aliyuncs.com", false},+ } {+ t.Run(tc.endpointURL, func(t *testing.T) {+ s := &S3Storage{endpointURL: tc.endpointURL}+ if got := s.usesAWSEndpoint(); got != tc.want {+ t.Fatalf("usesAWSEndpoint(%q) = %v, want %v", tc.endpointURL, got, tc.want)+ }+ })+ }+}++// The OSS/COS workaround costs the request its client-side checksum, so it+// must not reach AWS: real AWS S3 accepts the aws-chunked trailer, and buckets+// carrying a default Object Lock retention require a checksum to be present.+// The store below is shaped the way NewS3StorageFromEnv leaves it when+// AWS_ENDPOINT_URL is unset; the client is pointed at a local TLS server only+// so the request can be observed.+func TestS3StorageAWSUploadKeepsChecksumTrailer(t *testing.T) {+ for _, endpointURL := range []string{+ "",+ "https://s3.us-east-1.amazonaws.com",+ } {+ t.Run("endpoint="+endpointURL, func(t *testing.T) {+ observed := make(chan observedChecksumRequest, 1)+ server := newChecksumRecordingServer(t, observed)+ payload := "buffered payload"++ if _, err := newChecksumTestStore(server, endpointURL).Upload(+ context.Background(), "uploads/media.bin", []byte(payload),+ "application/octet-stream", "media.bin",+ ); err != nil {+ t.Fatalf("Upload: %v", err)+ }++ got := <-observed+ if got.contentSHA256 != "STREAMING-UNSIGNED-PAYLOAD-TRAILER" {+ t.Fatalf("x-amz-content-sha256 = %q, want the SDK default trailer flow", got.contentSHA256)+ }+ if !strings.HasPrefix(got.trailer, "x-amz-checksum-") {+ t.Fatalf("x-amz-trailer = %q, want a checksum trailer", got.trailer)+ }+ })+ }+}+func TestS3StorageKeyFromURL_CustomEndpointPreservesNestedKey(t *testing.T) {s := &S3Storage{bucket: "test-bucket",