Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(storage): support GCS S3 XML API signing (MUL-8232) (#9513)
Lalit Madan4a0c147c5020
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex f96a1f48fa..e1df2bf930 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -136,6 +136,8 @@ Lorsque `S3_BUCKET` n'est pas défini, Multica utilise le disque local.| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | `auto`, `cloudfront`, `presign` ou `proxy` || `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | Durée de vie des URL de téléchargement signées |+Lorsque `AWS_ENDPOINT_URL` pointe vers Google Cloud Storage, `Accept-Encoding` est automatiquement exclu de la signature des requêtes.+Utilisez `ATTACHMENT_DOWNLOAD_MODE=proxy` lorsque le point de terminaison — un MinIO interne, par exemple — n'est pas accessible depuis le navigateur.### Disque localdiff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 6d8cb367bf..8572a51b25 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -136,6 +136,8 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | `auto`、`cloudfront`、`presign`、`proxy` || `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | 署名付きダウンロード URL の有効期間 |+`AWS_ENDPOINT_URL` が Google Cloud Storage を指す場合、`Accept-Encoding` はリクエスト署名から自動的に除外されます。+内部ネットワークの MinIO など、ブラウザから endpoint に直接到達できない場合は `ATTACHMENT_DOWNLOAD_MODE=proxy` を使ってください。### ローカルディスクdiff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex b8b41e27ee..42f17d9995 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -136,6 +136,8 @@ allowlist의 정확한 판단 순서는 [로그인과 가입](/auth-setup#가입| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | `auto`, `cloudfront`, `presign`, `proxy` 중 하나 || `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | 서명된 다운로드 주소의 유효 기간 |+`AWS_ENDPOINT_URL`이 Google Cloud Storage를 가리키면 `Accept-Encoding`이 요청 서명에서 자동으로 제외됩니다.+내부 네트워크의 MinIO처럼 브라우저에서 endpoint에 직접 접근할 수 없다면 `ATTACHMENT_DOWNLOAD_MODE=proxy`를 사용하세요.### 로컬 디스크diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex a5a093dca1..db44bcda35 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -136,6 +136,8 @@ When `S3_BUCKET` is unset, Multica uses local disk.| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | `auto`, `cloudfront`, `presign`, or `proxy` || `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | Lifetime of signed download URLs |+When `AWS_ENDPOINT_URL` points to Google Cloud Storage, `Accept-Encoding` is automatically excluded from request signing.+Use `ATTACHMENT_DOWNLOAD_MODE=proxy` when the endpoint — an internal MinIO, for example — is not reachable from the browser.### Local diskdiff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 3963919338..245ece0572 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -136,6 +136,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | `auto`、`cloudfront`、`presign` 或 `proxy` || `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | 签名下载地址的有效期 |+当 `AWS_ENDPOINT_URL` 指向 Google Cloud Storage 时,会自动将 `Accept-Encoding` 排除在请求签名之外。+内网 MinIO 等 endpoint 无法被浏览器直接访问时,使用 `ATTACHMENT_DOWNLOAD_MODE=proxy`。### 本地磁盘diff --git a/server/go.mod b/server/go.modindex af3e14b5cd..199b6289de 100644--- a/server/go.mod+++ b/server/go.mod@@ -8,6 +8,7 @@ require (github.com/aws/aws-sdk-go-v2/credentials v1.20.4github.com/aws/aws-sdk-go-v2/service/s3 v1.113.0github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.49.0+ github.com/aws/smithy-go v1.28.1github.com/go-chi/chi/v5 v5.3.2github.com/go-chi/cors v1.2.2github.com/go-redis/redismock/v9 v9.2.0@@ -53,7 +54,6 @@ require (github.com/aws/aws-sdk-go-v2/service/sso v1.38.0 // indirectgithub.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.0 // indirectgithub.com/aws/aws-sdk-go-v2/service/sts v1.50.0 // indirect- github.com/aws/smithy-go v1.28.1 // indirectgithub.com/beorn7/perks v1.0.1 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectdiff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.goindex a9057a222f..59fe74503d 100644--- a/server/internal/storage/s3.go+++ b/server/internal/storage/s3.go@@ -17,6 +17,8 @@ import ("github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/service/s3""github.com/aws/aws-sdk-go-v2/service/s3/types"+ "github.com/aws/smithy-go/middleware"+ smithyhttp "github.com/aws/smithy-go/transport/http")type S3Storage struct {@@ -86,6 +88,11 @@ func NewS3StorageFromEnv() *S3Storage {o.UsePathStyle = usePathStyle})}+ if isGCSEndpoint(endpointURL) {+ s3Opts = append(s3Opts, func(o *s3.Options) {+ o.APIOptions = append(o.APIOptions, excludeGCSAcceptEncoding)+ })+ }slog.Info("S3 storage initialized", "bucket", bucket, "region", region, "cdn_domain", cdnDomain, "endpoint_url", endpointURL, "use_path_style", usePathStyle)return &S3Storage{@@ -136,6 +143,52 @@ func parseBoolEnv(raw string) (bool, error) {}}+// isGCSEndpoint reports whether endpointURL points to Google Cloud Storage XML API.+func isGCSEndpoint(endpointURL string) bool {+ if endpointURL == "" {+ return false+ }+ host := endpointHostname(endpointURL)+ return host == "storage.googleapis.com" || strings.HasSuffix(host, ".storage.googleapis.com")+}++// excludeGCSAcceptEncoding keeps the header GCS rewrites out of the signature,+// while retaining the SDK's value on the wire to prevent automatic decompression.+func excludeGCSAcceptEncoding(stack *middleware.Stack) error {+ // Presigning replaces Signing and removes the SDK's Accept-Encoding middleware.+ if _, ok := stack.Finalize.Get("Signing"); !ok {+ return nil+ }++ // Values belong to this operation's stack; retry attempts run sequentially.+ var values []string+ if err := stack.Finalize.Insert(middleware.FinalizeMiddlewareFunc("RemoveGCSAcceptEncoding",+ func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) {+ req, ok := in.Request.(*smithyhttp.Request)+ if !ok {+ return middleware.FinalizeOutput{}, middleware.Metadata{}, fmt.Errorf("GCS signing: unexpected request type %T", in.Request)+ }+ values = req.Header.Values("Accept-Encoding")+ req.Header.Del("Accept-Encoding")+ return next.HandleFinalize(ctx, in)+ },+ ), "Signing", middleware.Before); err != nil {+ return err+ }+ return stack.Finalize.Insert(middleware.FinalizeMiddlewareFunc("RestoreGCSAcceptEncoding",+ func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) {+ req, ok := in.Request.(*smithyhttp.Request)+ if !ok {+ return middleware.FinalizeOutput{}, middleware.Metadata{}, fmt.Errorf("GCS signing: unexpected request type %T", in.Request)+ }+ if len(values) > 0 {+ req.Header["Accept-Encoding"] = values+ }+ return next.HandleFinalize(ctx, in)+ },+ ), "Signing", middleware.After)+}+// 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"}diff --git a/server/internal/storage/s3_test.go b/server/internal/storage/s3_test.goindex 00df0e4418..db4d452910 100644--- a/server/internal/storage/s3_test.go+++ b/server/internal/storage/s3_test.go@@ -1,16 +1,20 @@package storageimport (+ "bytes"+ "compress/gzip""context""io""net/http""net/http/httptest""net/url""strings"+ "sync""testing""time""github.com/aws/aws-sdk-go-v2/aws"+ "github.com/aws/aws-sdk-go-v2/aws/retry""github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/service/s3")@@ -611,3 +615,254 @@ func TestS3StorageUploadedURL(t *testing.T) {})}}++func TestIsGCSEndpoint(t *testing.T) {+ for _, tc := range []struct {+ endpoint string+ want bool+ }{+ {"https://storage.googleapis.com", true},+ {"https://bucket.storage.googleapis.com", true},+ {"https://STORAGE.GOOGLEAPIS.COM:443", true},+ {"https://storage.googleapis.com.", true},+ {"", false},+ {"https://s3.us-east-1.amazonaws.com", false},+ {"https://minio.example.com", false},+ {"https://storage.googleapis.com.attacker.example", false},+ {"https://notstorage.googleapis.com", false},+ {"https://example.com/storage.googleapis.com", false},+ {"https://example.com?endpoint=storage.googleapis.com", false},+ } {+ t.Run(tc.endpoint, func(t *testing.T) {+ if got := isGCSEndpoint(tc.endpoint); got != tc.want {+ t.Fatalf("isGCSEndpoint(%q) = %v, want %v", tc.endpoint, got, tc.want)+ }+ })+ }+}++// Keep the constructor's API options, but route requests to a local TLS server.+// Replacing HTTPClient also verifies that signing does not depend on a client wrapper.+func newS3SigningTestStore(t *testing.T, server *httptest.Server, endpoint string) *S3Storage {+ t.Helper()+ t.Setenv("S3_BUCKET", "test-bucket")+ t.Setenv("S3_REGION", "us-east-1")+ t.Setenv("AWS_ACCESS_KEY_ID", "AKID")+ t.Setenv("AWS_SECRET_ACCESS_KEY", "SECRET")+ t.Setenv("AWS_ENDPOINT_URL", endpoint)+ t.Setenv("S3_USE_PATH_STYLE", "true")+ store := NewS3StorageFromEnv()+ if store == nil {+ t.Fatal("NewS3StorageFromEnv() = nil")+ }+ opts := store.client.Options()+ opts.BaseEndpoint = aws.String(server.URL)+ opts.HTTPClient = server.Client()+ opts.Retryer = retry.NewStandard(func(o *retry.StandardOptions) {+ o.MaxAttempts = 2+ o.MaxBackoff = time.Millisecond+ })+ store.client = s3.New(opts)+ return store+}++func TestS3StorageGCSRequestSigning(t *testing.T) {+ payload := []byte("attachment contents")+ var compressed bytes.Buffer+ zw := gzip.NewWriter(&compressed)+ if _, err := zw.Write(payload); err != nil {+ t.Fatal(err)+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }++ for _, tc := range []struct {+ name string+ endpoint string+ unsigned bool+ }{+ {"GCS", "https://storage.googleapis.com", true},+ {"AWS", "", false},+ {"MinIO", "https://minio.example.com", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ type observedRequest struct {+ header http.Header+ body []byte+ }+ observed := make(chan observedRequest, 1)+ 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 <- observedRequest{header: r.Header.Clone(), body: body}+ if r.Method == http.MethodGet {+ w.Header().Set("Content-Encoding", "gzip")+ _, _ = w.Write(compressed.Bytes())+ } else if r.Method == http.MethodDelete {+ w.WriteHeader(http.StatusNoContent)+ }+ }))+ t.Cleanup(server.Close)+ store := newS3SigningTestStore(t, server, tc.endpoint)++ for _, operation := range []struct {+ name string+ run func(*testing.T)+ }{+ {"upload", func(t *testing.T) {+ if _, err := store.Upload(context.Background(), "file", payload, "application/octet-stream", "file"); err != nil {+ t.Fatal(err)+ }+ }},+ {"streaming upload", func(t *testing.T) {+ stream := io.LimitReader(bytes.NewReader(payload), int64(len(payload)))+ if _, err := store.UploadStream(context.Background(), "file", stream, int64(len(payload)), "application/octet-stream", "file"); err != nil {+ t.Fatal(err)+ }+ }},+ {"download", func(t *testing.T) {+ reader, err := store.GetReader(context.Background(), "file")+ if err != nil {+ t.Fatal(err)+ }+ defer reader.Close()+ got, err := io.ReadAll(reader)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(got, compressed.Bytes()) {+ t.Fatal("download changed gzip-encoded object bytes")+ }+ }},+ {"delete", func(t *testing.T) {+ if err := store.DeleteObject(context.Background(), "file"); err != nil {+ t.Fatal(err)+ }+ }},+ } {+ if !t.Run(operation.name, func(t *testing.T) {+ operation.run(t)+ got := <-observed+ auth := got.header.Get("Authorization")+ if auth == "" || !strings.Contains(auth, "x-amz-date") || !strings.Contains(auth, "x-amz-content-sha256") {+ t.Fatalf("required headers are not signed: %s", auth)+ }+ if signed := strings.Contains(auth, "accept-encoding"); signed == tc.unsigned {+ t.Fatalf("accept-encoding signed = %v, want %v", signed, !tc.unsigned)+ }+ if encoding := got.header.Get("Accept-Encoding"); encoding != "identity" {+ t.Fatalf("Accept-Encoding = %q, want identity", encoding)+ }+ if operation.name == "upload" || operation.name == "streaming upload" {+ if !strings.Contains(auth, "content-type") {+ t.Fatalf("content-type is not signed: %s", auth)+ }+ if tc.unsigned && !bytes.Equal(got.body, payload) {+ t.Fatal("GCS upload changed object bytes")+ }+ }+ }) {+ break+ }+ }+ })+ }+}++func TestS3StorageGCSOnlyExcludesAcceptEncoding(t *testing.T) {+ t.Setenv("S3_UNSIGNED_HEADERS", "content-type,x-amz-content-sha256")+ observed := make(chan string, 1)+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = io.Copy(io.Discard, r.Body)+ observed <- r.Header.Get("Authorization")+ }))+ t.Cleanup(server.Close)+ store := newS3SigningTestStore(t, server, "https://storage.googleapis.com")+ if _, err := store.Upload(context.Background(), "file", []byte("payload"), "text/plain", "file.txt"); err != nil {+ t.Fatal(err)+ }+ auth := <-observed+ for _, header := range []string{"content-type", "x-amz-content-sha256"} {+ if !strings.Contains(auth, header) {+ t.Errorf("environment variable removed %s from signature: %s", header, auth)+ }+ }+}++func TestS3StorageGCSPresign(t *testing.T) {+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Error("presigning must not send an HTTP request")+ }))+ t.Cleanup(server.Close)+ store := newS3SigningTestStore(t, server, "https://storage.googleapis.com")+ signedURL, err := store.PresignGet(context.Background(), "file", 5*time.Minute)+ if err != nil {+ t.Fatal(err)+ }+ u, err := url.Parse(signedURL)+ if err != nil {+ t.Fatal(err)+ }+ if got := u.Query().Get("X-Amz-SignedHeaders"); got != "host" {+ t.Fatalf("X-Amz-SignedHeaders = %q, want host", got)+ }+ if u.Query().Get("X-Amz-Signature") == "" {+ t.Fatal("missing presigned signature")+ }+}++func TestS3StorageGCSRetries(t *testing.T) {+ observed := make(chan http.Header, 2)+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = io.Copy(io.Discard, r.Body)+ observed <- r.Header.Clone()+ if len(observed) == 1 {+ w.WriteHeader(http.StatusInternalServerError)+ }+ }))+ t.Cleanup(server.Close)+ store := newS3SigningTestStore(t, server, "https://storage.googleapis.com")+ if _, err := store.Upload(context.Background(), "file", []byte("payload"), "text/plain", "file.txt"); err != nil {+ t.Fatal(err)+ }+ if got := len(observed); got != 2 {+ t.Fatalf("attempts = %d, want 2", got)+ }+ for range 2 {+ header := <-observed+ if auth := header.Get("Authorization"); auth == "" || strings.Contains(auth, "accept-encoding") {+ t.Fatalf("invalid retry signature: %s", auth)+ }+ if got := header.Get("Accept-Encoding"); got != "identity" {+ t.Fatalf("Accept-Encoding = %q, want identity", got)+ }+ }+}++func TestS3StorageGCSConcurrentRequests(t *testing.T) {+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Accept-Encoding"); got != "identity" {+ t.Errorf("Accept-Encoding = %q, want identity", got)+ }+ if auth := r.Header.Get("Authorization"); auth == "" || strings.Contains(auth, "accept-encoding") {+ t.Errorf("invalid concurrent request signature: %s", auth)+ }+ }))+ t.Cleanup(server.Close)+ store := newS3SigningTestStore(t, server, "https://storage.googleapis.com")+ var wg sync.WaitGroup+ for range 8 {+ wg.Go(func() {+ reader, err := store.GetReader(context.Background(), "file")+ if err != nil {+ t.Error(err)+ return+ }+ _ = reader.Close()+ })+ }+ wg.Wait()+}