Files
seaweedfs/weed/s3api/lance/handlers_test.go
T
8bb5c069ec iceberg, s3tables: new tables take only fresh locations (#13160)
* s3tables, iceberg, lance: the catalog assigns every new location; an existing name answers only a reader

A REST create without a location gets <ns>/<name>-<uuid> (#12475) and a
location another record holds is refused (#12473), but a location a
client names is still taken: the REST create's location field and
warehouse property, S3 Tables CreateTable and CreateView with a
MetadataLocation, the Lance declare's location. A free location a client
picks can be one another caller holds staged write credentials for
(stage markers are not claims), or files no record claims any more.
Separately, CreateTable of a name that already holds a table returns
that table (ARN, version token, metadata location) to any caller who may
create, including one who may not read it.

- A REST create or create view naming a location (field or property,
  stage-create or not, the bare bucket included) is refused with 400
  before anything is written; the location is always placeNewEntry's:
  <ns>/<name>-<uuid> in the bucket, or under the operator's
  ICEBERG_WAREHOUSE (no longer under a client's warehouse property).
- A create commit uses a stage marker only when its assign-uuid matches
  the staged table's UUID (PyIceberg and Java send it); any other create
  commit is placed at a fresh <name>-<uuid>, never at the bare name path
  and never at another caller's staged location. Its updates may not set
  another location than the one assigned (400).
- S3 Tables CreateTable and CreateView naming a MetadataLocation are
  refused with 400 (ErrClientTableLocation) unless the call is the
  process's own (WithCatalogAssignedLocation: the REST create, create
  view and create commit at the location they placed; the Lance declare
  at the dataset's name path and register at an existing dataset). AWS's
  CreateTable takes no location either.
- A Lance declare naming a location is refused with 400 (register is for
  existing datasets).
- CreateTable of an existing name answers the table only to a caller who
  may GetTable it; a caller who may only create gets 409
  TableAlreadyExists and nothing about it.

Tests: TestAClientCreateNamesNoLocation (positive controls: a client
create without a location, the catalog's own create with one),
TestARESTCreateNamesNoLocation, TestACreateCommitCannotSetAnotherLocation,
TestACreateCommitTakesOnlyItsOwnStage (the stager's own commit is the
positive control), TestCreateExistingTableAnswersOnlyAReaderWithIt (a
reader gets the table). Existing tests adapted: the s3tables fixtures and
request helpers run as the catalog's own calls (assignedCtx), as do the
iceberg tests that seed tables through the manager;
iceberg_create_table_conflict_test.go's creates send no location and
newConflictEnv points placeNewEntry at conflictLocation, so its races
still collide on one location; TestCreatePathsRefuseAnotherTablesLocation
expects 400 for the three create paths and 409 for the register;
TestCreateTableWithoutLocationUsesItsOwnDirectory drops the bare-bucket
body; lance TestIcebergTablesAreInvisible seeds its Iceberg table as the
catalog; TestDeclareOfAnExistingTableKeepsItsLocation expects 400 for a
declare naming the index's location; TestDeregisterAndReregisterNeedUpdateTable
(#12552) expects 409 instead of 404 for the register and the declare of
a caller without GetTable: the table stays deregistered and nothing is
vended. Each rule is red with it undone.

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

* iceberg: a create may name a fresh location

A REST CreateTable naming a location (Trino always sends one built from
the namespace location, Spark LOCATION, PyIceberg location=) is accepted
again when nothing is stored under it and no live stage holds it; a used
or staged location answers 400. The check runs after the create's
authorization and before anything is written. A bare-bucket location
still gets the assigned <name>-<uuid>. CreateView always uses the
assigned location: a view holds only metadata files.

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

* lance: a declare may restate its name path as its location

pylance and other namespace clients may send the location they expect;
the dataset's own name path is accepted, any other location still
answers 400.

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

* iceberg: a commit cannot set another location on an existing table

CommitTable and CommitTransaction applied a set-location update, so a
table's metadata could name a location outside the directory its record
holds. Such a commit now answers 400 and nothing is written.

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

* iceberg: the fresh-location check pages through every stage marker

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

* iceberg: a fresh location stays apart from stages and tables above or under it

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

* iceberg: a create checks its location again after claiming it

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

* s3tables, iceberg: a live stage holds its location against every create

The catalog counts each live stage-create as a root of the record it
would commit to, so a native create, register, rename or move over a
stage's location is refused. The fresh-location check reads the same
roots, so a stage also backs out of a record that claimed an ancestor
after its first check. A location held by a record or stage answers 409,
as the create gate already did.

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

* iceberg: a create removes only the stages its location covers

A create or commit used to drop every stage marker of its name, which
freed the location of a stage whose credentials were still live.
Expired markers now go with their staged metadata.

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

* iceberg: an assigned stage location checks its claim again too

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

* iceberg: a stage marker lasts as long as its vended credentials

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

* iceberg: test a create that runs while a stage checks its claim

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

* iceberg: a stage holds its location against a create of the same name

A live stage-create now counts under its marker rather than under the
record of its name, so a same-name create over its location is refused
and a stage refuses a same-name table created over its location. Only a
staged commit takes the location its own stage holds.

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

* s3tables: a stage holds only its location against its own record's create

A live stage keeps the path of the record it would commit to away from
other records' files, but a create of that same record writes it: the
stage then holds only its location against it. A stage at its name path
can commit while a later stage of its name, elsewhere, is live.

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

* iceberg: a staged commit's create gate reads its location as a create does

The gate maps a metadata file's location to its table directory, so the
bare location of a stage under a metadata directory resolved to the
namespace and conflicted with the stage's own claim.

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

* iceberg, lance: tests from master create through the catalog's own call

Their creates name a location, which only the catalog's own calls may, and
a caller who may only create gets 409 for an existing name whatever
location its register names.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 -08:00

734 lines
33 KiB
Go

package lance
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"path"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
)
// openAuthenticator stands in for a gateway with no IAM configured, which is the
// mode the namespace falls open in.
type openAuthenticator struct{}
func (openAuthenticator) AuthenticateRequest(*http.Request) (string, interface{}, s3err.ErrorCode) {
return s3tables.DefaultAccountID, nil, s3err.ErrNone
}
func (openAuthenticator) DefaultAllow() bool { return true }
func (openAuthenticator) AuthEnabled() bool { return false }
// signedAuthenticator admits the same caller on a gateway that checks
// credentials.
type signedAuthenticator struct{ openAuthenticator }
func (signedAuthenticator) AuthEnabled() bool { return true }
type testHarness struct {
router *mux.Router
filer *s3tablestest.MemFiler
admin *s3tables.Manager
server *Server
}
func newTestHarness(t *testing.T) *testHarness {
t.Helper()
filer := s3tablestest.Start(t)
server := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{})
server.SetS3Endpoint("http://127.0.0.1:8333")
server.SetS3Region(s3tables.DefaultRegion)
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
// Table buckets are created by an operator, not by a namespace client, so
// the harness seeds them the way the shell and admin console would.
admin := s3tables.NewManager()
admin.SetTrusted(true)
return &testHarness{router: router, filer: filer, admin: admin, server: server}
}
// createBucket seeds a table bucket the Lance namespace can then be pointed at.
// An empty format strips the declaration afterwards, which is the only way to
// get the shape a bucket made before formats existed has: one that still
// accepts either format.
func (h *testHarness) createBucket(t *testing.T, name, format string) {
t.Helper()
var resp s3tables.CreateTableBucketResponse
declared := format
if declared == "" {
declared = s3tables.FormatIceberg
}
err := h.admin.Execute(t.Context(), s3tables.NewManagerClient(h.filer.Client), "CreateTableBucket",
&s3tables.CreateTableBucketRequest{Name: name, Format: declared}, &resp, "")
if err != nil {
t.Fatalf("create table bucket %s: %v", name, err)
}
if format == "" {
h.undeclareBucket(t, name)
}
}
// undeclareBucket removes a bucket's format from its metadata, ageing it back to
// what the filer holds for a bucket created before the field existed.
func (h *testHarness) undeclareBucket(t *testing.T, name string) {
t.Helper()
entry := h.filer.Get(s3tables.TablesPath, name)
if entry == nil {
t.Fatalf("table bucket %s is not in the filer", name)
}
var metadata map[string]any
if err := json.Unmarshal(entry.Extended[s3tables.ExtendedKeyMetadata], &metadata); err != nil {
t.Fatalf("read bucket metadata: %v", err)
}
delete(metadata, "format")
updated, err := json.Marshal(metadata)
if err != nil {
t.Fatalf("write bucket metadata: %v", err)
}
extended := map[string][]byte{}
for key, value := range entry.Extended {
extended[key] = value
}
extended[s3tables.ExtendedKeyMetadata] = updated
h.filer.Put(s3tables.TablesPath, name, extended)
}
func (h *testHarness) bucketARN(t *testing.T, name string) string {
t.Helper()
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, name)
if err != nil {
t.Fatalf("build arn: %v", err)
}
return arn
}
func (h *testHarness) do(t *testing.T, method, target, body string) *httptest.ResponseRecorder {
t.Helper()
var reader *strings.Reader
if body == "" {
reader = strings.NewReader("")
} else {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, target, reader)
recorder := httptest.NewRecorder()
h.router.ServeHTTP(recorder, req)
return recorder
}
func (h *testHarness) mustDo(t *testing.T, method, target, body string, want int) *httptest.ResponseRecorder {
t.Helper()
recorder := h.do(t, method, target, body)
if recorder.Code != want {
t.Fatalf("%s %s = %d (%s), want %d", method, target, recorder.Code, recorder.Body.String(), want)
}
return recorder
}
func decode[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
t.Helper()
var out T
if err := json.Unmarshal(recorder.Body.Bytes(), &out); err != nil {
t.Fatalf("decode %s: %v", recorder.Body.String(), err)
}
return out
}
// While the S3 port takes unsigned requests the catalog says so, and a client
// with no credentials of its own still reaches the data. Once auth is on it
// has to sign again.
func TestStorageOptionsSkipSignatureOnlyWhileS3AuthIsOff(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "open", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/open$ns/create", `{}`, http.StatusOK)
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/open$ns$t/declare", `{}`, http.StatusOK))
if declared.StorageOptions["aws_skip_signature"] != "true" {
t.Fatalf("auth off: storage options = %v, want aws_skip_signature", declared.StorageOptions)
}
h.server.authenticator = signedAuthenticator{}
described := decode[DescribeTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/open$ns$t/describe", `{}`, http.StatusOK))
if _, ok := described.StorageOptions["aws_skip_signature"]; ok {
t.Fatalf("auth on: storage options = %v, want no aws_skip_signature", described.StorageOptions)
}
}
// The lifecycle a Lance client drives: create the namespace, declare the table
// before any data exists, resolve it to a location, then deregister and bring it
// back by registering the same location.
func TestTableLifecycle(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{}`, http.StatusOK))
if declared.Location != "s3://analytics/sales/orders" {
t.Fatalf("declared location = %q", declared.Location)
}
// The endpoint is plaintext, so a client that does not get allow_http fails
// with what looks like a credential error.
if declared.StorageOptions["aws_endpoint"] != "http://127.0.0.1:8333" ||
declared.StorageOptions["allow_http"] != "true" {
t.Fatalf("storage options = %v", declared.StorageOptions)
}
described := decode[DescribeTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/describe?check_declared=true", `{}`, http.StatusOK))
if described.Location != declared.Location {
t.Fatalf("described location = %q, want %q", described.Location, declared.Location)
}
if described.IsOnlyDeclared == nil || !*described.IsOnlyDeclared {
t.Fatalf("is_only_declared = %v, want true for a table with no data", described.IsOnlyDeclared)
}
listed := decode[ListTablesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/analytics$sales/table/list", "", http.StatusOK))
if len(listed.Tables) != 1 || listed.Tables[0] != "analytics$sales$orders" {
t.Fatalf("listed tables = %v, want the full identifier", listed.Tables)
}
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/exists", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/deregister", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/exists", `{}`, http.StatusNotFound)
afterDrop := decode[ListTablesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/analytics$sales/table/list", "", http.StatusOK))
if len(afterDrop.Tables) != 0 {
t.Fatalf("deregistered table still listed: %v", afterDrop.Tables)
}
// Deregistering preserves the data. The catalog entry is the dataset
// directory, so dropping it would take the dataset with it.
if h.filer.Get(s3tables.GetNamespacePath("analytics", "sales"), "orders") == nil {
t.Fatal("deregister deleted the dataset directory")
}
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register",
`{"location":"s3://analytics/sales/orders"}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/exists", `{}`, http.StatusOK)
// Dropping is the operation that does remove the data.
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/drop", `{}`, http.StatusOK)
if h.filer.Get(s3tables.GetNamespacePath("analytics", "sales"), "orders") != nil {
t.Fatal("drop left the dataset directory behind")
}
}
// Repointing a registered name at another dataset (Overwrite) would move its
// root: the dataset it named would be left to no catalog record, and the next
// table placed there could take it. The catalog refuses the move (400) and keeps
// the old dataset where it is; an Overwrite at the table's own location works.
func TestRegisterOverwriteKeepsTheOldDataset(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{}`, http.StatusOK))
current := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$current/declare", `{}`, http.StatusOK))
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register",
`{"location":"`+current.Location+`","mode":"Overwrite"}`, http.StatusBadRequest)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register",
`{"location":"s3://analytics/sales/archive","mode":"Overwrite"}`, http.StatusBadRequest)
described := decode[DescribeTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/describe", `{}`, http.StatusOK))
if described.Location != declared.Location {
t.Fatalf("location after a refused repoint = %q, want %q", described.Location, declared.Location)
}
if h.filer.Get(s3tables.GetNamespacePath("analytics", "sales"), "orders") == nil {
t.Fatal("a refused repoint deleted the dataset the name holds")
}
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register",
`{"location":"`+declared.Location+`","mode":"Overwrite"}`, http.StatusOK)
}
// A required list field answers empty rather than null, which a generated
// client may decode differently.
func TestListAllTablesIsNeverNull(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
body := h.mustDo(t, http.MethodGet, "/v1/table", "", http.StatusOK).Body.String()
if strings.Contains(body, `"tables":null`) {
t.Fatalf("ListAllTables returned null for a required field: %s", body)
}
}
func TestNamespaceListing(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$finance/create", `{}`, http.StatusOK)
roots := decode[ListNamespacesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/$/list", "", http.StatusOK))
if len(roots.Namespaces) != 1 || roots.Namespaces[0] != "analytics" {
t.Fatalf("root listing = %v, want the table buckets", roots.Namespaces)
}
children := decode[ListNamespacesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/analytics/list", "", http.StatusOK))
if len(children.Namespaces) != 2 {
t.Fatalf("bucket listing = %v, want two namespaces", children.Namespaces)
}
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/exists", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$nope/exists", `{}`, http.StatusNotFound)
// Fail mode reports a missing namespace as 400 on this operation, which is
// what the spec asks for; Skip reports success.
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$nope/drop", `{}`, http.StatusBadRequest)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$nope/drop", `{"mode":"Skip"}`, http.StatusNoContent)
}
// Storage flattens a namespace's parts, so creating a$b without a would leave
// an intermediate that listing derives from the name and describe denies
// exists. The spec asks for NamespaceNotFound, which keeps them consistent.
func TestCreateNamespaceRequiresItsParent(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
recorder := h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$missing$child/create", `{}`, http.StatusNotFound)
if got := decode[errorResponse](t, recorder); got.Code != codeNamespaceNotFound {
t.Fatalf("error code = %d, want %d", got.Code, codeNamespaceNotFound)
}
// With the parent in place the child is fine, and both are then listed and
// describable.
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$parent/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$parent$child/create", `{}`, http.StatusOK)
listed := decode[ListNamespacesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/analytics/list", "", http.StatusOK))
for _, name := range listed.Namespaces {
path := "/v1/namespace/analytics$" + name
h.mustDo(t, http.MethodPost, path+"/exists", `{}`, http.StatusOK)
}
}
func TestCreateNamespaceModes(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusConflict)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{"mode":"ExistOk"}`, http.StatusOK)
// snake_case is the other spelling the spec accepts.
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{"mode":"exist_ok"}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/namespace/$/create", `{}`, http.StatusBadRequest)
}
// A Lance client must never resolve an Iceberg table's location, or it would
// write a dataset over a table another engine owns.
func TestIcebergTablesAreInvisible(t *testing.T) {
h := newTestHarness(t)
// Undeclared, because a bucket that declares one format cannot hold the
// other - and mixing is exactly what this test needs to prove is hidden.
h.createBucket(t, "analytics", "")
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$vectors/declare", `{}`, http.StatusOK)
manager := h.admin
var created s3tables.CreateTableResponse
err := manager.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{
TableBucketARN: h.bucketARN(t, "analytics"),
Namespace: []string{"sales"},
Name: "ledger",
Format: s3tables.FormatIceberg,
MetadataLocation: "s3://analytics/sales/ledger/metadata/v1.metadata.json",
}, &created, "")
if err != nil {
t.Fatalf("create iceberg table: %v", err)
}
listed := decode[ListTablesResponse](t,
h.mustDo(t, http.MethodGet, "/v1/namespace/analytics$sales/table/list", "", http.StatusOK))
if len(listed.Tables) != 1 || listed.Tables[0] != "analytics$sales$vectors" {
t.Fatalf("listing = %v, want only the lance table", listed.Tables)
}
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$ledger/describe", `{}`, http.StatusNotFound)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$ledger/exists", `{}`, http.StatusNotFound)
// Declaring over the Iceberg table must not quietly succeed and hand the
// Lance client a directory another format owns.
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$ledger/declare", `{}`, http.StatusConflict)
if got := decode[errorResponse](t, recorder); got.Code != codeTableAlreadyExists {
t.Fatalf("error code = %d, want %d", got.Code, codeTableAlreadyExists)
}
}
// The route and the body naming different objects is a bad request, not a silent
// preference for one of them.
func TestRouteAndBodyMustAgree(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare",
`{"id":["analytics","sales","other"]}`, http.StatusBadRequest)
if got := decode[errorResponse](t, recorder); got.Code != codeInvalidInput {
t.Fatalf("error code = %d, want %d", got.Code, codeInvalidInput)
}
}
// A client-supplied location must resolve inside its own bucket. Without this,
// a "../"-laden or cross-bucket location escapes when the marker path is joined
// under /buckets, letting the request reach another tenant's namespace, or
// outside /buckets entirely, and auto-create the parent directories on the way.
func TestLocationOutsideBucketIsRejected(t *testing.T) {
cases := []struct {
name string
location string
}{
{"another bucket", "s3://victim/secret"},
{"traversal into another bucket", "s3://analytics/../victim/secret"},
{"traversal above the buckets root", "s3://analytics/../../etc/cron.d"},
{"not an s3 uri", "../../etc/cron.d"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
dir := s3tables.TableDataDirFromMetadataLocation(tc.location)
body := `{"location":"` + tc.location + `"}`
// declare writes .lance-reserved at the location: rejection must leave
// nothing behind at the escaped directory.
t.Run("declare", func(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", body, http.StatusBadRequest)
if got := decode[errorResponse](t, recorder); got.Code != codeInvalidInput {
t.Fatalf("error code = %d, want %d", got.Code, codeInvalidInput)
}
if dir != "" && h.filer.Get(dir, reservedMarker) != nil {
t.Fatalf("declare wrote %s into %s despite rejection", reservedMarker, dir)
}
})
// register removes .lance-deregistered at the location: rejection must
// leave a victim's marker in place rather than un-hiding their table.
t.Run("register", func(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
if dir != "" {
h.filer.PutFile(dir, deregisteredMarker, time.Unix(1, 0))
}
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register", body, http.StatusBadRequest)
if got := decode[errorResponse](t, recorder); got.Code != codeInvalidInput {
t.Fatalf("error code = %d, want %d", got.Code, codeInvalidInput)
}
if dir != "" && h.filer.Get(dir, deregisteredMarker) == nil {
t.Fatalf("register removed %s from %s despite rejection", deregisteredMarker, dir)
}
})
})
}
}
// The data plane needs Lance format support that does not exist in Go, so it
// answers with the spec's own Unsupported code rather than a bare 404.
func TestDataPlaneIsUnsupported(t *testing.T) {
h := newTestHarness(t)
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/query", `{}`, http.StatusNotImplemented)
if got := decode[errorResponse](t, recorder); got.Code != codeUnsupported {
t.Fatalf("error code = %d, want %d", got.Code, codeUnsupported)
}
}
// createOnlyAuthenticator signs in an identity that may create and read tables
// but not update them; noRead also takes away reading.
type createOnlyAuthenticator struct{ noRead bool }
func (a createOnlyAuthenticator) AuthenticateRequest(*http.Request) (string, interface{}, s3err.ErrorCode) {
actions := []string{"s3tables:CreateTable", "s3tables:GetTable"}
if a.noRead {
actions = actions[:1]
}
return "creator", &struct {
Name string
Actions []string
}{Name: "creator", Actions: actions}, s3err.ErrNone
}
func (createOnlyAuthenticator) DefaultAllow() bool { return false }
func (createOnlyAuthenticator) AuthEnabled() bool { return true }
// The right to create a name is the write evidence for a table the declare
// creates, but not for one it only finds.
func TestDeclareVendsWriteOnlyForATableItCreates(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "lnc", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/lnc$ns/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/declare", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/deregister", `{}`, http.StatusOK)
server := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{})
server.SetCredentialVendor(recordingVendor{})
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
creator := &testHarness{router: router, filer: h.filer, admin: h.admin, server: server}
for _, tc := range []struct{ name, want string }{
{"theirs", "read-only"},
{"mine", "read-write"},
} {
t.Run(tc.name, func(t *testing.T) {
if got := creator.vendedKey(t, "/v1/table/lnc$ns$"+tc.name+"/declare", ""); got != tc.want {
t.Errorf("vended %q, want %q", got, tc.want)
}
})
}
if h.filer.Get("/buckets/lnc/ns/theirs", deregisteredMarker) == nil {
t.Error("a declare that may not write the table brought it back")
}
}
// Deregistering hides a table and registering over one brings it back, so
// both change its catalog state and need UpdateTable, not just GetTable.
func TestDeregisterAndReregisterNeedUpdateTable(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "lnc", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/lnc$ns/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/declare", `{}`, http.StatusOK)
server := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{})
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
reader := &testHarness{router: router, filer: h.filer, admin: h.admin, server: server}
reader.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/describe", `{}`, http.StatusOK)
reader.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/deregister", `{}`, http.StatusForbidden)
if h.filer.Get("/buckets/lnc/ns/theirs", deregisteredMarker) != nil {
t.Fatal("a refused deregister left its marker")
}
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/deregister", `{}`, http.StatusOK)
reader.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/register", `{"location":"s3://lnc/ns/theirs"}`, http.StatusForbidden)
if h.filer.Get("/buckets/lnc/ns/theirs", deregisteredMarker) == nil {
t.Fatal("a refused register brought the table back")
}
// Without GetTable the table looks absent; CreateTable of a name that exists
// answers 409 to a caller who may not read it (it returns nothing about the
// table), so the register stops there and the table stays deregistered.
blindServer := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{noRead: true})
blindServer.SetCredentialVendor(recordingVendor{})
blindRouter := mux.NewRouter().SkipClean(true)
blindServer.RegisterRoutes(blindRouter)
blind := &testHarness{router: blindRouter, filer: h.filer, admin: h.admin, server: blindServer}
blind.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/register", `{"location":"s3://lnc/ns/theirs"}`, http.StatusConflict)
// a declare that finds an unreadable table vends nothing: 409, no credentials
blind.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/declare", `{}`, http.StatusConflict)
if h.filer.Get("/buckets/lnc/ns/theirs", deregisteredMarker) == nil {
t.Fatal("a caller without GetTable brought the table back")
}
}
// An in-process describe for a trusted caller resolves the table without the
// caller's catalog grants, and still refuses a deregistered one.
func TestDescribeTableInternalIgnoresCatalogGrants(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "lnc", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/lnc$ns/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$t/declare", `{}`, http.StatusOK)
server := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{})
server.SetS3Endpoint("http://127.0.0.1:8333")
anonymous := httptest.NewRequest(http.MethodPost, "/", nil)
anonymous = anonymous.WithContext(s3_constants.SetIdentityNameInContext(anonymous.Context(), "stranger"))
if _, _, err := server.DescribeTable(anonymous, []string{"lnc", "ns", "t"}); err == nil {
t.Fatal("DescribeTable without grants resolved the table")
}
location, options, err := server.DescribeTableInternal(anonymous, []string{"lnc", "ns", "t"})
if err != nil {
t.Fatalf("DescribeTableInternal: %v", err)
}
if location != "s3://lnc/ns/t" || options["aws_endpoint"] != "http://127.0.0.1:8333" {
t.Fatalf("resolved %q %v", location, options)
}
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$t/deregister", `{}`, http.StatusOK)
_, _, err = server.DescribeTableInternal(anonymous, []string{"lnc", "ns", "t"})
var apiErr *s3tables.S3TablesError
if !errors.As(err, &apiErr) || apiErr.Type != s3tables.ErrCodeNoSuchTable {
t.Fatalf("a deregistered table resolved: %v, want %s", err, s3tables.ErrCodeNoSuchTable)
}
}
// The options an internal describe vends may write a vector index, whose
// writer is the engine, but not a table whose writes s3tables grants gate.
func TestDescribeTableInternalVendsWriteForTheVectorNamespace(t *testing.T) {
h := newTestHarness(t)
h.seedVectorIndex(t, "vec", s3tables.FormatLance)
h.createBucket(t, "lnc", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/lnc$ns/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$t/declare", `{}`, http.StatusOK)
server := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{})
server.SetCredentialVendor(recordingVendor{})
stranger := httptest.NewRequest(http.MethodPost, "/", nil)
stranger = stranger.WithContext(s3_constants.SetIdentityNameInContext(stranger.Context(), "stranger"))
for _, tc := range []struct {
id []string
want string
}{
{[]string{"vec", "vector", "idx"}, "read-write"},
{[]string{"lnc", "ns", "t"}, "read-only"},
} {
_, options, err := server.DescribeTableInternal(stranger, tc.id)
if err != nil {
t.Fatalf("%v: %v", tc.id, err)
}
if got := options["aws_access_key_id"]; got != tc.want {
t.Errorf("%v: vended %q, want %q", tc.id, got, tc.want)
}
}
}
// A declare may restate the dataset's own name path; any other location is refused.
func TestDeclareTakesOnlyItsNamePath(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$other/declare", `{"location":"s3://analytics/sales/elsewhere"}`, http.StatusBadRequest)
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{"location":"s3://analytics/sales/orders/"}`, http.StatusOK))
if declared.Location != "s3://analytics/sales/orders" {
t.Fatalf("declared location = %q", declared.Location)
}
}
// actionsAuthenticator authenticates every request as name, holding actions.
type actionsAuthenticator struct {
name string
actions []string
}
func (a actionsAuthenticator) AuthenticateRequest(*http.Request) (string, interface{}, s3err.ErrorCode) {
return a.name, &struct {
Name string
Actions []string
}{Name: a.name, Actions: a.actions}, s3err.ErrNone
}
func (actionsAuthenticator) DefaultAllow() bool { return false }
func (actionsAuthenticator) AuthEnabled() bool { return true }
// A register points a name at a dataset that exists: a location holding no
// Lance dataset (nothing there, or a dropped table's root, which its drop
// emptied) is refused, so a register never claims a location in the
// catalog's stead; a location holding one (_versions/) registers.
func TestRegisterNeedsALanceDataset(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", s3tables.FormatLance)
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$empty/register", `{"location":"s3://analytics/sales/a"}`, http.StatusBadRequest)
// a caller who may not create there learns nothing about the location
server := NewServer(s3tables.NewManagerClient(h.filer.Client), actionsAuthenticator{name: "nobody", actions: []string{"s3tables:GetTable"}})
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
nobody := &testHarness{router: router, filer: h.filer, admin: h.admin, server: server}
if r := nobody.do(t, http.MethodPost, "/v1/table/analytics$sales$empty/register", `{"location":"s3://analytics/sales/a"}`); r.Code != http.StatusForbidden {
t.Errorf("register by a caller who may not create: %d (%s), want 403", r.Code, r.Body.String())
}
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{}`, http.StatusOK))
dir := "/buckets/" + strings.TrimPrefix(declared.Location, "s3://")
if h.filer.Get(path.Dir(dir), path.Base(dir)) == nil { // a declare at the name path made it already
h.filer.Put(path.Dir(dir), path.Base(dir), nil)
}
h.filer.Put(dir, versionsDir, nil)
h.filer.PutFile(dir+"/"+versionsDir, "1.manifest", time.Now())
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/drop", `{}`, http.StatusOK)
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$dropped/register", `{"location":"`+declared.Location+`"}`, http.StatusBadRequest)
// a location in another namespace is refused alike whether a dataset is
// there or not: the register is no probe of other namespaces
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$secret/create", `{}`, http.StatusOK)
h.filer.Put("/buckets/analytics/secret", "ledger", nil)
h.filer.Put("/buckets/analytics/secret/ledger", versionsDir, nil)
h.filer.PutFile("/buckets/analytics/secret/ledger/"+versionsDir, "1.manifest", time.Now())
existing := h.do(t, http.MethodPost, "/v1/table/analytics$sales$probe/register", `{"location":"s3://analytics/secret/ledger"}`)
absent := h.do(t, http.MethodPost, "/v1/table/analytics$sales$probe/register", `{"location":"s3://analytics/secret/nothing"}`)
if existing.Code < 400 || existing.Code != absent.Code || existing.Body.String() != absent.Body.String() {
t.Errorf("register at another namespace's dataset: %d %s; at an absent path there: %d %s; want one refusal",
existing.Code, existing.Body.String(), absent.Code, absent.Body.String())
}
// a file named _versions is no dataset
h.filer.Put("/buckets/analytics/sales", "flat", nil)
h.filer.PutFile("/buckets/analytics/sales/flat", versionsDir, time.Now())
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$flat/register", `{"location":"s3://analytics/sales/flat"}`, http.StatusBadRequest)
// positive control: a dataset written there registers
h.filer.Put("/buckets/analytics/sales", "imported", nil)
h.filer.Put("/buckets/analytics/sales/imported", versionsDir, nil)
h.filer.PutFile("/buckets/analytics/sales/imported/"+versionsDir, "1.manifest", time.Now())
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$imported/register", `{"location":"s3://analytics/sales/imported"}`, http.StatusOK)
}
// A register of a name that already has a record answers for that record,
// whatever the location it names holds.
func TestRegisterOfAnExistingName(t *testing.T) {
h := newTestHarness(t)
h.createBucket(t, "analytics", "")
h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK)
if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{
TableBucketARN: h.bucketARN(t, "analytics"),
Namespace: []string{"sales"},
Name: "ledger",
Format: s3tables.FormatIceberg,
MetadataLocation: "s3://analytics/sales/ledger/metadata/v1.metadata.json",
}, &s3tables.CreateTableResponse{}, ""); err != nil {
t.Fatalf("create iceberg table: %v", err)
}
declared := decode[DeclareTableResponse](t,
h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{}`, http.StatusOK))
t.Run("another format", func(t *testing.T) {
recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$ledger/register", `{"location":"s3://analytics/sales/nothing"}`, http.StatusConflict)
if got := decode[errorResponse](t, recorder); got.Code != codeTableAlreadyExists {
t.Fatalf("error code = %d, want %d", got.Code, codeTableAlreadyExists)
}
})
t.Run("a caller who may only create", func(t *testing.T) {
server := NewServer(s3tables.NewManagerClient(h.filer.Client), actionsAuthenticator{name: "creator", actions: []string{"s3tables:CreateTable"}})
router := mux.NewRouter().SkipClean(true)
server.RegisterRoutes(router)
creator := &testHarness{router: router, filer: h.filer, admin: h.admin, server: server}
for _, location := range []string{"s3://analytics/sales/ledger", "s3://analytics/sales/nothing", declared.Location} {
recorder := creator.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register", `{"location":"`+location+`"}`, http.StatusConflict)
if got := decode[errorResponse](t, recorder); got.Code != codeTableAlreadyExists {
t.Fatalf("%s: error code = %d, want %d", location, got.Code, codeTableAlreadyExists)
}
}
})
}