diff --git a/weed/s3api/iceberg/handlers_commit.go b/weed/s3api/iceberg/handlers_commit.go index 30547f1e11..c6b4c42c65 100644 --- a/weed/s3api/iceberg/handlers_commit.go +++ b/weed/s3api/iceberg/handlers_commit.go @@ -153,7 +153,8 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { } stagedMetadataBytes, loadErr := s.loadMetadataFile(r.Context(), stagedBucket, stagedPath, stagedFileName) if loadErr != nil { - if !errors.Is(loadErr, filer_pb.ErrNotFound) { + // a staged create's empty placeholder is no template + if !errors.Is(loadErr, filer_pb.ErrNotFound) && !errors.Is(loadErr, errEmptyMetadataFile) { writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to load staged metadata: "+loadErr.Error()) return } @@ -252,6 +253,10 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { writeError(w, reqErr.status, reqErr.errType, reqErr.message) return } + if reqErr := refuseCatalogOnlyCommit(getResp, tableName); reqErr != nil { + writeError(w, reqErr.status, reqErr.errType, reqErr.message) + return + } location := tableLocation(getResp, bucketName, namespace, tableName) locBucket, locPath, locErr := parseS3Location(location) @@ -301,6 +306,11 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { return } } + // the stored UUID follows the metadata the commit builds on, not a + // record's that disagrees with it + if u := currentMetadata.TableUUID(); u != uuid.Nil { + tableUUID = u + } for _, requirement := range req.Requirements { if err := requirement.Validate(currentMetadata); err != nil { diff --git a/weed/s3api/iceberg/handlers_table.go b/weed/s3api/iceberg/handlers_table.go index 7192d23aec..4e5e1c49c0 100644 --- a/weed/s3api/iceberg/handlers_table.go +++ b/weed/s3api/iceberg/handlers_table.go @@ -407,33 +407,25 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) { bucketARN := buildTableBucketARN(bucketName) identityName := s3_constants.GetIdentityNameFromContext(r) - // Read the existing metadata object before registering, so a bad location - // is rejected (400) without leaving a dangling catalog entry. - metadataBucket, tablePath, err := parseS3Location(tableLocationFromMetadataLocation(req.MetadataLocation)) - if err != nil { + // The location is checked without reading anything (in the bucket, no + // traversal, a file directly in a table's metadata directory), then the + // caller's right to create the table and the location's owner, and only + // then is anything read: the file read (and, in a mounted bucket, fetched) + // on a caller's word would otherwise tell a caller without rights whether a + // file exists and is metadata. + if _, err := metadataLocationPath(bucketName, req.MetadataLocation); err != nil { writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid metadata-location: "+err.Error()) return } - // metadata-location is client-supplied; confine the read to the authorized - // catalog bucket and reject traversal segments so path.Join in - // loadMetadataFile cannot escape into another bucket. - if metadataBucket != bucketName { - writeError(w, http.StatusBadRequest, "BadRequestException", "metadata-location must be within bucket "+bucketName) - return - } - if !isValidTablePath(tablePath) { - writeError(w, http.StatusBadRequest, "BadRequestException", "invalid metadata-location path") - return - } if authErr := s.authorizeCreateTable(r.Context(), bucketARN, namespace, req.Name, identityName, req.MetadataLocation); authErr != nil { writeManagerError(w, authErr) return } - metadataFileName := path.Base(req.MetadataLocation) // A table migrated in has its metadata uploaded through the S3 gateway, - // which stores it in chunks rather than inline, so follow the chunks. - metadataBytes, err := s.loadTableMetadataBlob(r.Context(), metadataBucket, tablePath, metadataFileName) + // which stores it in chunks rather than inline; in a remote-mounted bucket + // it may be held only remotely. metadataAtLocation reads both. + metadataBytes, err := s.metadataAtLocation(r.Context(), bucketName, req.MetadataLocation) if err != nil { glog.V(1).Infof("Iceberg: RegisterTable load metadata at %s: %v", req.MetadataLocation, err) writeError(w, http.StatusBadRequest, "BadRequestException", "Cannot read metadata at "+req.MetadataLocation) @@ -444,6 +436,12 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "BadRequestException", fmt.Sprintf("Invalid metadata at %s: %v", req.MetadataLocation, err)) return } + // the metadata describes the table at this location, not another one: a + // file copied from another table names that table's files + if want := tableLocationFromMetadataLocation(req.MetadataLocation); strings.TrimSuffix(registered.Location(), "/") != strings.TrimSuffix(want, "/") { + writeError(w, http.StatusBadRequest, "BadRequestException", fmt.Sprintf("the metadata's location %s is not %s", registered.Location(), want)) + return + } registeredMetadata := &s3tables.TableMetadata{ Iceberg: &s3tables.IcebergMetadata{TableUUID: registered.TableUUID().String()}, @@ -568,13 +566,11 @@ func (s *Server) buildLoadTableResult(r *http.Request, getResp s3tables.GetTable } var metadata table.Metadata if len(metadataBytes) > 0 { + // metadata that does not parse fails the load: an empty table in its + // place reads as no rows, and a writer could commit over it metadata, err = table.ParseMetadataBytes(metadataBytes) if err != nil { - glog.Warningf("Iceberg: Failed to parse persisted metadata for %s: %v", tableName, err) - // Attempt to reconstruct from IcebergMetadata if available, otherwise synthetic - // TODO: Extract schema/spec from getResp.Metadata.Iceberg if FullMetadata fails but partial info exists? - // For now, fallback to empty metadata - metadata, err = newTableMetadata(tableUUID, location, nil, nil, nil, nil) + return LoadTableResult{}, fmt.Errorf("read metadata of %s at %s: %w", tableName, getResp.MetadataLocation, err) } } else { // No full metadata, create synthetic diff --git a/weed/s3api/iceberg/handlers_transaction.go b/weed/s3api/iceberg/handlers_transaction.go index 9aab8985d4..87ceba8b87 100644 --- a/weed/s3api/iceberg/handlers_transaction.go +++ b/weed/s3api/iceberg/handlers_transaction.go @@ -142,6 +142,9 @@ func (s *Server) prepareTableCommit(ctx context.Context, bucketName, bucketARN, if reqErr := s.authorizeCommit(ctx, bucketARN, namespace, tableName, identityName); reqErr != nil { return nil, reqErr } + if reqErr := refuseCatalogOnlyCommit(getResp, tableName); reqErr != nil { + return nil, reqErr + } location := tableLocation(getResp, bucketName, namespace, tableName) locBucket, locPath, locErr := parseS3Location(location) @@ -183,6 +186,11 @@ func (s *Server) prepareTableCommit(ctx context.Context, bucketName, bucketARN, return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to build current metadata"} } } + // the stored UUID follows the metadata the transaction builds on, not a + // record's that disagrees with it + if u := currentMetadata.TableUUID(); u != uuid.Nil { + tableUUID = u + } for _, requirement := range requirements { if err := requirement.Validate(currentMetadata); err != nil { @@ -391,3 +399,12 @@ func (s *Server) cleanupPreparedMetadata(ctx context.Context, prepared []prepare } } } + +// refuseCatalogOnlyCommit refuses an Iceberg commit to a catalog-only table: +// its record's location is the dataset root its own client owns. +func refuseCatalogOnlyCommit(getResp s3tables.GetTableResponse, tableName string) *icebergRequestError { + if !s3tables.IsCatalogOnlyFormat(getResp.Format) { + return nil + } + return &icebergRequestError{http.StatusBadRequest, "BadRequestException", fmt.Sprintf("table %s is a %s table, not an Iceberg table", tableName, getResp.Format)} +} diff --git a/weed/s3api/iceberg/iceberg_access_delegation_test.go b/weed/s3api/iceberg/iceberg_access_delegation_test.go index 5b3ee9ba57..f5c8672d08 100644 --- a/weed/s3api/iceberg/iceberg_access_delegation_test.go +++ b/weed/s3api/iceberg/iceberg_access_delegation_test.go @@ -1,10 +1,12 @@ package iceberg import ( + "encoding/json" "net/http" "net/http/httptest" "testing" + "github.com/google/uuid" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" ) @@ -68,7 +70,17 @@ func TestLoadTableResultOmitsConfigForCredentialVendingClients(t *testing.T) { r := httptest.NewRequest(http.MethodGet, "/v1/namespaces/ns/tables/t", nil) r.Header.Set(accessDelegationHeader, "vended-credentials") - getResp := s3tables.GetTableResponse{MetadataLocation: "s3://bkt/ns/t/metadata/v1.metadata.json"} + // stored with its metadata, as a create stores it: a location whose file + // cannot be read fails the load (TestBuildLoadTableResultNeverReturnsNilMetadata) + md, err := newTableMetadata(uuid.New(), "s3://bkt/ns/t", nil, nil, nil, nil) + if err != nil { + t.Fatal(err) + } + full, err := json.Marshal(md) + if err != nil { + t.Fatal(err) + } + getResp := s3tables.GetTableResponse{MetadataLocation: "s3://bkt/ns/t/metadata/v1.metadata.json", Metadata: &s3tables.TableMetadata{FullMetadata: full}} result, err := s.buildLoadTableResult(r, getResp, "bkt", []string{"ns"}, "t") if err != nil { t.Fatalf("buildLoadTableResult() error = %v", err) diff --git a/weed/s3api/iceberg/iceberg_commit_authorize_test.go b/weed/s3api/iceberg/iceberg_commit_authorize_test.go index fc13c64dc9..f0735682e3 100644 --- a/weed/s3api/iceberg/iceberg_commit_authorize_test.go +++ b/weed/s3api/iceberg/iceberg_commit_authorize_test.go @@ -3,6 +3,7 @@ package iceberg import ( "context" "encoding/json" + "github.com/google/uuid" "net/http" "net/http/httptest" "path" @@ -47,8 +48,11 @@ func seedOwnedTable(fc *memFiler, bucket, namespace, tableName, owner string) { "versionToken": "v1", "metadataVersion": 1, "metadataLocation": "s3://" + bucket + "/" + namespace + "/" + tableName + "/metadata/v1.metadata.json", + // stored with its metadata, as a create stores it: a table with a location and no + // readable metadata is refused a commit rather than given an empty base "metadata": s3tables.TableMetadata{ - Iceberg: &s3tables.IcebergMetadata{TableUUID: "00000000-0000-0000-0000-000000000001"}, + Iceberg: &s3tables.IcebergMetadata{TableUUID: "00000000-0000-0000-0000-000000000001"}, + FullMetadata: ownedTableMetadata(bucket, namespace, tableName), }, } metaBytes, _ := json.Marshal(internal) @@ -59,6 +63,19 @@ func seedOwnedTable(fc *memFiler, bucket, namespace, tableName, owner string) { }) } +// ownedTableMetadata is an empty table's metadata.json at the table's location. +func ownedTableMetadata(bucket, namespace, tableName string) json.RawMessage { + md, err := newTableMetadata(uuid.MustParse("00000000-0000-0000-0000-000000000001"), "s3://"+bucket+"/"+namespace+"/"+tableName, nil, nil, nil, nil) + if err != nil { + panic(err) + } + b, err := json.Marshal(md) + if err != nil { + panic(err) + } + return b +} + // seedOwnedView registers an existing view owned by owner. func seedOwnedView(fc *memFiler, bucket, namespace, viewName, owner string, fullMetadata []byte) { internal := map[string]any{ diff --git a/weed/s3api/iceberg/iceberg_create_table_test.go b/weed/s3api/iceberg/iceberg_create_table_test.go index e566f476b9..e090edeb57 100644 --- a/weed/s3api/iceberg/iceberg_create_table_test.go +++ b/weed/s3api/iceberg/iceberg_create_table_test.go @@ -94,10 +94,20 @@ func TestNewTableMetadataAcceptsV3TypeAtV3(t *testing.T) { // A LoadTable response must never carry nil metadata: it serializes as // "metadata":null under HTTP 200, which no Iceberg client can parse. func TestBuildLoadTableResultNeverReturnsNilMetadata(t *testing.T) { + // A table stored with its location alone is served from the file there + // (TestRegisteredTableLoadsWithItsMetadata); when that cannot be read the + // load fails rather than serving an empty table. + r := httptest.NewRequest(http.MethodGet, "/v1/namespaces/ns/tables/t", nil) + if _, err := (&Server{filerClient: newMemFiler()}).buildLoadTableResult(r, s3tables.GetTableResponse{MetadataLocation: "s3://bkt/ns/t/metadata/v1.metadata.json"}, "bkt", []string{"ns"}, "t"); err == nil { + t.Error("a location whose metadata cannot be read: want an error, not an empty table") + } + // stored metadata that does not parse fails the load rather than serving an empty table + if _, err := (&Server{filerClient: newMemFiler()}).buildLoadTableResult(r, s3tables.GetTableResponse{Metadata: &s3tables.TableMetadata{FullMetadata: json.RawMessage(`{"nope":`)}}, "bkt", []string{"ns"}, "t"); err == nil { + t.Error("unparseable stored metadata: want an error, not an empty table") + } cases := map[string]s3tables.GetTableResponse{ - "no stored metadata": {MetadataLocation: "s3://bkt/ns/t/metadata/v1.metadata.json"}, - "empty full metadata": {Metadata: &s3tables.TableMetadata{}}, - "unparseable metadata": {Metadata: &s3tables.TableMetadata{FullMetadata: json.RawMessage(`{"nope":`)}}, + "empty full metadata": {Metadata: &s3tables.TableMetadata{}}, + "no location": {}, } for name, getResp := range cases { t.Run(name, func(t *testing.T) { diff --git a/weed/s3api/iceberg/iceberg_register_load_test.go b/weed/s3api/iceberg/iceberg_register_load_test.go new file mode 100644 index 0000000000..b252af9d82 --- /dev/null +++ b/weed/s3api/iceberg/iceberg_register_load_test.go @@ -0,0 +1,669 @@ +package iceberg + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "path" + "strings" + "testing" + + "github.com/apache/iceberg-go/table" + "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/s3tables" + "google.golang.org/grpc" +) + +// registeredMetadata is a table's metadata.json with a schema and a snapshot, +// as a table that was written to and then unmounted leaves it. +const registeredMetadata = `{ + "format-version": 2, "table-uuid": "9c12d441-03fe-4693-9a96-a0705ddf69c1", "location": "s3://warehouse/finance/orders", + "last-sequence-number": 1, "last-updated-ms": 1700000000000, "last-column-id": 2, + "current-schema-id": 0, "schemas": [{"type": "struct", "schema-id": 0, "fields": [ + {"id": 1, "name": "id", "required": true, "type": "long"}, {"id": 2, "name": "name", "required": false, "type": "string"}]}], + "default-spec-id": 0, "partition-specs": [{"spec-id": 0, "fields": []}], "last-partition-id": 999, + "default-sort-order-id": 0, "sort-orders": [{"order-id": 0, "fields": []}], "properties": {}, + "current-snapshot-id": 3055729675574597004, + "snapshots": [{"snapshot-id": 3055729675574597004, "sequence-number": 1, "timestamp-ms": 1700000000000, + "manifest-list": "s3://warehouse/finance/orders/metadata/snap-3055729675574597004-1.avro", "summary": {"operation": "append"}, "schema-id": 0}], + "snapshot-log": [{"snapshot-id": 3055729675574597004, "timestamp-ms": 1700000000000}], "metadata-log": [], + "refs": {"main": {"snapshot-id": 3055729675574597004, "type": "branch"}} +}` + +const registeredLocation = "s3://warehouse/finance/orders/metadata/00001-4c1f6d0e-2b1a-4d39-9d37-0f6a7c7f1b11.metadata.json" + +// remoteMemFiler holds some files only as their RemoteEntry, as a remote-mounted +// bucket does for files not cached here; caching one gives it its content. +type remoteMemFiler struct { + *memFiler + remote map[string][]byte + cached int +} + +func (m *remoteMemFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error { + return fn(m) +} + +func (m *remoteMemFiler) CacheRemoteObjectToLocalCluster(_ context.Context, in *filer_pb.CacheRemoteObjectToLocalClusterRequest, _ ...grpc.CallOption) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) { + p := path.Join(in.Directory, in.Name) + content, ok := m.remote[p] + if !ok { + return nil, filer_pb.ErrNotFound + } + if in.MaxSize > 0 && int64(len(content)) > in.MaxSize { + return nil, fmt.Errorf("remote object %s is %d bytes, over the %d byte limit", p, len(content), in.MaxSize) + } + m.cached++ + entry := &filer_pb.Entry{Name: in.Name, Content: content, RemoteEntry: m.entries[p].RemoteEntry} + m.entries[p] = entry + return &filer_pb.CacheRemoteObjectToLocalClusterResponse{Entry: entry}, nil +} + +func seedRegisteredFile(fc *memFiler, content []byte, remoteOnly bool) { + dir := metadataDirPath("warehouse", "finance/orders") + name := path.Base(registeredLocation) + entry := &filer_pb.Entry{Name: name, Content: content} + if remoteOnly { + entry = &filer_pb.Entry{Name: name, RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: int64(len(content))}} + } + fc.seed(path.Join(dir, name), entry) +} + +func registerRequest(t *testing.T, body string) *http.Request { + t.Helper() + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/register", strings.NewReader(body)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance"}) + return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) +} + +func loadTable(t *testing.T, s *Server) (int, table.Metadata, string) { + t.Helper() + r := httptest.NewRequest(http.MethodGet, "/v1/warehouse/namespaces/finance/tables/orders", nil) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleLoadTable(w, r) + if w.Code != http.StatusOK { + return w.Code, nil, w.Body.String() + } + var resp struct { + MetadataLocation string `json:"metadata-location"` + Metadata json.RawMessage `json:"metadata"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode load: %v", err) + } + md, err := table.ParseMetadataBytes(resp.Metadata) + if err != nil { + t.Fatalf("parse loaded metadata: %v (%s)", err, resp.Metadata) + } + return w.Code, md, resp.MetadataLocation +} + +// assertSameTable checks a loaded table against the metadata.json it was +// registered from: schema, snapshots, current snapshot. +func assertSameTable(t *testing.T, got table.Metadata) { + t.Helper() + want, err := table.ParseMetadataBytes([]byte(registeredMetadata)) + if err != nil { + t.Fatal(err) + } + if !got.CurrentSchema().Equals(want.CurrentSchema()) { + t.Errorf("schema = %v, want %v", got.CurrentSchema(), want.CurrentSchema()) + } + if len(got.Snapshots()) != 1 || got.CurrentSnapshot() == nil || got.CurrentSnapshot().SnapshotID != want.CurrentSnapshot().SnapshotID { + t.Errorf("snapshots = %v, current = %v; want the one snapshot %d current", got.Snapshots(), got.CurrentSnapshot(), want.CurrentSnapshot().SnapshotID) + } + if got.TableUUID() != want.TableUUID() { + t.Errorf("table uuid = %v, want %v", got.TableUUID(), want.TableUUID()) + } +} + +// RegisterTable stored the metadata location alone, and LoadTable serves the +// stored metadata: a registered table loaded with no schema and no snapshots, +// and DuckDB read it as empty. The metadata.json is now read +// and stored with the table, whether it is inline here or held only on a +// mounted remote, as after an unmount and attach. +func TestRegisteredTableLoadsWithItsMetadata(t *testing.T) { + for _, remoteOnly := range []bool{false, true} { + name := map[bool]string{false: "inline", true: "remote-only"}[remoteOnly] + t.Run(name, func(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), remoteOnly) + if remoteOnly { + fc.remote[path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))] = []byte(registeredMetadata) + } + s := NewServer(fc, nil) + + w := httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusOK { + t.Fatalf("register: status %d, body %s", w.Code, w.Body.String()) + } + if remoteOnly && fc.cached != 1 { + t.Errorf("remote file cached %d times, want once (at register)", fc.cached) + } + // stored with the table, as a commit stores it: a load does not depend on the file + entry := fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")] + var stored struct { + Metadata *s3tables.TableMetadata `json:"metadata"` + } + if entry == nil || json.Unmarshal(entry.Extended[s3tables.ExtendedKeyMetadata], &stored) != nil || + stored.Metadata == nil || len(stored.Metadata.FullMetadata) == 0 { + t.Fatalf("the registered table holds no full metadata") + } + if md, err := table.ParseMetadataBytes(stored.Metadata.FullMetadata); err != nil { + t.Fatalf("stored metadata: %v", err) + } else { + assertSameTable(t, md) + } + + code, md, location := loadTable(t, s) + if code != http.StatusOK { + t.Fatalf("load: status %d (%s)", code, location) + } + if location != registeredLocation { + t.Errorf("metadata-location = %q, want %q", location, registeredLocation) + } + assertSameTable(t, md) + if remoteOnly && fc.cached != 1 { + t.Errorf("remote file cached %d times, want once: the load serves the stored metadata", fc.cached) + } + }) + } +} + +// A table registered before the fix holds its location alone: it loads from +// the metadata.json there, and a location that cannot be read fails the load +// rather than serving an empty table. +func TestATableStoredWithItsLocationAloneLoadsFromIt(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + seedRegisteredFile(fc, []byte(registeredMetadata), false) + s := NewServer(fc, nil) + // the registration as the unpatched store made it: no metadata + err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + var resp s3tables.RegisterTableResponse + return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + TableBucketARN: buildTableBucketARN("warehouse"), Namespace: []string{"finance"}, Name: "orders", MetadataLocation: registeredLocation, + }, &resp, "alice") + }) + if err != nil { + t.Fatalf("register without metadata: %v", err) + } + + code, md, body := loadTable(t, s) + if code != http.StatusOK { + t.Fatalf("load: status %d (%s)", code, body) + } + assertSameTable(t, md) + + // the file gone: the load fails + delete(fc.entries, path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))) + if code, _, _ := loadTable(t, s); code == http.StatusOK { + t.Error("load with its metadata.json gone: 200, want an error rather than an empty table") + } +} + +// A file at the location that is not table metadata is refused at register. +func TestRegisterRefusesAFileThatIsNotTableMetadata(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + seedRegisteredFile(fc, []byte(`{"not":"metadata"}`), false) + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusBadRequest { + t.Fatalf("status %d, want 400 (body %s)", w.Code, w.Body.String()) + } + if _, ok := fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")]; ok { + t.Error("a refused register left a catalog entry") + } +} + +// registerLocationOnly registers orders as the unpatched store did: its +// location alone, no metadata. +func registerLocationOnly(t *testing.T, fc *memFiler, s *Server) { + t.Helper() + err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + var resp s3tables.RegisterTableResponse + return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + TableBucketARN: buildTableBucketARN("warehouse"), Namespace: []string{"finance"}, Name: "orders", MetadataLocation: registeredLocation, + }, &resp, "alice") + }) + if err != nil { + t.Fatalf("register without metadata: %v", err) + } +} + +// A commit to a table stored with its location alone builds on the metadata +// there. It used to build on an empty table with a new UUID: a client's commit +// (its requirements taken from the load) was refused for ever on a UUID +// mismatch, and a commit without requirements replaced the table's history +// with an empty one. Both commit paths, the table +// commit and the multi-table transaction, are checked; with the file gone, +// both fail and the table is left as it was. +func TestACommitToALocationOnlyTableKeepsItsHistory(t *testing.T) { + want, err := table.ParseMetadataBytes([]byte(registeredMetadata)) + if err != nil { + t.Fatal(err) + } + requirements := `[{"type":"assert-table-uuid","uuid":"` + want.TableUUID().String() + `"},` + + `{"type":"assert-ref-snapshot-id","ref":"main","snapshot-id":3055729675574597004}]` + commit := map[string]func(s *Server, requirements string) int{ + "commit-table": func(s *Server, requirements string) int { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/orders", + strings.NewReader(`{"requirements":`+requirements+`,"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleUpdateTable(w, r) + return w.Code + }, + "commit-transaction": func(s *Server, requirements string) int { + body := `{"table-changes":[{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":` + requirements + + `,"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}` + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader(body)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleCommitTransaction(w, r) + return w.Code + }, + } + for name, do := range commit { + for _, reqs := range map[string]string{"with the load's requirements": requirements, "without requirements": "[]"} { + t.Run(name+" "+map[bool]string{true: "with requirements", false: "without requirements"}[reqs != "[]"], func(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + seedRegisteredFile(fc, []byte(registeredMetadata), false) + s := NewServer(fc, nil) + registerLocationOnly(t, fc, s) + + if code := do(s, reqs); code != http.StatusOK && code != http.StatusNoContent { + t.Fatalf("commit: status %d, want success", code) + } + code, md, body := loadTable(t, s) + if code != http.StatusOK { + t.Fatalf("load after commit: status %d (%s)", code, body) + } + assertSameTable(t, md) + if md.Properties()["k"] != "v" { + t.Errorf("properties = %v, want the commit's k=v", md.Properties()) + } + // the stored UUID is the metadata's + if _, stored := storedTableEntry(t, fc, "orders"); stored == nil || stored.Iceberg == nil || stored.Iceberg.TableUUID != want.TableUUID().String() { + t.Errorf("stored table uuid = %+v, want %s", stored, want.TableUUID()) + } + }) + } + t.Run(name+" with the file gone", func(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + s := NewServer(fc, nil) + seedRegisteredFile(fc, []byte(registeredMetadata), false) + registerLocationOnly(t, fc, s) + delete(fc.entries, path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))) + if code := do(s, "[]"); code < 500 { + t.Errorf("commit with the metadata.json gone: status %d, want a server error", code) + } + entry := fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")] + var stored struct { + MetadataLocation string `json:"metadataLocation"` + Metadata *s3tables.TableMetadata `json:"metadata"` + } + if err := json.Unmarshal(entry.Extended[s3tables.ExtendedKeyMetadata], &stored); err != nil || stored.MetadataLocation != registeredLocation || stored.Metadata != nil { + t.Errorf("the table moved after a refused commit: %+v (err %v)", stored, err) + } + }) + } +} + +// A remote file is checked against the metadata size limit before it is +// fetched, and a location below the metadata directory is refused rather +// than read as a same-named file there. +func TestRegisterRefusesOversizedRemoteFilesAndNestedLocations(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + p := path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation)) + fc.seed(p, &filer_pb.Entry{Name: path.Base(registeredLocation), RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: maxMetadataFileSize + 1}}) + fc.remote[p] = []byte(registeredMetadata) + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusBadRequest || fc.cached != 0 { + t.Errorf("an oversized remote file: status %d, cached %d times; want 400 and no fetch", w.Code, fc.cached) + } + + fc2 := newMemFiler() + seedNamespace(fc2, "warehouse", "finance", "alice") + seedRegisteredFile(fc2, []byte(registeredMetadata), false) + s2 := NewServer(fc2, nil) + nested := strings.Replace(registeredLocation, "/metadata/", "/metadata/sub/", 1) + w = httptest.NewRecorder() + s2.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+nested+`"}`)) + if w.Code != http.StatusBadRequest { + t.Errorf("a nested location %s: status %d, want 400 (it would read %s)", nested, w.Code, registeredLocation) + } + // control: the same file at its own location registers + w = httptest.NewRecorder() + s2.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusOK { + t.Errorf("control: status %d, want 200 (%s)", w.Code, w.Body.String()) + } +} + +// failingFlipFiler fails the catalog update of one table: the pointer flip of +// that table in a transaction. +type failingFlipFiler struct { + *memFiler + failPath string + // onFail runs as the failing flip is refused; beforeUpdate before every + // other update: each can land a concurrent write + onFail func() + beforeUpdate func(p string, conditional bool) +} + +func (m *failingFlipFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error { + return fn(m) +} + +func (m *failingFlipFiler) UpdateEntry(ctx context.Context, in *filer_pb.UpdateEntryRequest, opts ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) { + if path.Join(in.Directory, in.Entry.Name) == m.failPath { + if m.onFail != nil { + m.onFail() + } + return nil, errors.New("injected flip failure") + } + if m.beforeUpdate != nil { + m.beforeUpdate(path.Join(in.Directory, in.Entry.Name), len(in.ExpectedExtended) > 0) + } + return m.memFiler.UpdateEntry(ctx, in, opts...) +} + +func storedTableEntry(t *testing.T, fc *memFiler, name string) (location string, md *s3tables.TableMetadata) { + t.Helper() + entry := fc.entries[s3tables.GetTablePath("warehouse", "finance", name)] + var stored struct { + MetadataLocation string `json:"metadataLocation"` + Metadata *s3tables.TableMetadata `json:"metadata"` + } + if entry == nil || json.Unmarshal(entry.Extended[s3tables.ExtendedKeyMetadata], &stored) != nil { + t.Fatalf("no catalog entry for %s", name) + } + return stored.MetadataLocation, stored.Metadata +} + +// A transaction over a location-only table and a second table whose flip +// fails rolls the first back to the table as it was read; with no stored +// metadata the restore used to keep the failed transaction's metadata, and +// readers saw the rolled-back change. +func TestARolledBackTransactionRestoresALocationOnlyTable(t *testing.T) { + fc := &failingFlipFiler{memFiler: newMemFiler(), failPath: s3tables.GetTablePath("warehouse", "finance", "b")} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), false) + seedOwnedTable(fc.memFiler, "warehouse", "finance", "b", "alice") + s := NewServer(fc, nil) + registerLocationOnly(t, fc.memFiler, s) + + body := `{"table-changes":[` + + `{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]},` + + `{"identifier":{"namespace":["finance"],"name":"b"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}` + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader(body)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleCommitTransaction(w, r) + if w.Code < 400 { + t.Fatalf("transaction with a failing flip: status %d, want a failure", w.Code) + } + + location, _ := storedTableEntry(t, fc.memFiler, "orders") + if location != registeredLocation { + t.Errorf("orders points at %s after the rollback, want %s", location, registeredLocation) + } + code, md, body2 := loadTable(t, s) + if code != http.StatusOK { + t.Fatalf("load after rollback: %d (%s)", code, body2) + } + assertSameTable(t, md) + if _, ok := md.Properties()["k"]; ok { + t.Errorf("properties = %v: the rolled-back change is visible", md.Properties()) + } +} + +// Register checks the caller's right to create the table before it reads, +// or fetches, anything at the location: a caller without rights gets one +// answer whether the file exists, is metadata, or is absent. +func TestRegisterRefusesACallerWithoutRightsBeforeReading(t *testing.T) { + for _, file := range []string{"metadata", "absent"} { + t.Run(file, func(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + if file == "metadata" { + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), true) + fc.remote[path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))] = []byte(registeredMetadata) + } + s := NewServer(fc, nil) + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/register", + strings.NewReader(`{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "mallory")) + w := httptest.NewRecorder() + s.handleRegisterTable(w, r) + if w.Code != http.StatusForbidden { + t.Errorf("status %d, want 403 (body %s)", w.Code, w.Body.String()) + } + if fc.cached != 0 { + t.Errorf("the remote file was fetched %d times for a caller without rights", fc.cached) + } + }) + } +} + +// A register may not point at the location another table of the bucket holds +// in any namespace: a rename moves the catalog record and leaves +// the files, so a table renamed into hr still owns finance/orders, and an +// alias registered there would read it and be vended credentials for its files +// under finance's grants. The refusal names no table. Once the owner is +// dropped the location is free again. The metadata must describe the table at +// the location it is registered from. +func TestRegisterRefusesAnotherTablesLocationAndAForeignMetadataLocation(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + seedNamespace(fc.memFiler, "warehouse", "hr", "alice") + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), false) + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusOK { + t.Fatalf("control register: %d (%s)", w.Code, w.Body.String()) + } + w = httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders_copy","metadata-location":"`+registeredLocation+`"}`)) + // a location another record holds: 409, naming no table (#12473) + if w.Code != http.StatusConflict || strings.Contains(w.Body.String(), "orders") { + t.Errorf("a second entry for orders' files: status %d (%s), want 409 naming no table", w.Code, w.Body.String()) + } + + // orders renamed into hr keeps its files under finance/orders + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/tables/rename", strings.NewReader( + `{"source":{"namespace":["finance"],"name":"orders"},"destination":{"namespace":["hr"],"name":"orders"}}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"}) + w = httptest.NewRecorder() + s.handleRenameTable(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))) + if w.Code != http.StatusNoContent { + t.Fatalf("rename finance.orders to hr.orders: %d (%s)", w.Code, w.Body.String()) + } + // refused before the file is read: in a mounted bucket, not even fetched + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), true) + fc.remote[path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))] = []byte(registeredMetadata) + w = httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"alias","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusConflict || fc.cached != 0 { + t.Errorf("an alias of the files hr.orders kept under finance: status %d (%s), fetched %d times, want 409 and none", w.Code, w.Body.String(), fc.cached) + } + + // positive control: the same register goes through once hr.orders is gone + r = httptest.NewRequest(http.MethodDelete, "/v1/warehouse/namespaces/hr/tables/orders", nil) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "hr", "table": "orders"}) + w = httptest.NewRecorder() + s.handleDropTable(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))) + if w.Code != http.StatusNoContent { + t.Fatalf("drop hr.orders: %d (%s)", w.Code, w.Body.String()) + } + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), false) // the drop purged it + w = httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"alias","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusOK { + t.Errorf("register at a location no table holds any more: status %d (%s), want 200", w.Code, w.Body.String()) + } + + fc2 := newMemFiler() + seedNamespace(fc2, "warehouse", "finance", "alice") + seedRegisteredFile(fc2, []byte(strings.Replace(registeredMetadata, `"location": "s3://warehouse/finance/orders"`, `"location": "s3://warehouse/finance/elsewhere"`, 1)), false) + s2 := NewServer(fc2, nil) + w = httptest.NewRecorder() + s2.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+registeredLocation+`"}`)) + if w.Code != http.StatusBadRequest { + t.Errorf("metadata describing another location: status %d (%s), want 400", w.Code, w.Body.String()) + } +} + +// An empty staged-create file is a placeholder, as an absent one is: the +// create commit goes on instead of failing. +func TestAnEmptyMetadataFileIsAPlaceholderForAStagedCreate(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, "warehouse", "finance", `{"name":"orders","stage-create":true}`, "alice")) + if w.Code != http.StatusOK { + t.Fatalf("stage-create: %d (%s)", w.Code, w.Body.String()) + } + emptied := 0 + for p, entry := range fc.entries { + if !entry.IsDirectory && strings.HasSuffix(p, ".metadata.json") { + fc.entries[p] = &filer_pb.Entry{Name: entry.Name} + emptied++ + if _, err := s.loadMetadataFile(context.Background(), "warehouse", strings.TrimPrefix(path.Dir(path.Dir(p)), s3tables.GetTableBucketPath("warehouse")+"/"), entry.Name); !errors.Is(err, errEmptyMetadataFile) { + t.Errorf("err = %v, want errEmptyMetadataFile", err) + } + } + } + if emptied != 1 { + t.Fatalf("staged metadata files = %d, want 1", emptied) + } + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/orders", + strings.NewReader(`{"requirements":[{"type":"assert-create"}],"updates":[]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w = httptest.NewRecorder() + s.handleUpdateTable(w, r) + if w.Code >= 500 { + t.Errorf("create commit over an empty staged file: status %d (%s)", w.Code, w.Body.String()) + } +} + +// A location in another namespace of the bucket is refused before anything is +// read or fetched: the ownership check lists only the table's own namespace, +// and the catalog's own namespace check came after the read. +func TestRegisterRefusesAnotherNamespaceBeforeReading(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedNamespace(fc.memFiler, "warehouse", "finance", "alice") + seedNamespace(fc.memFiler, "warehouse", "hr", "alice") + other := strings.Replace(registeredLocation, "/finance/", "/hr/", 1) + p := path.Join(metadataDirPath("warehouse", "hr/orders"), path.Base(other)) + fc.seed(p, &filer_pb.Entry{Name: path.Base(other), RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: int64(len(registeredMetadata))}}) + fc.remote[p] = []byte(strings.Replace(registeredMetadata, "/finance/", "/hr/", -1)) + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleRegisterTable(w, registerRequest(t, `{"name":"orders","metadata-location":"`+other+`"}`)) + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "within namespace") { + t.Errorf("another namespace's location: status %d (%s), want 400", w.Code, w.Body.String()) + } + if fc.cached != 0 { + t.Errorf("the file was fetched %d times before the refusal", fc.cached) + } +} + +// A commit or a transaction stores the UUID of the metadata it builds on, not +// a record's that disagrees with it: the next client that asserts the UUID it +// loaded would otherwise be refused. +func TestACommitStoresTheBaseMetadatasUUID(t *testing.T) { + const fileUUID = "9c12d441-03fe-4693-9a96-a0705ddf69c1" + for _, mode := range []string{"commit", "transaction"} { + t.Run(mode, func(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + internal := map[string]any{ + "name": "orders", "namespace": "finance", "format": "ICEBERG", "ownerAccountId": "alice", + "versionToken": "v1", "metadataVersion": 1, "metadataLocation": registeredLocation, + "metadata": s3tables.TableMetadata{ + Iceberg: &s3tables.IcebergMetadata{TableUUID: "00000000-0000-0000-0000-000000000001"}, + FullMetadata: json.RawMessage(registeredMetadata), + }, + } + b, _ := json.Marshal(internal) + fc.seed(s3tables.GetTablePath("warehouse", "finance", "orders"), &filer_pb.Entry{Name: "orders", IsDirectory: true, + Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: b}}) + s := NewServer(fc, nil) + w := httptest.NewRecorder() + if mode == "commit" { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/orders", + strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"}) + s.handleUpdateTable(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))) + } else { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader( + `{"table-changes":[{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse"}) + s.handleCommitTransaction(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))) + } + if w.Code >= 300 { + t.Fatalf("%s: %d %s", mode, w.Code, w.Body.String()) + } + _, md := storedTableEntry(t, fc, "orders") + if md == nil || md.Iceberg == nil || md.Iceberg.TableUUID != fileUUID { + got := "" + if md != nil && md.Iceberg != nil { + got = md.Iceberg.TableUUID + } + t.Errorf("stored record UUID = %q, want the base metadata's %s (the stored metadata itself carries %s)", got, fileUUID, fileUUID) + } + }) + } +} + +// The remote size the lookup saw can be stale: the cache request carries the +// limit so the filer refuses a larger replacement before downloading it. +func TestRemoteMetadataCacheCarriesTheLimit(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedRegisteredFile(fc.memFiler, []byte("{}"), true) + fc.remote[path.Join(metadataDirPath("warehouse", "finance/orders"), path.Base(registeredLocation))] = []byte(registeredMetadata) + s := NewServer(fc, nil) + if _, err := s.readMetadataDirFile(t.Context(), "warehouse", "finance/orders", path.Base(registeredLocation), 64); err == nil { + t.Fatal("read a remote file larger than the limit") + } + if fc.cached != 0 { + t.Errorf("cached %d times, want the filer to refuse", fc.cached) + } +} + +func TestInlineMetadataOverTheLimit(t *testing.T) { + fc := &remoteMemFiler{memFiler: newMemFiler(), remote: map[string][]byte{}} + seedRegisteredFile(fc.memFiler, []byte(registeredMetadata), false) + s := NewServer(fc, nil) + if _, err := s.readMetadataDirFile(t.Context(), "warehouse", "finance/orders", path.Base(registeredLocation), 64); err == nil { + t.Fatal("read inline content larger than the limit") + } + if _, err := s.readMetadataDirFile(t.Context(), "warehouse", "finance/orders", path.Base(registeredLocation), uint64(len(registeredMetadata))); err != nil { + t.Fatalf("inline content at the limit: %v", err) + } +} diff --git a/weed/s3api/iceberg/iceberg_register_table_test.go b/weed/s3api/iceberg/iceberg_register_table_test.go index d65e11ab84..788fc56816 100644 --- a/weed/s3api/iceberg/iceberg_register_table_test.go +++ b/weed/s3api/iceberg/iceberg_register_table_test.go @@ -81,7 +81,19 @@ func seedMetadataFile(fc *memFiler, tableName, name string, content []byte) stri // main on the second, the way the file a table is registered from holds them. func seedRegistrableMetadata(t *testing.T, fc *memFiler, tableName string) (string, table.Metadata) { t.Helper() - metadata := metadataWithSnapshots(t, []int64{1, 2}, 0) + // RegisterTable refuses metadata whose own location is not the table + // location it is registered from, so the fixture's location is the table's + builder, err := table.MetadataBuilderFromBase(metadataWithSnapshots(t, []int64{1, 2}, 0), "") + if err != nil { + t.Fatalf("builder: %v", err) + } + if err := builder.SetLoc("s3://" + registerTestBucket + "/" + path.Join("finance", tableName)); err != nil { + t.Fatalf("set location: %v", err) + } + metadata, err := builder.Build() + if err != nil { + t.Fatalf("build metadata: %v", err) + } content, err := json.Marshal(metadata) if err != nil { t.Fatalf("marshal metadata: %v", err) @@ -259,6 +271,9 @@ func seedOversizedMetadata(t *testing.T, fc *memFiler, tableName string) (string if err != nil { t.Fatalf("MetadataBuilderFromBase() error = %v", err) } + if err := builder.SetLoc("s3://" + registerTestBucket + "/" + path.Join("finance", tableName)); err != nil { // as in seedRegistrableMetadata + t.Fatalf("set location: %v", err) + } if err := builder.SetProperties(map[string]string{"padding": strings.Repeat("x", s3tables.MaxRequestBodySize)}); err != nil { t.Fatalf("SetProperties() error = %v", err) } diff --git a/weed/s3api/iceberg/metadata_files.go b/weed/s3api/iceberg/metadata_files.go index ad68aa7a6a..8b3ea77337 100644 --- a/weed/s3api/iceberg/metadata_files.go +++ b/weed/s3api/iceberg/metadata_files.go @@ -1,6 +1,7 @@ package iceberg import ( + "bytes" "context" "errors" "fmt" @@ -9,6 +10,7 @@ import ( "strings" "time" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" @@ -191,57 +193,169 @@ func (s *Server) deleteStagedMetadataFile(ctx context.Context, bucketName, table }) } +// errEmptyMetadataFile is a metadata file that exists and holds no bytes: a +// staged create's placeholder is one, and is treated as absent there. +var errEmptyMetadataFile = errors.New("empty metadata file") + +// maxMetadataFileSize bounds a metadata.json read whole into memory (and, for +// a remote-only file, fetched into the local cluster). +const maxMetadataFileSize = 64 << 20 + +// loadMetadataFile reads a file of a table's metadata directory whole: inline +// content (what the catalog writes), chunks (a file written through the S3 +// gateway or the store's maintenance), or, in a remote-mounted bucket, a file +// that holds only its RemoteEntry here, fetched into the local cluster first +// as an S3 read does. A file that holds no bytes is errEmptyMetadataFile. func (s *Server) loadMetadataFile(ctx context.Context, bucketName, tablePath, metadataFileName string) ([]byte, error) { + content, err := s.readMetadataDirFile(ctx, bucketName, tablePath, metadataFileName, maxMetadataFileSize) + if err != nil { + return nil, err + } + if len(content) == 0 { + return nil, fmt.Errorf("%s/%s: %w", metadataDirPath(bucketName, tablePath), metadataFileName, errEmptyMetadataFile) + } + return content, nil +} + +// readMetadataDirFile reads a file of a table's metadata directory whole, at +// most limit bytes: inline content, chunks, or a remote-only file of a +// remote-mounted bucket, cached into the local cluster first (its remote size +// checked against limit before anything is fetched). Reading only inline +// content, or chunks, returned a remote-only file as empty bytes: in a +// remote-mounted bucket every file the write-back has uncached is one. +func (s *Server) readMetadataDirFile(ctx context.Context, bucketName, tablePath, fileName string, limit uint64) ([]byte, error) { opCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() metadataDir := metadataDirPath(bucketName, tablePath) - - var content []byte + var entry *filer_pb.Entry err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { resp, err := filer_pb.LookupEntry(opCtx, client, &filer_pb.LookupDirectoryEntryRequest{ Directory: metadataDir, - Name: metadataFileName, + Name: fileName, }) if err != nil { return err } if resp == nil || resp.Entry == nil { - return fmt.Errorf("lookup returned nil entry for %s/%s", metadataDir, metadataFileName) + return fmt.Errorf("lookup returned nil entry for %s/%s", metadataDir, fileName) + } + entry = resp.Entry + // a remote file's size is known before it is fetched: one larger than the limit is not fetched at all + if remoteOnlyEntry(entry) && uint64(entry.RemoteEntry.RemoteSize) > limit { + return fmt.Errorf("%s/%s is %d bytes on the remote, larger than the %d byte limit", metadataDir, fileName, entry.RemoteEntry.RemoteSize, limit) + } + // one retry in place: a cache call can lose a race with an uncache or a write-back of the same entry + for attempt := 0; attempt < 2 && remoteOnlyEntry(entry); attempt++ { + cached, err := client.CacheRemoteObjectToLocalCluster(opCtx, &filer_pb.CacheRemoteObjectToLocalClusterRequest{ + Directory: metadataDir, + Name: fileName, + MaxSize: int64(limit), + }) + if err != nil { + return fmt.Errorf("cache remote %s/%s: %w", metadataDir, fileName, err) + } + if cached == nil || cached.Entry == nil { + return fmt.Errorf("cache remote %s/%s: no entry returned", metadataDir, fileName) + } + entry = cached.Entry + } + if remoteOnlyEntry(entry) { + return fmt.Errorf("cache remote %s/%s: still remote-only after caching twice", metadataDir, fileName) } - content = append([]byte(nil), resp.Entry.Content...) return nil }) if err != nil { return nil, err } - return content, nil + if len(entry.Content) > 0 { + if uint64(len(entry.Content)) > limit { + return nil, fmt.Errorf("%s/%s is %d bytes, larger than the %d byte limit", metadataDir, fileName, len(entry.Content), limit) + } + return append([]byte(nil), entry.Content...), nil + } + if len(entry.GetChunks()) == 0 { + return nil, nil + } + size := filer.FileSize(entry) + if size > limit { + return nil, fmt.Errorf("%s/%s is %d bytes, larger than the %d byte limit", metadataDir, fileName, size, limit) + } + fullClient, ok := s.filerClient.(filer_pb.FilerClient) + if !ok { + return nil, fmt.Errorf("filer client cannot resolve chunk locations") + } + var buf bytes.Buffer + buf.Grow(int(size)) + lookup := &lookupFileIDAdapter{fn: filer.LookupFn(fullClient)} + if err := filer.StreamContent(lookup, &buf, entry.GetChunks(), 0, int64(size)); err != nil { + return nil, fmt.Errorf("read %s/%s: %w", metadataDir, fileName, err) + } + return buf.Bytes(), nil +} + +// remoteOnlyEntry is a file of a remote-mounted bucket that holds no bytes +// here: no chunks and no inline content, only its RemoteEntry. +func remoteOnlyEntry(entry *filer_pb.Entry) bool { + return entry.IsInRemoteOnly() && len(entry.Content) == 0 +} + +// metadataLocationPath checks a metadata location without reading anything: +// in bucketName, without traversal segments, and a file directly in a table's +// metadata directory. It returns the bucket-relative table path. +func metadataLocationPath(bucketName, metadataLocation string) (string, error) { + metadataBucket, tablePath, err := parseS3Location(tableLocationFromMetadataLocation(metadataLocation)) + if err != nil { + return "", fmt.Errorf("invalid metadata location %s: %w", metadataLocation, err) + } + if err := confineMetadataLocation(metadataBucket, tablePath, bucketName); err != nil { + return "", err + } + // the file itself, directly in the table's metadata directory: a deeper + // path would be read as a same-named file there + if path.Base(path.Dir(metadataLocation)) != "metadata" { + return "", fmt.Errorf("metadata location %s is not a file of a table's metadata directory", metadataLocation) + } + return tablePath, nil +} + +// metadataAtLocation reads the metadata.json a metadata location names, +// confined to bucketName (metadataLocationPath). +func (s *Server) metadataAtLocation(ctx context.Context, bucketName, metadataLocation string) ([]byte, error) { + if s.filerClient == nil { + return nil, fmt.Errorf("no filer to read %s from", metadataLocation) + } + tablePath, err := metadataLocationPath(bucketName, metadataLocation) + if err != nil { + return nil, err + } + return s.loadMetadataFile(ctx, bucketName, tablePath, path.Base(metadataLocation)) } // currentMetadataBytes returns the Iceberg metadata a table serves: the copy // kept in its catalog record or, for a record that holds only a metadata -// location, the file at that location. Tables registered before the record -// kept their metadata look like that, and serving an empty placeholder for -// them hides every snapshot and fails every commit on a table UUID mismatch. -// It returns nil, for the caller's placeholder, when the record has neither -// or the file is gone. +// location, the file at that location (metadataAtLocation: confined to the +// bucket and to a table's metadata directory, chunks followed, a remote-only +// file of a mounted bucket fetched first). It returns nil, for the caller's +// placeholder, only when the record has neither: a table created without a +// location, a new empty table until its first update. A location whose file +// cannot be read, or is gone, is an error on every path (load, commit, +// transaction): an empty table in its place reads as no rows, refuses every +// client commit on a UUID mismatch, and lets a commit without requirements +// replace the table's history. +// +// A catalog-only table (a Lance dataset) has no Iceberg metadata: its +// record's metadata and location are the Lance client's, never read here, and +// it is served as an empty read-only Iceberg table. func (s *Server) currentMetadataBytes(ctx context.Context, getResp s3tables.GetTableResponse, bucketName string) ([]byte, error) { + if s3tables.IsCatalogOnlyFormat(getResp.Format) { + return nil, nil + } if getResp.Metadata != nil && len(getResp.Metadata.FullMetadata) > 0 { return getResp.Metadata.FullMetadata, nil } if getResp.MetadataLocation == "" { return nil, nil } - metadataBucket, tablePath, err := parseS3Location(tableLocationFromMetadataLocation(getResp.MetadataLocation)) - if err != nil { - return nil, err - } - if err := confineMetadataLocation(metadataBucket, tablePath, bucketName); err != nil { - return nil, err - } - content, err := s.loadTableMetadataBlob(ctx, metadataBucket, tablePath, path.Base(getResp.MetadataLocation)) - if errors.Is(err, filer_pb.ErrNotFound) { - return nil, nil - } - return content, err + return s.metadataAtLocation(ctx, bucketName, getResp.MetadataLocation) } diff --git a/weed/s3api/iceberg/vector_namespace_test.go b/weed/s3api/iceberg/vector_namespace_test.go index dad8e4ecb6..3a22f77b39 100644 --- a/weed/s3api/iceberg/vector_namespace_test.go +++ b/weed/s3api/iceberg/vector_namespace_test.go @@ -128,3 +128,55 @@ func TestStageCreateCannotReachVectorIndex(t *testing.T) { }) } } + +// A Lance dataset outside the vector namespace loads as an empty Iceberg +// table, but neither commit path may write Iceberg metadata over it: the +// record's location is the Lance client's dataset root. +func TestCatalogOnlyTableRefusesIcebergCommits(t *testing.T) { + filer := s3tablestest.Start(t) + s := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{}) + router := mux.NewRouter().SkipClean(true) + s.RegisterRoutes(router) + + admin := s3tables.NewManager() + admin.SetTrusted(true) + client := s3tables.NewManagerClient(filer.Client) + arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, "lbk") + if err != nil { + t.Fatal(err) + } + const datasetRoot = "s3://lbk/ds/t.lance" + for _, op := range []struct { + name string + req interface{} + }{ + {"CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: "lbk", Format: s3tables.FormatLance}}, + {"CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"ds"}}}, + {"CreateTable", &s3tables.CreateTableRequest{TableBucketARN: arn, Namespace: []string{"ds"}, + Name: "t", Format: s3tables.FormatLance, MetadataLocation: datasetRoot}}, + } { + if err := admin.Execute(t.Context(), client, op.name, op.req, nil, ""); err != nil { + t.Fatalf("%s: %v", op.name, err) + } + } + + for name, tc := range map[string]struct{ path, body string }{ + "commit table": {"/v1/lbk/namespaces/ds/tables/t", `{"requirements":[],"updates":[]}`}, + "commit transaction": {"/v1/lbk/transactions/commit", `{"table-changes":[{"identifier":{"namespace":["ds"],"name":"t"},"requirements":[],"updates":[]}]}`}, + } { + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body))) + if rec.Code != http.StatusBadRequest { + t.Errorf("commit = %d (%s), want 400", rec.Code, rec.Body.String()) + } + var got s3tables.GetTableResponse + if err := admin.Execute(t.Context(), client, "GetTable", &s3tables.GetTableRequest{TableBucketARN: arn, Namespace: []string{"ds"}, Name: "t"}, &got, ""); err != nil { + t.Fatal(err) + } + if got.MetadataLocation != datasetRoot { + t.Errorf("metadata location = %q, want %q", got.MetadataLocation, datasetRoot) + } + }) + } +}