Files
seaweedfs/weed/s3api/auth_no_such_bucket_test.go
T
05d9242f3c s3api: answer NoSuchBucket to a denied authenticated request on a missing bucket (#13139)
* s3api: optionally answer NoSuchBucket to a denied signed request on a missing bucket

## Problem

AWS S3 answers 404 NoSuchBucket to an authenticated caller that is denied on a bucket that does not exist. SeaweedFS answers 403 AccessDenied. S3-compatibility test suites run by data platforms (which create, probe and clean up buckets with a scoped key) flag the difference, and a client that maps 404 to "create it" or "skip it" takes the 403 for a permissions problem instead.

Answering 404 tells every authenticated identity whether a bucket name exists, which a multi-tenant deployment may not want, so the default stays 403.

## Fix

A new option, off by default: `-s3.noSuchBucketWhenDenied` on `weed server`, `weed filer` and `weed mini`, `-noSuchBucketWhenDenied` on `weed s3` (`S3ApiServerOption.NoSuchBucketWhenDenied`).

With it set, `refineDenial` extends `refineDenialForBucketName` (400 InvalidBucketName) with the NoSuchBucket answer, in `Auth`, `AuthPostPolicy` and the POST policy handler:

- only after authentication succeeded with a signature or a token (signed, presigned, V2, streaming signed, streaming-unsigned with a signed header, JWT). The anonymous identity keeps 403 under any auth type, so an anonymous caller still learns nothing about which buckets exist;
- a bucket-level PUT (CreateBucket, configuring a bucket) keeps 403, as AWS answers a refused create;
- the lookup goes through the bucket config cache, which the authorization path has usually just filled, so a denied request rarely costs a filer lookup; a failed lookup is "unknown" and keeps 403;
- an allowed request never looks a bucket up.

`Auth` now keeps the auth type it used to discard; the POST policy handler, which verifies the form signature itself, passes `authTypeSigned`.

With the option off nothing changes.

## Tests

`weed/s3api/auth_no_such_bucket_test.go`:

- `TestRefineDenialThroughAuth`: through `iam.Auth`, a signed caller denied on another identity's existing bucket gets 403 and on a missing bucket 404 (GET, PUT, a signed streaming-unsigned PUT); a bucket-level PUT stays 403; the caller's own bucket is allowed with no lookup.
- `TestRefineDenialAnonymousLearnsNothing`: anonymous requests answer 403 for a missing and an existing bucket alike and never drive a lookup.
- `TestRefineDenialRules`: presigned and JWT callers, failed authentication, allowed requests, a missing bucket name, a failed lookup, and the option off (no lookup wired) all keep their answer.
- `TestPostPolicyDeniedNoSuchBucket`: a verified browser POST form denied on a missing bucket answers NoSuchBucket; a bad signature stays SignatureDoesNotMatch; an existing bucket stays AccessDenied.

`TestRefineDenialThroughAuth`, `TestRefineDenialRules` and `TestPostPolicyDeniedNoSuchBucket` fail without the NoSuchBucket answer. `go vet` reports nothing in the touched files; `go test ./weed/s3api/ ./weed/command/`: ok. `go build ./weed`: ok.

* s3api: count streaming-unsigned as signed only with a SigV4 or JWT credential

A client-certificate identity that streamed its body unsigned answered
NoSuchBucket on a denied missing bucket, while the same request without
the body-encoding header answered 403.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: tell the anonymous identity by name, without the unlocked pointer read

isAnonymousIdentity compared against iam.identityAnonymous without iam.m,
racing a configuration reload. The configured anonymous identity always
has the anonymous name and account, which the check already covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* command: keep allowBackslashInKeyUsage's doc comment on its const

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer NoSuchBucket to a denied request on a missing bucket by default

AWS S3 answers it this way, so drop the -s3.noSuchBucketWhenDenied flag
and always wire the bucket lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer NoSuchBucket to a client-certificate identity too

The AWS answer now goes to every authenticated identity, so it no
longer depends on how the caller authenticated. The anonymous identity
keeps 403, as anonymous object reads mask a missing bucket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fold the NoSuchBucket answer into refineDenialForBucketName

One refinement for the bucket a denied request names: 400 for a
malformed name, 404 for a missing one. The anonymous read paths keep
their answer, since the anonymous identity never gets the 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:00:01 -08:00

244 lines
12 KiB
Go

package s3api
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A denied request on a bucket that does not exist answers 404 NoSuchBucket, as
// AWS S3 does, when the caller authenticated as an identity; a malformed name
// answers 400 InvalidBucketName (auth_invalid_bucket_name_test.go). Everything
// else, including every anonymous request, is unchanged.
const (
rdAccessKey = "RDTENANTKEY000000001"
rdSecretKey = "rd-tenant-secret-for-tests-only"
rdOwnBucket = "own-bucket" // the tenant may read this one
rdForeign = "foreign-bucket" // exists, someone else's
rdMissing = "missing-bucket" // does not exist
)
// refineFixture is an IAM with one tenant identity allowed to read rdOwnBucket only, an anonymous identity
// with no rights, and a bucketMissing that knows rdOwnBucket and rdForeign exist and counts its calls.
type refineFixture struct {
iam *IdentityAccessManagement
mu sync.Mutex
lookups []string
}
func newRefineFixture(t *testing.T) *refineFixture {
t.Helper()
iam := &IdentityAccessManagement{hashes: make(map[string]*sync.Pool), hashCounters: make(map[string]*int32)}
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "admin", Actions: []string{"Admin"},
Credentials: []*iam_pb.Credential{{AccessKey: "RDADMINKEY0000000001", SecretKey: "rd-admin-secret"}}},
{Name: "tenant", Actions: []string{"Read:" + rdOwnBucket, "List:" + rdOwnBucket},
Credentials: []*iam_pb.Credential{{AccessKey: rdAccessKey, SecretKey: rdSecretKey}}},
{Name: "cert-tenant", Actions: []string{"Read:" + rdOwnBucket},
Certificates: []*iam_pb.CertificateMatch{{SubjectCn: "rd-cert-tenant"}}},
{Name: s3_constants.AccountAnonymousId}, // a configured anonymous identity with no actions
},
}))
f := &refineFixture{iam: iam}
iam.bucketMissing = func(bucket string) bool {
f.mu.Lock()
f.lookups = append(f.lookups, bucket)
f.mu.Unlock()
return bucket != rdOwnBucket && bucket != rdForeign
}
return f
}
// serve runs the request through iam.Auth (the wrapper every S3 object and bucket route uses) and returns the
// status and the S3 error code; ran says whether the handler was reached.
func (f *refineFixture) serve(t *testing.T, r *http.Request, action Action) (status int, ran bool) {
t.Helper()
rec := httptest.NewRecorder()
f.iam.Auth(func(w http.ResponseWriter, r *http.Request) { ran = true; w.WriteHeader(http.StatusOK) }, action).ServeHTTP(rec, r)
return rec.Code, ran
}
func rdRequest(t *testing.T, method, bucket, object string, sign bool) *http.Request {
t.Helper()
urlStr := fmt.Sprintf("http://127.0.0.1:8333/%s", bucket)
if object != "" {
urlStr += "/" + object
}
req := mustNewRequest(method, urlStr, 0, nil, t)
if sign {
require.NoError(t, signRequestV4(req, rdAccessKey, rdSecretKey))
}
vars := map[string]string{"bucket": bucket}
if object != "" {
vars["object"] = object
}
return mux.SetURLVars(req, vars)
}
func TestRefineDenialThroughAuth(t *testing.T) {
f := newRefineFixture(t)
require.True(t, f.iam.isEnabled())
// positive control: the tenant's own bucket is allowed, unchanged, and costs no lookup
code, ran := f.serve(t, rdRequest(t, http.MethodGet, rdOwnBucket, "ns/t/data/a.parquet", true), s3_constants.ACTION_READ)
assert.True(t, ran)
assert.Equal(t, http.StatusOK, code)
assert.Empty(t, f.lookups, "an allowed request never looks a bucket up")
// same shape, two answers: someone else's existing bucket stays 403, a missing one becomes 404
code, ran = f.serve(t, rdRequest(t, http.MethodGet, rdForeign, "ns/t/data/a.parquet", true), s3_constants.ACTION_READ)
assert.False(t, ran)
assert.Equal(t, http.StatusForbidden, code, "an existing bucket of another tenant stays AccessDenied")
code, _ = f.serve(t, rdRequest(t, http.MethodGet, rdMissing, "ns/t/data/a.parquet", true), s3_constants.ACTION_READ)
assert.Equal(t, http.StatusNotFound, code, "a missing bucket answers NoSuchBucket to a signed caller")
code, _ = f.serve(t, rdRequest(t, http.MethodPut, rdMissing, "x.parquet", true), s3_constants.ACTION_WRITE)
assert.Equal(t, http.StatusNotFound, code, "PutObject into a missing bucket answers NoSuchBucket")
assert.Equal(t, []string{rdForeign, rdMissing, rdMissing}, f.lookups)
// a signed PUT whose body is streamed unsigned (what botocore sends for a plain put_object) is a signed caller too
f.lookups = nil
r := rdRequest(t, http.MethodPut, rdMissing, "x.parquet", false)
r.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
require.NoError(t, signRequestV4(r, rdAccessKey, rdSecretKey))
require.Equal(t, "STREAMING-UNSIGNED-PAYLOAD-TRAILER", r.Header.Get("x-amz-content-sha256"), "the signer kept the streaming header")
require.Equal(t, authTypeStreamingUnsigned, getRequestAuthType(r))
code, _ = f.serve(t, r, s3_constants.ACTION_WRITE)
assert.Equal(t, http.StatusNotFound, code, "a signed streaming-unsigned PUT into a missing bucket answers NoSuchBucket")
r = rdRequest(t, http.MethodPut, rdForeign, "x.parquet", false)
r.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
require.NoError(t, signRequestV4(r, rdAccessKey, rdSecretKey))
code, _ = f.serve(t, r, s3_constants.ACTION_WRITE)
assert.Equal(t, http.StatusForbidden, code, "the same shape on an existing foreign bucket stays AccessDenied")
assert.Equal(t, []string{rdMissing, rdForeign}, f.lookups)
// a refused CreateBucket (bucket-level PUT) keeps 403, as AWS answers it, and looks nothing up
f.lookups = nil
code, _ = f.serve(t, rdRequest(t, http.MethodPut, rdMissing, "", true), s3_constants.ACTION_ADMIN)
assert.Equal(t, http.StatusForbidden, code)
assert.Empty(t, f.lookups)
// a malformed name answers 400 to a signed caller, without a lookup
code, _ = f.serve(t, rdRequest(t, http.MethodGet, "Bad_Bucket", "k", true), s3_constants.ACTION_READ)
assert.Equal(t, http.StatusBadRequest, code)
assert.Empty(t, f.lookups)
}
func TestRefineDenialAnonymousLearnsNothing(t *testing.T) {
f := newRefineFixture(t)
// plain anonymous GET: 403 for a missing and an existing bucket alike, and no lookup
missing, _ := f.serve(t, rdRequest(t, http.MethodGet, rdMissing, "k.parquet", false), s3_constants.ACTION_READ)
foreign, _ := f.serve(t, rdRequest(t, http.MethodGet, rdForeign, "k.parquet", false), s3_constants.ACTION_READ)
assert.Equal(t, http.StatusForbidden, missing)
assert.Equal(t, missing, foreign)
// an anonymous streaming-unsigned PUT (what botocore sends for a plain PUT) resolves to the anonymous identity
// under another auth type: still 403 for both
for _, b := range []string{rdMissing, rdForeign} {
r := rdRequest(t, http.MethodPut, b, "k.parquet", false)
r.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
code, ran := f.serve(t, r, s3_constants.ACTION_WRITE)
assert.False(t, ran)
assert.Equal(t, http.StatusForbidden, code, b)
}
assert.Empty(t, f.lookups, "anonymous traffic never drives a bucket lookup")
}
// A client certificate identity gets the same answers as a signed caller,
// whether or not the body is streamed unsigned.
func TestRefineDenialClientCertificate(t *testing.T) {
f := newRefineFixture(t)
for _, streaming := range []bool{false, true} {
for b, want := range map[string]int{rdMissing: http.StatusNotFound, rdForeign: http.StatusForbidden} {
r := rdRequest(t, http.MethodPut, b, "k.parquet", false)
cert := clientCertificate("rd-cert-tenant", "")
r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert}, VerifiedChains: [][]*x509.Certificate{{cert}}}
if streaming {
r.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
}
identity, errCode := f.iam.AuthenticateRequest(r)
require.Equal(t, s3err.ErrNone, errCode)
require.Equal(t, "cert-tenant", identity.Name)
code, ran := f.serve(t, r, s3_constants.ACTION_WRITE)
assert.False(t, ran)
assert.Equal(t, want, code, "streaming=%v bucket=%s", streaming, b)
}
}
}
// The unit rules, including the cases no wrapper test reaches.
func TestRefineDenialRules(t *testing.T) {
f := newRefineFixture(t)
tenant := &Identity{Name: "tenant"}
req := func(bucket string) *http.Request {
return mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/", nil), map[string]string{"bucket": bucket})
}
anonymous := &Identity{Name: s3_constants.AccountAnonymousId, Account: &AccountAnonymous}
cases := []struct {
name string
bucket string
identity *Identity
in, want s3err.ErrorCode
}{
{"space in the name", "bucket name", tenant, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
{"non-ASCII letter", "bücket", tenant, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
{"superscript digit", "b²cket", tenant, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
{"too short", "ab", tenant, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
{"missing", rdMissing, tenant, s3err.ErrAccessDenied, s3err.ErrNoSuchBucket},
{"existing", rdForeign, tenant, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
{"anonymous identity, missing", rdMissing, anonymous, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
{"unnamed identity, missing", rdMissing, &Identity{}, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
// authentication failures and allowed requests are never refined, whatever the name
{"authN failed (no identity), malformed name", "Bad_Bucket", nil, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
{"authN failed (no identity), missing", rdMissing, nil, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
{"allowed", rdMissing, tenant, s3err.ErrNone, s3err.ErrNone},
{"bad signature", rdMissing, nil, s3err.ErrSignatureDoesNotMatch, s3err.ErrSignatureDoesNotMatch},
{"unknown key", "bad name", nil, s3err.ErrInvalidAccessKeyID, s3err.ErrInvalidAccessKeyID},
{"no bucket in the request", "", tenant, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
}
for _, c := range cases {
assert.Equal(t, c.want, f.iam.refineDenialForBucketName(req(c.bucket), c.identity, c.in), c.name)
}
// a lookup that failed is "unknown", never "missing": the denial stays 403
f.iam.bucketMissing = func(string) bool { return false }
assert.Equal(t, s3err.ErrAccessDenied, f.iam.refineDenialForBucketName(req(rdMissing), tenant, s3err.ErrAccessDenied))
// no lookup wired: every denial stays 403
f.iam.bucketMissing = nil
assert.Equal(t, s3err.ErrAccessDenied, f.iam.refineDenialForBucketName(req(rdMissing), tenant, s3err.ErrAccessDenied))
}
// A browser POST upload verifies its signature in the handler; a verified form
// denied on a missing bucket answers NoSuchBucket, a bad signature stays 403.
func TestPostPolicyDeniedNoSuchBucket(t *testing.T) {
s3a := newPostAuthzServer(t)
s3a.iam.bucketMissing = func(bucket string) bool { return bucket == "gone-bucket" }
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: "other-bucket"})
serve := func(r *http.Request) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
s3a.iam.AuthPostPolicy(s3a.PostPolicyBucketHandler, s3_constants.ACTION_WRITE).ServeHTTP(rec, r)
return rec
}
rec := serve(signedPostForm(t, "gone-bucket", "k", postAuthzSecretKey))
assert.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
assert.Contains(t, rec.Body.String(), "NoSuchBucket")
rec = serve(signedPostForm(t, "gone-bucket", "k", "not-the-secret"))
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
assert.Contains(t, rec.Body.String(), "SignatureDoesNotMatch")
rec = serve(signedPostForm(t, "other-bucket", "k", postAuthzSecretKey))
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
assert.Contains(t, rec.Body.String(), "AccessDenied")
}