Files
seaweedFS/weed/s3api/auth_proxy_integration_test.go
blitt001 3d81d5bef7 Fix S3 signature verification behind reverse proxies (#8444)
* Fix S3 signature verification behind reverse proxies

When SeaweedFS is deployed behind a reverse proxy (e.g. nginx, Kong,
Traefik), AWS S3 Signature V4 verification fails because the Host header
the client signed with (e.g. "localhost:9000") differs from the Host
header SeaweedFS receives on the backend (e.g. "seaweedfs:8333").

This commit adds a new -s3.externalUrl parameter (and S3_EXTERNAL_URL
environment variable) that tells SeaweedFS what public-facing URL clients
use to connect. When set, SeaweedFS uses this host value for signature
verification instead of the Host header from the incoming request.

New parameter:
  -s3.externalUrl  (flag) or S3_EXTERNAL_URL (environment variable)
  Example: -s3.externalUrl=http://localhost:9000
  Example: S3_EXTERNAL_URL=https://s3.example.com

The environment variable is particularly useful in Docker/Kubernetes
deployments where the external URL is injected via container config.
The flag takes precedence over the environment variable when both are set.

At startup, the URL is parsed and default ports are stripped to match
AWS SDK behavior (port 80 for HTTP, port 443 for HTTPS), so
"http://s3.example.com:80" and "http://s3.example.com" are equivalent.

Bugs fixed:
- Default port stripping was removed by a prior PR, causing signature
  mismatches when clients connect on standard ports (80/443)
- X-Forwarded-Port was ignored when X-Forwarded-Host was not present
- Scheme detection now uses proper precedence: X-Forwarded-Proto >
  TLS connection > URL scheme > "http"
- Test expectations for standard port stripping were incorrect
- expectedHost field in TestSignatureV4WithForwardedPort was declared
  but never actually checked (self-referential test)

* Add Docker integration test for S3 proxy signature verification

Docker Compose setup with nginx reverse proxy to validate that the
-s3.externalUrl parameter (or S3_EXTERNAL_URL env var) correctly
resolves S3 signature verification when SeaweedFS runs behind a proxy.

The test uses nginx proxying port 9000 to SeaweedFS on port 8333,
with X-Forwarded-Host/Port/Proto headers set. SeaweedFS is configured
with -s3.externalUrl=http://localhost:9000 so it uses "localhost:9000"
for signature verification, matching what the AWS CLI signs with.

The test can be run with aws CLI on the host or without it by using
the amazon/aws-cli Docker image with --network host.

Test covers: create-bucket, list-buckets, put-object, head-object,
list-objects-v2, get-object, content round-trip integrity,
delete-object, and delete-bucket — all through the reverse proxy.

* Create s3-proxy-signature-tests.yml

* fix CLI

* fix CI

* Update s3-proxy-signature-tests.yml

* address comments

* Update Dockerfile

* add user

* no need for fuse

* Update s3-proxy-signature-tests.yml

* debug

* weed mini

* fix health check

* health check

* fix health checking

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-02-26 14:20:42 -08:00

213 lines
6.4 KiB
Go

package s3api
import (
"context"
"crypto/sha256"
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestReverseProxySignatureVerification is an integration test that exercises
// the full HTTP stack: real AWS SDK v4 signer -> real httputil.ReverseProxy ->
// real net/http server running IAM signature verification.
//
// This catches issues that unit tests miss: header normalization by net/http,
// proxy header injection, and real-world Host header handling.
func TestReverseProxySignatureVerification(t *testing.T) {
const (
accessKey = "AKIAIOSFODNN7EXAMPLE"
secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
)
configJSON := `{
"identities": [
{
"name": "test_user",
"credentials": [
{
"accessKey": "` + accessKey + `",
"secretKey": "` + secretKey + `"
}
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
}
]
}`
tests := []struct {
name string
externalUrl string // s3.externalUrl config for the backend
clientScheme string // scheme the client uses for signing
clientHost string // host the client signs against
proxyForwardsHost bool // whether proxy sets X-Forwarded-Host
expectSuccess bool
}{
{
name: "non-standard port, externalUrl matches proxy address",
externalUrl: "", // filled dynamically with proxy address
clientScheme: "http",
clientHost: "", // filled dynamically
proxyForwardsHost: true,
expectSuccess: true,
},
{
name: "externalUrl with non-standard port, client signs against external host",
externalUrl: "http://api.example.com:9000",
clientScheme: "http",
clientHost: "api.example.com:9000",
proxyForwardsHost: true,
expectSuccess: true,
},
{
name: "externalUrl with HTTPS default port stripped, client signs without port",
externalUrl: "https://api.example.com:443",
clientScheme: "https",
clientHost: "api.example.com",
proxyForwardsHost: true,
expectSuccess: true,
},
{
name: "externalUrl with HTTP default port stripped, client signs without port",
externalUrl: "http://api.example.com:80",
clientScheme: "http",
clientHost: "api.example.com",
proxyForwardsHost: true,
expectSuccess: true,
},
{
name: "proxy forwards X-Forwarded-Host correctly, no externalUrl needed",
externalUrl: "",
clientScheme: "http",
clientHost: "api.example.com:9000",
proxyForwardsHost: true,
expectSuccess: true,
},
{
name: "proxy without X-Forwarded-Host, no externalUrl: host mismatch",
externalUrl: "",
clientScheme: "http",
clientHost: "api.example.com:9000",
proxyForwardsHost: false,
expectSuccess: false,
},
{
name: "proxy without X-Forwarded-Host, externalUrl saves the day",
externalUrl: "http://api.example.com:9000",
clientScheme: "http",
clientHost: "api.example.com:9000",
proxyForwardsHost: false,
expectSuccess: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// --- Write config to temp file ---
tmpFile := t.TempDir() + "/s3.json"
require.NoError(t, os.WriteFile(tmpFile, []byte(configJSON), 0644))
// --- Set up backend ---
var iam *IdentityAccessManagement
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, errCode := iam.authRequest(r, "Read")
if errCode != 0 {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "error: %d", int(errCode))
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK")
}))
defer backend.Close()
// --- Set up reverse proxy ---
backendURL, _ := url.Parse(backend.URL)
proxy := httputil.NewSingleHostReverseProxy(backendURL)
forwardsHost := tt.proxyForwardsHost
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
originalHost := req.Host
originalScheme := req.URL.Scheme
if originalScheme == "" {
originalScheme = "http"
}
originalDirector(req)
// Simulate real proxy behavior: rewrite Host to backend address
// (nginx proxy_pass and Kong both do this by default)
req.Host = backendURL.Host
if forwardsHost {
req.Header.Set("X-Forwarded-Host", originalHost)
req.Header.Set("X-Forwarded-Proto", originalScheme)
}
}
proxyServer := httptest.NewServer(proxy)
defer proxyServer.Close()
// --- Configure IAM ---
externalUrl := tt.externalUrl
clientHost := tt.clientHost
clientScheme := tt.clientScheme
if externalUrl == "" && clientHost == "" {
// Dynamic: use the proxy's actual address
proxyURL, _ := url.Parse(proxyServer.URL)
externalUrl = proxyServer.URL
clientHost = proxyURL.Host
clientScheme = proxyURL.Scheme
}
option := &S3ApiServerOption{
Config: tmpFile,
ExternalUrl: externalUrl,
}
iam = NewIdentityAccessManagementWithStore(option, nil, "memory")
require.True(t, iam.isEnabled())
// --- Sign the request using real AWS SDK v4 signer ---
clientURL := fmt.Sprintf("%s://%s/test-bucket/test-object", clientScheme, clientHost)
req, err := http.NewRequest(http.MethodGet, clientURL, nil)
require.NoError(t, err)
req.Host = clientHost
signer := v4.NewSigner()
payloadHash := fmt.Sprintf("%x", sha256.Sum256([]byte{}))
err = signer.SignHTTP(
context.Background(),
aws.Credentials{AccessKeyID: accessKey, SecretAccessKey: secretKey},
req, payloadHash, "s3", "us-east-1", time.Now(),
)
require.NoError(t, err)
// --- Send the signed request through the proxy ---
// Rewrite destination to the proxy, but keep signed headers and Host intact
proxyURL, _ := url.Parse(proxyServer.URL)
req.URL.Scheme = proxyURL.Scheme
req.URL.Host = proxyURL.Host
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
if tt.expectSuccess {
assert.Equal(t, http.StatusOK, resp.StatusCode,
"Expected signature verification to succeed through reverse proxy")
} else {
assert.Equal(t, http.StatusForbidden, resp.StatusCode,
"Expected signature verification to fail (host mismatch)")
}
})
}
}