Files
seaweedfs/weed/s3api/table_bucket_layout_message_test.go
T
f4931605e0 s3tables: say why a write the table bucket layout refuses is refused (#13133)
* s3tables: say why a write the table bucket layout refuses is refused

## Problem

A table bucket accepts only Iceberg files under `<namespace>/<table>/(data|metadata)/`. A PutObject, CopyObject or CreateMultipartUpload of any other key is refused with a bare 403 AccessDenied, which a client that put a plain file there (a README, a CSV next to the table) reads as a permissions problem and goes looking for a missing grant.

## Fix

Those three refusals now carry a message:

    table buckets accept only Iceberg files under <namespace>/<table>/data/ or <namespace>/<table>/metadata/; put other objects in a general purpose bucket

Status and code are unchanged (403 AccessDenied).

The message tells the caller that the bucket is a table bucket, so it goes only to a caller the bucket policy lets write that key (`checkPolicyWithEntry`). A caller the policy denies gets the policy's own refusal, identical to the one for a key the layout accepts, so the answer never tells a table bucket from another bucket to someone who could not write there.

A PUT of the volume verification key that the layout accepts but `volumeVerifyPutAllowed` refuses (outside its window, too large, stored headers) is not a layout refusal and keeps the bare AccessDenied.

## Tests

`weed/s3api/table_bucket_layout_message_test.go`:

- `TestTableBucketLayoutRefusalExplainsItself`: PUT, copy and multipart initiation of `ns/t/data/notes.txt` answer 403 AccessDenied with the message. Fails without the change.
- `TestTableBucketLayoutRefusalIsBareWhenPolicyDenies`: with a bucket policy denying the write, the refusal of a layout-refused key is byte-for-byte the refusal of a valid `.parquet` key.
- `TestTableBucketVerifyRefusalIsNotALayoutRefusal`: a stale verification key keeps the bare refusal.

`go vet ./weed/s3api/` reports nothing in the touched files; `go test ./weed/s3api/`: ok. `go build ./weed`: ok.

* s3api: load the bucket before a layout refusal checks its policy

With authentication off nothing loads the bucket before the handler, so a
stored Deny was not in the engine yet and the first layout-refused write
after a restart got the table-bucket explanation.

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

* s3api: apply existing-object tag conditions before a layout refusal explains itself

A Deny on s3:ExistingObjectTag is deferred by the first policy check and
applied only by the later lookup recheck, which the layout refusal skipped,
so a tag-denied writer still learned the bucket is a table bucket.

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

* s3api: name the format-owned directories in the table layout refusal

Table buckets also accept a table format's own _-prefixed directories
(Lance's _versions, _transactions, _indices), so telling a Lance writer that
only Iceberg data/ and metadata/ files are accepted misleads it.

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 10:33:15 -08:00

187 lines
8.1 KiB
Go

package s3api
import (
"encoding/xml"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const layoutMessageBucket = "iceberg-tables"
func newLayoutMessageServer(t *testing.T, policy string) *S3ApiServer {
t.Helper()
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}, iam: &IdentityAccessManagement{}}
if policy != "" {
policyEngine := NewBucketPolicyEngine()
require.NoError(t, policyEngine.engine.SetBucketPolicy(layoutMessageBucket, policy))
s3a.policyEngine = policyEngine
}
s3a.bucketRegistry = NewBucketRegistry(s3a)
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: layoutMessageBucket, IsTableBucket: true})
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
s3a.bucketConfigCache.Set(layoutMessageBucket, &BucketConfig{Name: layoutMessageBucket, Ownership: s3_constants.OwnershipObjectWriter})
return s3a
}
func layoutMessageRequest(method, key, query string) *http.Request {
req := httptest.NewRequest(method, "/"+layoutMessageBucket+"/"+key+query, strings.NewReader("x"))
return mux.SetURLVars(req, map[string]string{"bucket": layoutMessageBucket, "object": key})
}
func layoutAnswer(t *testing.T, s3a *S3ApiServer, handler func(*S3ApiServer) http.HandlerFunc, req *http.Request) (int, s3err.RESTErrorResponse) {
t.Helper()
rec := httptest.NewRecorder()
handler(s3a)(rec, req)
var resp s3err.RESTErrorResponse
require.NoError(t, xml.Unmarshal(rec.Body.Bytes(), &resp), rec.Body.String())
return rec.Code, resp
}
// A write the table bucket layout refuses says why (PUT, copy, multipart
// initiation), so a client that put a plain file in a table bucket learns
// where it belongs instead of reading a bare AccessDenied.
func TestTableBucketLayoutRefusalExplainsItself(t *testing.T) {
s3a := newLayoutMessageServer(t, "")
put := func(s *S3ApiServer) http.HandlerFunc { return s.PutObjectHandler }
code, resp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/notes.txt", ""))
assert.Equal(t, http.StatusForbidden, code)
assert.Equal(t, "AccessDenied", resp.Code)
assert.Equal(t, tableBucketLayoutMessage, resp.Message)
cp := layoutMessageRequest(http.MethodPut, "ns/t/data/notes.txt", "")
cp.Header.Set("X-Amz-Copy-Source", "/"+layoutMessageBucket+"/ns/t/data/part-00000.parquet")
code, resp = layoutAnswer(t, s3a, func(s *S3ApiServer) http.HandlerFunc { return s.CopyObjectHandler }, cp)
assert.Equal(t, http.StatusForbidden, code)
assert.Equal(t, tableBucketLayoutMessage, resp.Message, "CopyObject")
code, resp = layoutAnswer(t, s3a, func(s *S3ApiServer) http.HandlerFunc { return s.NewMultipartUploadHandler },
layoutMessageRequest(http.MethodPost, "ns/t/data/notes.txt", "?uploads"))
assert.Equal(t, http.StatusForbidden, code)
assert.Equal(t, tableBucketLayoutMessage, resp.Message, "CreateMultipartUpload")
}
// The explanation says the bucket is a table bucket, so it goes only to a
// caller the bucket policy lets write there. Anyone else gets the policy's own
// bare refusal, the same as for a key the layout would accept.
func TestTableBucketLayoutRefusalIsBareWhenPolicyDenies(t *testing.T) {
s3a := newLayoutMessageServer(t, `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::`+layoutMessageBucket+`/*"]
}]
}`)
put := func(s *S3ApiServer) http.HandlerFunc { return s.PutObjectHandler }
code, resp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/notes.txt", ""))
require.Equal(t, http.StatusForbidden, code)
assert.Equal(t, "AccessDenied", resp.Code)
assert.Equal(t, s3err.GetAPIError(s3err.ErrAccessDenied).Description, resp.Message)
// positive control with the same key shape: a key the layout accepts,
// refused by the same policy, answers exactly the same, so the refusal does
// not tell a table bucket from any other
validCode, validResp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/part-00000.parquet", ""))
assert.Equal(t, validCode, code)
assert.Equal(t, validResp.Code, resp.Code)
assert.Equal(t, validResp.Message, resp.Message)
}
// A verification key the layout accepts but whose PUT is refused for its age or
// headers is not a layout refusal: it keeps the bare AccessDenied.
func TestTableBucketVerifyRefusalIsNotALayoutRefusal(t *testing.T) {
s3a := newLayoutMessageServer(t, "")
prev := volumeVerifyLookup
volumeVerifyLookup = func(*S3ApiServer, string, string) (*filer_pb.Entry, error) { return nil, filer_pb.ErrNotFound }
t.Cleanup(func() { volumeVerifyLookup = prev })
stale := "verify_1000000000000_1" // a verification key, far outside the one-hour window
code, resp := layoutAnswer(t, s3a, func(s *S3ApiServer) http.HandlerFunc { return s.PutObjectHandler },
layoutMessageRequest(http.MethodPut, stale, ""))
assert.Equal(t, http.StatusForbidden, code)
assert.Equal(t, "AccessDenied", resp.Code)
assert.NotEqual(t, tableBucketLayoutMessage, resp.Message)
}
func newColdLayoutMessageServer(t *testing.T, policy string) (*S3ApiServer, *ambiguousPutFiler) {
t.Helper()
bucketEntry := &filer_pb.Entry{
Name: layoutMessageBucket,
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{
s3_constants.ExtAmzOwnerKey: []byte("000000000000"),
s3tables.ExtendedKeyTableBucket: []byte("{}"),
BUCKET_POLICY_METADATA_KEY: []byte(policy),
},
}
filer := &ambiguousPutFiler{
volume: startFakeVolumeServer(t),
entries: map[string]*filer_pb.Entry{"/buckets/" + layoutMessageBucket: bucketEntry},
}
s3a := newPostAutoCreateServer(t, filer)
s3a.iam = &IdentityAccessManagement{}
s3a.policyEngine = NewBucketPolicyEngine()
s3a.bucketRegistry = NewBucketRegistry(s3a)
return s3a, filer
}
// With authentication off nothing loads the bucket before the handler, so the
// refusal loads it itself: a stored Deny keeps the answer bare on the first
// request after a restart.
func TestTableBucketLayoutRefusalLoadsTheBucketPolicy(t *testing.T) {
s3a, _ := newColdLayoutMessageServer(t, `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::`+layoutMessageBucket+`/*"]
}]
}`)
put := func(s *S3ApiServer) http.HandlerFunc { return s.PutObjectHandler }
code, resp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/notes.txt", ""))
require.Equal(t, http.StatusForbidden, code)
assert.Equal(t, s3err.GetAPIError(s3err.ErrAccessDenied).Description, resp.Message)
}
// A Deny on the existing object's tags governs a layout-refused key the same
// as a layout-accepted one, so the explanation does not reach that caller.
func TestTableBucketLayoutRefusalAppliesExistingObjectTagDeny(t *testing.T) {
s3a, filer := newColdLayoutMessageServer(t, `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::`+layoutMessageBucket+`/*"],
"Condition": {"StringEquals": {"s3:ExistingObjectTag/team": "locked"}}
}]
}`)
dir := "/buckets/" + layoutMessageBucket + "/ns/t/data"
for _, name := range []string{"notes.txt", "part-00000.parquet"} {
filer.entries[dir+"/"+name] = &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "team": []byte("locked")},
}
}
put := func(s *S3ApiServer) http.HandlerFunc { return s.PutObjectHandler }
code, resp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/notes.txt", ""))
require.Equal(t, http.StatusForbidden, code)
assert.Equal(t, s3err.GetAPIError(s3err.ErrAccessDenied).Description, resp.Message)
validCode, validResp := layoutAnswer(t, s3a, put, layoutMessageRequest(http.MethodPut, "ns/t/data/part-00000.parquet", ""))
assert.Equal(t, validCode, code)
assert.Equal(t, validResp.Message, resp.Message)
}