From 05d9242f3cb498d94fdcf829cf2f796f568b9ce4 Mon Sep 17 00:00:00 2001 From: Javier de la Torre Date: Mon, 30 Nov 2026 22:00:01 +0100 Subject: [PATCH] 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 * 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 * command: keep allowBackslashInKeyUsage's doc comment on its const Co-Authored-By: Claude Opus 5.5 * 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 * 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 * 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 --------- Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- weed/s3api/auth_credentials.go | 47 +++- weed/s3api/auth_invalid_bucket_name_test.go | 3 +- weed/s3api/auth_no_such_bucket_test.go | 243 ++++++++++++++++++ weed/s3api/s3api_object_anonymous_read.go | 2 +- .../s3api/s3api_object_handlers_postpolicy.go | 6 +- weed/s3api/s3api_server.go | 9 +- 6 files changed, 295 insertions(+), 15 deletions(-) create mode 100644 weed/s3api/auth_no_such_bucket_test.go diff --git a/weed/s3api/auth_credentials.go b/weed/s3api/auth_credentials.go index 0cbafb34ff..d4b536a2a3 100644 --- a/weed/s3api/auth_credentials.go +++ b/weed/s3api/auth_credentials.go @@ -93,6 +93,11 @@ type IdentityAccessManagement struct { // NewS3ApiServer; nil in tests. objectEntryForPolicy func(r *http.Request, bucket, object string) (map[string][]byte, bool) + // bucketMissing reports whether a bucket is known NOT to exist; a failed + // lookup is not "missing". Used only by refineDenialForBucketName. Set by + // NewS3ApiServer; nil in tests, which keeps every denial 403. + bucketMissing func(bucket string) bool + // Cached policy engine for IAM policy fallback evaluation. // Keyed by policy name, kept in sync by PutPolicy/DeletePolicy. iamPolicyEngine *policy_engine.PolicyEngine @@ -1781,7 +1786,7 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt // requester; a failed authN resolves no identity at all. since := iam.inFlightGeneration() identity, errCode, _ := iam.authRequestWithAuthType(r, action) - errCode = refineDenialForBucketName(r, identity, errCode) + errCode = iam.refineDenialForBucketName(r, identity, errCode) if errCode != s3err.ErrNone { glog.V(3).Infof("auth error: %v", errCode) } @@ -1820,7 +1825,7 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A } } - errCode = refineDenialForBucketName(r, identity, errCode) + errCode = iam.refineDenialForBucketName(r, identity, errCode) if errCode != s3err.ErrNone { glog.V(3).Infof("auth error: %v", errCode) } @@ -1829,25 +1834,49 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A } } -// refineDenialForBucketName answers 400 InvalidBucketName, as AWS S3 does, -// when an authenticated caller is denied on a bucket whose name breaks the S3 -// naming rules. The rules are public and the answer depends on the name alone, -// so it tells the caller nothing about which buckets exist. Authentication -// failures (no identity resolved) and every other answer are left unchanged. -func refineDenialForBucketName(r *http.Request, identity *Identity, errCode s3err.ErrorCode) s3err.ErrorCode { +// refineDenialForBucketName refines a denial to the answer AWS S3 gives for +// the bucket the request names, when the caller resolved to an identity: +// - 400 InvalidBucketName when the name breaks the S3 naming rules. The +// rules are public, so this tells the caller nothing about which buckets +// exist, and it applies to the anonymous identity too; +// - 404 NoSuchBucket when the bucket does not exist. The anonymous identity +// keeps 403, as anonymous object reads mask a missing bucket; a +// bucket-level PUT (CreateBucket, or configuring a bucket) keeps 403, as +// AWS answers a refused create; a lookup that fails, or no lookup wired, +// keeps 403: unknown is never "missing". +// +// Authentication failures (no identity resolved) and every other answer are +// left unchanged. +func (iam *IdentityAccessManagement) refineDenialForBucketName(r *http.Request, identity *Identity, errCode s3err.ErrorCode) s3err.ErrorCode { if errCode != s3err.ErrAccessDenied || identity == nil { return errCode } - bucket, _ := s3_constants.GetBucketAndObject(r) + bucket, object := s3_constants.GetBucketAndObject(r) if bucket == "" { return errCode } if !isASCIIBucketName(bucket) || s3bucket.VerifyS3BucketName(bucket) != nil { return s3err.ErrInvalidBucketName } + if iam.bucketMissing == nil || isAnonymousIdentity(identity) { + return errCode + } + if r.Method == http.MethodPut && (object == "" || object == "/") { + return errCode + } + if iam.bucketMissing(bucket) { + return s3err.ErrNoSuchBucket + } return errCode } +// The configured anonymous identity always carries the anonymous name and +// account, so no read of iam.identityAnonymous (and of iam.m) is needed. +func isAnonymousIdentity(identity *Identity) bool { + return identity.Name == "" || identity.Name == s3_constants.AccountAnonymousId || + (identity.Account != nil && identity.Account.Id == s3_constants.AccountAnonymousId) +} + // isASCIIBucketName reports whether name uses only the characters S3 allows // in a bucket name. VerifyS3BucketName checks with unicode.IsLower and // unicode.IsNumber, which also accept letters such as 'ü' and digits such as diff --git a/weed/s3api/auth_invalid_bucket_name_test.go b/weed/s3api/auth_invalid_bucket_name_test.go index e702d49001..082295bdd5 100644 --- a/weed/s3api/auth_invalid_bucket_name_test.go +++ b/weed/s3api/auth_invalid_bucket_name_test.go @@ -100,8 +100,9 @@ func TestRefineDenialForBucketName(t *testing.T) { {"authentication failed", "Bad_Bucket", nil, s3err.ErrAccessDenied, s3err.ErrAccessDenied}, {"bad signature", "Bad_Bucket", nil, s3err.ErrSignatureDoesNotMatch, s3err.ErrSignatureDoesNotMatch}, } + iam := &IdentityAccessManagement{} for _, c := range cases { - assert.Equal(t, c.want, refineDenialForBucketName(req(c.bucket), c.identity, c.in), c.name) + assert.Equal(t, c.want, iam.refineDenialForBucketName(req(c.bucket), c.identity, c.in), c.name) } } diff --git a/weed/s3api/auth_no_such_bucket_test.go b/weed/s3api/auth_no_such_bucket_test.go new file mode 100644 index 0000000000..f1904c9493 --- /dev/null +++ b/weed/s3api/auth_no_such_bucket_test.go @@ -0,0 +1,243 @@ +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") +} diff --git a/weed/s3api/s3api_object_anonymous_read.go b/weed/s3api/s3api_object_anonymous_read.go index 529fb87155..26a8cfbd52 100644 --- a/weed/s3api/s3api_object_anonymous_read.go +++ b/weed/s3api/s3api_object_anonymous_read.go @@ -187,7 +187,7 @@ func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket str func (s3a *S3ApiServer) writeAnonymousAwareNotFound(w http.ResponseWriter, r *http.Request, bucket string, code s3err.ErrorCode) { if isAnonymousObjectRead(r) && s3a.authorizeAnonymousBucketList(r, bucket) != s3err.ErrNone { identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity) - s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, s3err.ErrAccessDenied)) + s3err.WriteErrorResponse(w, r, s3a.iam.refineDenialForBucketName(r, identity, s3err.ErrAccessDenied)) return } s3err.WriteErrorResponse(w, r, code) diff --git a/weed/s3api/s3api_object_handlers_postpolicy.go b/weed/s3api/s3api_object_handlers_postpolicy.go index d372bb7b6b..6cee5421b9 100644 --- a/weed/s3api/s3api_object_handlers_postpolicy.go +++ b/weed/s3api/s3api_object_handlers_postpolicy.go @@ -92,7 +92,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R if s3a.iam.isEnabled() { identity, errCode = s3a.iam.doesPolicySignatureMatch(r.Context(), formValues) if errCode != s3err.ErrNone { - s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode)) + s3err.WriteErrorResponse(w, r, s3a.iam.refineDenialForBucketName(r, identity, errCode)) return } if identity != nil { @@ -170,14 +170,14 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R return } if errCode := s3a.iam.AuthorizeObjectWrite(policyReq, identity, bucket, object); errCode != s3err.ErrNone { - s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode)) + s3err.WriteErrorResponse(w, r, s3a.iam.refineDenialForBucketName(r, identity, errCode)) return } // An acl or x-amz-grant-* form field rides onto the upload as ACL headers, // which the PUT path only applies under s3:PutObjectAcl. if postRequestsAcl(r) { if errCode := s3a.iam.AuthorizeObjectAclWrite(policyReq, identity, bucket, object); errCode != s3err.ErrNone { - s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode)) + s3err.WriteErrorResponse(w, r, s3a.iam.refineDenialForBucketName(r, identity, errCode)) return } } diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index 4be2a23cbd..db454ab44a 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -443,6 +443,13 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl } return entry.Extended, true } + // Through the bucket config cache (positive and negative entries), which + // the IAM path above has often just filled: a denied request costs no + // extra filer lookup when the answer is cached. + iam.bucketMissing = func(bucket string) bool { + _, errCode := s3ApiServer.getBucketConfig(bucket) + return errCode == s3err.ErrNoSuchBucket + } // Initialize advanced IAM system if config is provided or explicitly enabled if option.IamConfig != "" || option.EnableIam { @@ -722,7 +729,7 @@ func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, ob // Refined like writeAnonymousAwareNotFound's masked miss, so a denied // existing key and a missing key answer alike on a malformed name. identity, _ := GetIdentityFromContext(r).(*Identity) - return refineDenialForBucketName(r, identity, s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry)) + return s3a.iam.refineDenialForBucketName(r, identity, s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry)) } if s3a.isVersionFileKey(object, objectEntry) { return s3err.ErrAccessDenied