From cf3eda7e57e84e6b3fa2d14b77016657c4dd0fa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20L=E1=BB=99c=20Ph=C3=BAc?= <112325531+omninguyen@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:54:04 +0700 Subject: [PATCH] perf(s3vectors): read the bucket once per authorization (#13427) s3vectors: read the bucket once per authorization Co-authored-by: Claude Opus 5.5 --- weed/s3api/s3tables/filer_ops.go | 18 +- weed/s3api/s3tables/handler.go | 14 +- .../handler_bucket_get_list_delete.go | 37 +++-- .../handler_bucket_get_lookups_test.go | 38 +++++ weed/s3api/s3tables/manager.go | 30 ++++ .../s3vectors/authorize_lookups_bench_test.go | 65 ++++++++ .../s3api/s3vectors/authorize_lookups_test.go | 65 ++++++++ weed/s3api/s3vectors/handlers.go | 64 +++---- weed/s3api/s3vectors/handlers_test.go | 2 +- .../s3vectors/vector_bucket_read_test.go | 156 ++++++++++++++++++ 10 files changed, 424 insertions(+), 65 deletions(-) create mode 100644 weed/s3api/s3tables/handler_bucket_get_lookups_test.go create mode 100644 weed/s3api/s3vectors/authorize_lookups_bench_test.go create mode 100644 weed/s3api/s3vectors/authorize_lookups_test.go create mode 100644 weed/s3api/s3vectors/vector_bucket_read_test.go diff --git a/weed/s3api/s3tables/filer_ops.go b/weed/s3api/s3tables/filer_ops.go index 95d98d0168..150bf9171d 100644 --- a/weed/s3api/s3tables/filer_ops.go +++ b/weed/s3api/s3tables/filer_ops.go @@ -417,24 +417,20 @@ func snapshotExtended(extended map[string][]byte, keys ...string) map[string][]b // getExtendedAttribute gets an extended attribute from an entry func (h *S3TablesHandler) getExtendedAttribute(ctx context.Context, client filer_pb.SeaweedFilerClient, path, key string) ([]byte, error) { - dir, name := splitPath(path) - resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{ - Directory: dir, - Name: name, - }) + entry, err := h.lookupEntry(ctx, client, path) if err != nil { return nil, err } + return extendedAttr(entry, key) +} - if resp.Entry.Extended == nil { - return nil, fmt.Errorf("%w: %s", ErrAttributeNotFound, key) - } - - data, ok := resp.Entry.Extended[key] +// extendedAttr is getExtendedAttribute on an entry already looked up, so a +// caller needing several attributes of one entry reads it once. +func extendedAttr(entry *filer_pb.Entry, key string) ([]byte, error) { + data, ok := entry.Extended[key] if !ok { return nil, fmt.Errorf("%w: %s", ErrAttributeNotFound, key) } - return data, nil } diff --git a/weed/s3api/s3tables/handler.go b/weed/s3api/s3tables/handler.go index 9e5ef6d860..771f8f82f3 100644 --- a/weed/s3api/s3tables/handler.go +++ b/weed/s3api/s3tables/handler.go @@ -631,13 +631,19 @@ func (h *S3TablesHandler) authorizeAbsentTarget(r *http.Request, filerClient Fil } func (h *S3TablesHandler) readTags(ctx context.Context, client filer_pb.SeaweedFilerClient, path string) (map[string]string, error) { - data, err := h.getExtendedAttribute(ctx, client, path, ExtendedKeyTags) + entry, err := h.lookupEntry(ctx, client, path) if err != nil { - if errors.Is(err, ErrAttributeNotFound) { - return nil, nil - } return nil, err } + return tagsFromEntry(entry) +} + +// tagsFromEntry is readTags on an entry already looked up. +func tagsFromEntry(entry *filer_pb.Entry) (map[string]string, error) { + data, err := extendedAttr(entry, ExtendedKeyTags) + if err != nil { + return nil, nil + } tags := make(map[string]string) if err := json.Unmarshal(data, &tags); err != nil { return nil, fmt.Errorf("failed to unmarshal tags: %w", err) diff --git a/weed/s3api/s3tables/handler_bucket_get_list_delete.go b/weed/s3api/s3tables/handler_bucket_get_list_delete.go index 73ffa7b9c9..d7e412e651 100644 --- a/weed/s3api/s3tables/handler_bucket_get_list_delete.go +++ b/weed/s3api/s3tables/handler_bucket_get_list_delete.go @@ -35,13 +35,31 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re return err } + resp, _, err := h.getTableBucket(w, r, filerClient, bucketName) + if err != nil { + return err + } + h.writeJSON(w, http.StatusOK, resp) + return nil +} + +// getTableBucket reads a table bucket's record and checks the caller may get +// it, answering a failure on w as GetTableBucket does. It looks the bucket up +// once and returns that entry too, for a caller that needs more of its +// attributes than the record holds. +func (h *S3TablesHandler) getTableBucket(w http.ResponseWriter, r *http.Request, filerClient FilerClient, bucketName string) (*GetTableBucketResponse, *filer_pb.Entry, error) { bucketPath := GetTableBucketPath(bucketName) + var entry *filer_pb.Entry var metadata tableBucketMetadata var bucketPolicy string var bucketTags map[string]string - err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata) + err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + var err error + if entry, err = h.lookupEntry(r.Context(), client, bucketPath); err != nil { + return err + } + data, err := extendedAttr(entry, ExtendedKeyMetadata) if err != nil { return err } @@ -50,14 +68,14 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re } // Fetch bucket policy if it exists - policyData, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyPolicy) + policyData, err := extendedAttr(entry, ExtendedKeyPolicy) if err == nil { bucketPolicy = string(policyData) } else if !errors.Is(err, ErrAttributeNotFound) { return fmt.Errorf("failed to fetch bucket policy: %v", err) } if bucketPolicy != "" { - if bucketTags, err = h.readTags(r.Context(), client, bucketPath); err != nil { + if bucketTags, err = tagsFromEntry(entry); err != nil { return err } } @@ -71,7 +89,7 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re } else { h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, fmt.Sprintf("failed to get table bucket: %v", err)) } - return err + return nil, nil, err } bucketARN := h.generateTableBucketARN(metadata.OwnerAccountID, bucketName) @@ -88,20 +106,17 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re DefaultAllow: h.defaultAllowFor(r), }) { h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName)) - return ErrAccessDenied + return nil, nil, ErrAccessDenied } - resp := &GetTableBucketResponse{ + return &GetTableBucketResponse{ ARN: h.generateTableBucketARN(metadata.OwnerAccountID, bucketName), Name: metadata.Name, OwnerAccountID: metadata.OwnerAccountID, CreatedAt: metadata.CreatedAt, Format: metadata.Format, EncryptionConfiguration: metadata.EncryptionConfiguration, - } - - h.writeJSON(w, http.StatusOK, resp) - return nil + }, entry, nil } // handleListTableBuckets lists all table buckets diff --git a/weed/s3api/s3tables/handler_bucket_get_lookups_test.go b/weed/s3api/s3tables/handler_bucket_get_lookups_test.go new file mode 100644 index 0000000000..4b3e0d3828 --- /dev/null +++ b/weed/s3api/s3tables/handler_bucket_get_lookups_test.go @@ -0,0 +1,38 @@ +package s3tables + +import ( + "net/http" + "testing" +) + +// GetTableBucket decides on the bucket entry's metadata, policy and tags, all +// returned by one lookup of the entry, yet fetched each attribute with a +// lookup of its own: two lookups, three under a policy. +func TestGetTableBucketLooksUpTheBucketOnce(t *testing.T) { + for _, withPolicy := range []bool{false, true} { + name := "no policy" + if withPolicy { + name = "policy" + } + t.Run(name, func(t *testing.T) { + fs, m := startEmptyBucket(t) + if withPolicy { + requireOK(t, m, fs, "PutTableBucketPolicy", &PutTableBucketPolicyRequest{TableBucketARN: mustBucketARN(t), + ResourcePolicy: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:*","Resource":"*"}]}`}) + } + lookups := 0 + fs.OnLookup = func(dir, name string) { + if dir == TablesPath && name == renameTestBucket { + lookups++ + } + } + defer func() { fs.OnLookup = nil }() + if code, resp := runHandler(t, m, fs.Client, "GetTableBucket", &GetTableBucketRequest{TableBucketARN: mustBucketARN(t)}); code != http.StatusOK { + t.Fatalf("GetTableBucket = %d %+v", code, resp) + } + if lookups != 1 { + t.Errorf("GetTableBucket looked up the bucket %d times, want 1", lookups) + } + }) + } +} diff --git a/weed/s3api/s3tables/manager.go b/weed/s3api/s3tables/manager.go index c9988eeb10..3c6211fc8c 100644 --- a/weed/s3api/s3tables/manager.go +++ b/weed/s3api/s3tables/manager.go @@ -204,6 +204,36 @@ func (m *Manager) AuthorizeUpdateView(ctx context.Context, filerClient FilerClie return authErr } +// GetTableBucketEntry runs GetTableBucket and also returns the attributes of +// the bucket entry it read, so a caller needing more of them than the record +// holds does not look the bucket up again. The record and its attributes come +// from the same read, and the answers are GetTableBucket's. +func (m *Manager) GetTableBucketEntry(ctx context.Context, filerClient FilerClient, req *GetTableBucketRequest, identity string) (*GetTableBucketResponse, map[string][]byte, error) { + httpReq, err := newManagerRequest(ctx, "GetTableBucket", nil, identity) + if err != nil { + return nil, nil, err + } + recorder := httptest.NewRecorder() + if req.TableBucketARN == "" { + m.handler.writeError(recorder, http.StatusBadRequest, ErrCodeInvalidRequest, "tableBucketARN is required") + return nil, nil, decodeS3TablesHTTPResponse(recorder, nil) + } + bucketName, err := parseBucketNameFromARN(req.TableBucketARN) + if err != nil { + m.handler.writeError(recorder, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error()) + return nil, nil, decodeS3TablesHTTPResponse(recorder, nil) + } + resp, entry, getErr := m.handler.getTableBucket(recorder, httpReq, filerClient, bucketName) + if getErr == nil { + return resp, entry.Extended, nil + } + logRequestError("GetTableBucket", recorder.Code, getErr) + if decoded := decodeS3TablesHTTPResponse(recorder, nil); decoded != nil { + return nil, nil, decoded + } + return nil, nil, getErr +} + func newManagerRequest(ctx context.Context, operation string, body []byte, identity string) (*http.Request, error) { httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "/", bytes.NewReader(body)) if err != nil { diff --git a/weed/s3api/s3vectors/authorize_lookups_bench_test.go b/weed/s3api/s3vectors/authorize_lookups_bench_test.go new file mode 100644 index 0000000000..f2f27d4ff7 --- /dev/null +++ b/weed/s3api/s3vectors/authorize_lookups_bench_test.go @@ -0,0 +1,65 @@ +package s3vectors + +import ( + "fmt" + "net/http" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest" +) + +// BenchmarkVectorBucketReads times the requests that read only the bucket +// entry against the in-memory filer. The rtt cases add a fixed delay to every +// filer lookup to stand in for a filer on another host; they model no measured +// deployment. lookups/op is an exact count and does not depend on the machine. +func BenchmarkVectorBucketReads(b *testing.B) { + fs := s3tablestest.Start(b) + s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0)) + if w := postJSONAs(b, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK { + b.Fatalf("create bucket: %d %s", w.Code, w.Body.String()) + } + const policy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:*","Resource":"*"}]}` + if w := postJSONAs(b, "", s.handlePutVectorBucketPolicy, &PutVectorBucketPolicyRequest{VectorBucketName: "vec-bucket", Policy: policy}); w.Code != http.StatusOK { + b.Fatalf("put policy: %d %s", w.Code, w.Body.String()) + } + var lookups, delay atomic.Int64 + fs.OnLookup = func(string, string) { + lookups.Add(1) + if d := time.Duration(delay.Load()); d > 0 { + // spin: time.Sleep overshoots a delay this short several times over + for start := time.Now(); time.Since(start) < d; { + } + } + } + b.Cleanup(func() { fs.OnLookup = nil }) + + requests := []struct { + name string + handler http.HandlerFunc + input interface{} + }{ + {"GetVectorBucket", s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: "vec-bucket"}}, + {"GetVectorBucketPolicy", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"}}, + } + for _, req := range requests { + for _, rtt := range []time.Duration{0, 200 * time.Microsecond} { + b.Run(fmt.Sprintf("%s/rtt=%s", req.name, rtt), func(b *testing.B) { + delay.Store(int64(rtt)) + defer delay.Store(0) + lookups.Store(0) + ops := 0 + b.ReportAllocs() + for b.Loop() { + if w := postJSONAs(b, "", req.handler, req.input); w.Code != http.StatusOK { + b.Fatalf("%s = %d %s", req.name, w.Code, w.Body.String()) + } + ops++ + } + b.ReportMetric(float64(lookups.Load())/float64(ops), "lookups/op") + }) + } + } +} diff --git a/weed/s3api/s3vectors/authorize_lookups_test.go b/weed/s3api/s3vectors/authorize_lookups_test.go new file mode 100644 index 0000000000..c5c941efdc --- /dev/null +++ b/weed/s3api/s3vectors/authorize_lookups_test.go @@ -0,0 +1,65 @@ +package s3vectors + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest" +) + +// Authorizing a vector request needs the bucket's record, its s3vectors policy +// and its tags, all attributes of the one bucket entry. The check reads the +// record through the catalog's GetTableBucket and then the entry again for the +// policy and tags, three lookups of the same entry, and GetVectorBucketPolicy +// reads it a fourth time for the policy it returns. One lookup is enough. +func TestVectorAuthorizationLooksUpTheBucketOnce(t *testing.T) { + fs := s3tablestest.Start(t) + s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0)) + if w := postJSONAs(t, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK { + t.Fatalf("create bucket: %d %s", w.Code, w.Body.String()) + } + const policy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:*","Resource":"*"}]}` + if w := postJSONAs(t, "", s.handlePutVectorBucketPolicy, &PutVectorBucketPolicyRequest{VectorBucketName: "vec-bucket", Policy: policy}); w.Code != http.StatusOK { + t.Fatalf("put policy: %d %s", w.Code, w.Body.String()) + } + dir, name := splitEntryPath(s3tables.GetTableBucketPath("vec-bucket")) + + cases := []struct { + name string + call func() int + }{ + {"authorizeVector", func() int { + r := httptest.NewRequest(http.MethodPost, "/", nil) + r = r.WithContext(contextWithIdentity(r.Context(), "")) + if _, err := s.authorizeVector(r.Context(), r, "s3vectors:GetVectorBucket", "vec-bucket", ""); err != nil { + t.Fatalf("authorize: %v", err) + } + return http.StatusOK + }}, + {"GetVectorBucket", func() int { + return postJSONAs(t, "", s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: "vec-bucket"}).Code + }}, + {"GetVectorBucketPolicy", func() int { + return postJSONAs(t, "", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"}).Code + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + lookups := 0 + fs.OnLookup = func(d, n string) { + if d == dir && n == name { + lookups++ + } + } + defer func() { fs.OnLookup = nil }() + if code := tc.call(); code != http.StatusOK { + t.Fatalf("%s = %d", tc.name, code) + } + if lookups != 1 { + t.Errorf("%s looked up the bucket %d times, want 1", tc.name, lookups) + } + }) + } +} diff --git a/weed/s3api/s3vectors/handlers.go b/weed/s3api/s3vectors/handlers.go index 271ba73e7a..69ae3c69a7 100644 --- a/weed/s3api/s3vectors/handlers.go +++ b/weed/s3api/s3vectors/handlers.go @@ -719,33 +719,15 @@ func stripVectorActions(raw string) (string, bool) { // identity for the authorization lookup; nothing reaches the caller until // the permission check below it passes. func (s *Server) vectorBucket(ctx context.Context, bucket string) (*s3tables.GetTableBucketResponse, error) { - var resp s3tables.GetTableBucketResponse - if err := s.internalCatalog(ctx, "GetTableBucket", - &s3tables.GetTableBucketRequest{TableBucketARN: s.s3tablesArn(bucket)}, &resp); err != nil { - return nil, err - } - return &resp, nil + record, _, err := s.vectorBucketEntry(ctx, bucket) + return record, err } -// vectorPolicy reads the bucket's stored s3vectors policy and its tags. A -// bucket written before the dedicated key carried the raw document in the -// shared policy slot; one that still names vector actions keeps working until -// the next vector policy write migrates it out. -func (s *Server) vectorPolicy(ctx context.Context, bucket string) (policy string, tags map[string]string, err error) { - dir, name := splitEntryPath(s3tables.GetTableBucketPath(bucket)) - err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{ - Directory: dir, - Name: name, - }) - if err != nil { - return err - } - policy = vectorPolicyFromExt(resp.Entry.Extended) - tags, err = tagsFromExt(resp.Entry.Extended) - return err - }) - return policy, tags, err +// vectorBucketEntry is vectorBucket plus the attributes of the bucket entry +// the record was read from: its policy and tags, with no second lookup. +func (s *Server) vectorBucketEntry(ctx context.Context, bucket string) (*s3tables.GetTableBucketResponse, map[string][]byte, error) { + return s.internal.GetTableBucketEntry(ctx, s.filerClient, + &s3tables.GetTableBucketRequest{TableBucketARN: s.s3tablesArn(bucket)}, "") } // indexTags reads an index's tags; one not created yet has none. @@ -949,35 +931,44 @@ func (s *Server) authorizeVector(ctx context.Context, r *http.Request, action, b // authorizeVectorTags is authorizeVector for a request that sets or removes // tags. func (s *Server) authorizeVectorTags(ctx context.Context, r *http.Request, action, bucket, index string, req tagRequest) (*s3tables.GetTableBucketResponse, error) { + record, _, err := s.authorizeVectorPolicy(ctx, r, action, bucket, index, req) + return record, err +} + +// authorizeVectorPolicy is authorizeVectorTags that also returns the +// s3vectors policy the request was granted under. The record, the policy and +// the tags all come from one read of the bucket entry. +func (s *Server) authorizeVectorPolicy(ctx context.Context, r *http.Request, action, bucket, index string, req tagRequest) (*s3tables.GetTableBucketResponse, string, error) { setRequestTarget(r, bucket, index) - record, err := s.vectorBucket(ctx, bucket) + record, ext, err := s.vectorBucketEntry(ctx, bucket) if err != nil { - return nil, err + return nil, "", err } - policy, bucketTags, err := s.vectorPolicy(ctx, bucket) + policy := vectorPolicyFromExt(ext) + bucketTags, err := tagsFromExt(ext) if err != nil { - return nil, err + return nil, "", err } resourceARN, resourceTags := s.vectorBucketArn(bucket), bucketTags if index != "" { resourceARN, resourceTags = s.indexArn(bucket, index), nil if _, usesIAM := s.authenticator.(IAMAuthorizer); readsResourceTags(policy) || usesIAM { if resourceTags, err = s.indexTags(ctx, bucket, index); err != nil { - return nil, err + return nil, "", err } } } principal := s.tables.PrincipalFor(r) if !s.checkPermission(r, action, principal, record.OwnerAccountID, policy, resourceARN, s.policyContext(r, bucket, bucketTags, resourceTags, req)) { - return nil, &s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "access denied"} + return nil, "", &s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "access denied"} } if !isVectorBucket(record) { - return nil, &s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchBucket, + return nil, "", &s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchBucket, Message: fmt.Sprintf("vector bucket %s not found", bucket)} } authorizeRequest(r, bucket, index) - return record, nil + return record, policy, nil } func (s *Server) handlePutVectorBucketPolicy(w http.ResponseWriter, r *http.Request) { @@ -1039,11 +1030,8 @@ func (s *Server) handleGetVectorBucketPolicy(w http.ResponseWriter, r *http.Requ writeError(w, http.StatusBadRequest, "ValidationException", err.Error()) return } - if _, err := s.authorizeVector(r.Context(), r, "s3vectors:GetVectorBucketPolicy", arns.bucket, ""); err != nil { - catalogErr(w, err) - return - } - policy, _, err := s.vectorPolicy(r.Context(), arns.bucket) + // The policy returned is the one the request was granted under. + _, policy, err := s.authorizeVectorPolicy(r.Context(), r, "s3vectors:GetVectorBucketPolicy", arns.bucket, "", tagRequest{}) if err != nil { catalogErr(w, err) return diff --git a/weed/s3api/s3vectors/handlers_test.go b/weed/s3api/s3vectors/handlers_test.go index bc13c8f86f..688f6db080 100644 --- a/weed/s3api/s3vectors/handlers_test.go +++ b/weed/s3api/s3vectors/handlers_test.go @@ -833,7 +833,7 @@ func TestValidateVectorPolicy(t *testing.T) { // postJSONAs runs the handler under a named identity: empty resolves to the // account the catalog would charge, a name is a non-owner principal. -func postJSONAs(t *testing.T, identity string, handler http.HandlerFunc, payload interface{}) *httptest.ResponseRecorder { +func postJSONAs(t testing.TB, identity string, handler http.HandlerFunc, payload interface{}) *httptest.ResponseRecorder { t.Helper() body, err := json.Marshal(payload) if err != nil { diff --git a/weed/s3api/s3vectors/vector_bucket_read_test.go b/weed/s3api/s3vectors/vector_bucket_read_test.go new file mode 100644 index 0000000000..0fba370f6e --- /dev/null +++ b/weed/s3api/s3vectors/vector_bucket_read_test.go @@ -0,0 +1,156 @@ +package s3vectors + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest" +) + +// These tests pin how a vector request reads its bucket: the answers a +// missing, damaged or foreign bucket entry gives, and the catalog's own +// rules the read still honours. + +// startReadBucket creates vec-bucket and returns its filer entry location. +func startReadBucket(t *testing.T) (*s3tablestest.MemFiler, *Server, string, string) { + t.Helper() + fs := s3tablestest.Start(t) + s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0)) + if w := postJSONAs(t, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK { + t.Fatalf("create bucket: %d %s", w.Code, w.Body.String()) + } + dir, name := splitEntryPath(s3tables.GetTableBucketPath("vec-bucket")) + return fs, s, dir, name +} + +// editBucket rewrites the bucket entry's attributes. +func editBucket(fs *s3tablestest.MemFiler, dir, name string, edit func(ext map[string][]byte)) { + ext := fs.Get(dir, name).Extended + edit(ext) + fs.Put(dir, name, ext) +} + +func setBucketMetadata(t *testing.T, key string, value interface{}) func(ext map[string][]byte) { + return func(ext map[string][]byte) { + var meta map[string]interface{} + if err := json.Unmarshal(ext[s3tables.ExtendedKeyMetadata], &meta); err != nil { + t.Fatalf("decode bucket metadata: %v", err) + } + meta[key] = value + data, err := json.Marshal(meta) + if err != nil { + t.Fatal(err) + } + ext[s3tables.ExtendedKeyMetadata] = data + } +} + +const ( + catalogDenyGetBucket = `{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*","Action":"s3tables:GetTableBucket","Resource":"*"}]}` + catalogAllowGetBucket = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:GetTableBucket","Resource":"*"}]}` +) + +func TestVectorBucketReadAnswers(t *testing.T) { + for _, tc := range []struct { + name string + bucket string + edit func(t *testing.T) func(ext map[string][]byte) + identity string + want int + wantType string + }{ + {name: "intact", want: http.StatusOK}, + {name: "absent", bucket: "nope", want: http.StatusNotFound, wantType: "NotFoundException"}, + {name: "no metadata", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { delete(ext, s3tables.ExtendedKeyMetadata) } + }, want: http.StatusNotFound, wantType: "NotFoundException"}, + {name: "damaged metadata", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyMetadata] = []byte("{bad") } + }, want: http.StatusInternalServerError, wantType: "InternalFailure"}, + // The catalog's record check reads no bucket marker. + {name: "no bucket marker", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { delete(ext, s3tables.ExtendedKeyTableBucket) } + }, want: http.StatusOK}, + {name: "damaged tags", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyTags] = []byte("{bad") } + }, want: http.StatusInternalServerError, wantType: "InternalFailure"}, + {name: "damaged tags under a catalog policy", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { + ext[s3tables.ExtendedKeyTags] = []byte("{bad") + ext[s3tables.ExtendedKeyPolicy] = []byte(catalogAllowGetBucket) + } + }, want: http.StatusInternalServerError, wantType: "InternalFailure"}, + // The record is read through the catalog's GetTableBucket, so a deny + // of that action in the shared policy slot hides the bucket. + {name: "catalog deny of GetTableBucket", edit: func(t *testing.T) func(map[string][]byte) { + return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(catalogDenyGetBucket) } + }, want: http.StatusNotFound, wantType: "NotFoundException"}, + // The permission check comes before the format check, so a caller + // that may not read the bucket does not learn it is no vector bucket. + {name: "iceberg bucket", edit: func(t *testing.T) func(map[string][]byte) { + return setBucketMetadata(t, "format", s3tables.FormatIceberg) + }, want: http.StatusNotFound, wantType: "NotFoundException"}, + {name: "iceberg bucket, foreign caller", edit: func(t *testing.T) func(map[string][]byte) { + return setBucketMetadata(t, "format", s3tables.FormatIceberg) + }, identity: "stranger", want: http.StatusForbidden, wantType: "AccessDeniedException"}, + } { + t.Run(tc.name, func(t *testing.T) { + fs, s, dir, name := startReadBucket(t) + if tc.edit != nil { + editBucket(fs, dir, name, tc.edit(t)) + } + bucket := tc.bucket + if bucket == "" { + bucket = "vec-bucket" + } + w := postJSONAs(t, tc.identity, s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: bucket}) + if w.Code != tc.want { + t.Fatalf("GetVectorBucket = %d %s, want %d", w.Code, w.Body.String(), tc.want) + } + if tc.wantType != "" { + var body struct { + Type string `json:"__type"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Type != tc.wantType { + t.Fatalf("GetVectorBucket error = %s, want %s", w.Body.String(), tc.wantType) + } + } + }) + } +} + +// The policy GetVectorBucketPolicy returns is the bucket's s3vectors policy: +// the dedicated key, else a shared-slot document naming vector actions, and +// none for a bucket without either. +func TestGetVectorBucketPolicyAnswers(t *testing.T) { + const vectorPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:GetVectorBucketPolicy","Resource":"*"}]}` + for _, tc := range []struct { + name string + edit func(ext map[string][]byte) + want int + body string + }{ + {"none", func(map[string][]byte) {}, http.StatusNotFound, ""}, + {"dedicated key", func(ext map[string][]byte) { ext[vectorPolicyKey] = []byte(vectorPolicy) }, http.StatusOK, vectorPolicy}, + {"legacy shared slot", func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(vectorPolicy) }, http.StatusOK, vectorPolicy}, + {"catalog-only shared slot", func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(catalogAllowGetBucket) }, http.StatusNotFound, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + fs, s, dir, name := startReadBucket(t) + editBucket(fs, dir, name, tc.edit) + w := postJSONAs(t, "", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"}) + if w.Code != tc.want { + t.Fatalf("GetVectorBucketPolicy = %d %s, want %d", w.Code, w.Body.String(), tc.want) + } + if tc.body == "" { + return + } + var resp GetVectorBucketPolicyResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || resp.Policy != tc.body { + t.Fatalf("GetVectorBucketPolicy = %s, want policy %s", w.Body.String(), tc.body) + } + }) + } +}