Files
seaweedfs/weed/s3api/lance/storage.go
T
Chris LuandClaude Opus 5.5 b9bc42c217 s3vectors: vend write credentials to index data only to the vector engine and Lance worker (#12316)
* security: share the filer admin token check

CheckGrpcAdminPeer verifies an admin Bearer token inline. Move the check
into IsFilerAdminToken so an HTTP endpoint can accept the same token.

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

* lance: recognize the cluster's own components by a signed token

A request whose X-Seaweedfs-Cluster-Token header carries an admin token
signed with jwt.filer_signing.key comes from a component that holds the
cluster key: the vector engine or the Lance maintenance worker. Mark such
a request as trusted. It still authenticates as an identity, which stays
the principal for vended credentials. A dedicated header leaves the
Authorization header to Lance OAuth clients. A gateway with no key
trusts no one.

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

* lance: vend write credentials to a vector bucket's indexes only to trusted callers

An index in a vector bucket's vector namespace is also a Lance table, so
a caller granted s3tables:UpdateTable could describe it, or declare it
again, and get credentials that write the index data without passing the
vector bucket policy. In that namespace both now vend read-only
credentials unless the caller is trusted, and a declare from anyone else
no longer writes the dataset markers.

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

* lance worker: prove the cluster key to the Lance namespace

The gateway now vends write credentials to a vector bucket's indexes only
to callers that send a token signed with jwt.filer_signing.key. The
worker already takes that key for the admin stream; its namespace client
now mints a token from it for every catalog request.

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

* weed-vector: describe the index the gateway created and prove the cluster key

CreateIndex declared a table the gateway had just created, which only
worked because declare is idempotent. Describe it instead. The Lance
namespace vends write credentials to a vector bucket's indexes only to
callers that send a token signed with jwt.filer_signing.key, so take the
key with --filer-signing-key, the same flag the Lance worker has.

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

* lance worker: keep the cluster key out of Debug output

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

* lance: answer a declare of an existing table with its own location

CreateTable succeeds for a name that already exists without looking at
the location requested, and declare kept using that location for the
dataset markers and the vended credentials. Declaring an existing table
with another table's location, such as a vector index, got credentials
to that table's data. Use the location the catalog holds, which
CreateTable now also reports for a new table.

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

* lance: sign cluster tokens with a key derived for the catalog

A cluster token was a filer admin token signed with jwt.filer_signing.key
and, by default, never expired. Sent to the Lance namespace on every
request, often over plain HTTP, a captured one would also authorize the
filer's IAM service. Sign it with a key derived from the cluster key for
this one use, which the admin services do not accept, and mint it with a
five minute lifetime. weed-vector drops its token lifetime flag.

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

* lance: follow a reloaded jwt.filer_signing.key

The Lance namespace copied the cluster key at startup. A SIGHUP reload
refreshes the gateway's filer guard but not that copy, so after a key
rotation the restarted vector engine and worker were no longer trusted.
Read the key from the guard on every check.

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

* iceberg: keep a vector bucket's indexes read-only

An index in a vector bucket is also a catalog table the Iceberg REST
catalog loads, and LoadTable vended credentials that could write it to
any caller granted s3tables:UpdateTable. A commit staged its metadata
file in the index directory on the same grant. Apply the vector
namespace rule to both, after the caller's own UpdateTable check.

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

* iceberg: confine a created table's location to its namespace before writing

Stage-create skips the registration that confines a location to the
table's namespace, yet vends write credentials for that location. A
caller allowed to create a table in any namespace of a bucket could name
another namespace's prefix, a vector index included, and get write
credentials to it. The non-staged create also wrote its first metadata
file there before the registration refused the location.

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

* lance: a declare that finds an existing table answers like describe

Creating a name that already exists is idempotent, so a caller allowed
only to create tables could declare someone else's table and get write
credentials to it, and clear its deregistered marker. Describe would have
vended that caller read-only credentials. A declare now looks the name up
first; when it only finds the table, writing needs UpdateTable, as it does
for describe.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:49:01 -08:00

221 lines
7.8 KiB
Go

package lance
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
const defaultPageSize = 1000
// execute runs one S3 Tables operation as the request's authenticated caller.
func (s *Server) execute(r *http.Request, operation string, req, resp interface{}) error {
identityName := s3_constants.GetIdentityNameFromContext(r)
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return s.tablesManager.Execute(r.Context(), s3tables.NewManagerClient(client), operation, req, resp, identityName)
})
}
func bucketARN(bucket string) string {
arn, _ := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3_constants.AccountAdminId, bucket)
return arn
}
// maxRequestBody bounds what one call can make the catalog hold. Every request
// this surface takes is a small JSON envelope; the largest carries a set of
// properties, not data.
const maxRequestBody = 4 << 20
// decodeBody reads an optional JSON request body. Every Lance operation carries
// one, but the fields that matter are also in the route, so an empty body is
// not an error.
func decodeBody(r *http.Request, into interface{}) error {
body, err := io.ReadAll(io.LimitReader(r.Body, maxRequestBody+1))
if err != nil {
return fmt.Errorf("read request body: %w", err)
}
if len(body) > maxRequestBody {
return fmt.Errorf("request body is larger than %d bytes", maxRequestBody)
}
if len(strings.TrimSpace(string(body))) == 0 {
return nil
}
if err := json.Unmarshal(body, into); err != nil {
return fmt.Errorf("invalid request body: %w", err)
}
return nil
}
// routeIdentifier parses the {id} route variable, writing the error response
// itself when the identifier is malformed.
func routeIdentifier(w http.ResponseWriter, r *http.Request) (identifier, string, bool) {
delimiter := requestDelimiter(r)
id, err := parseIdentifier(mux.Vars(r)["id"], delimiter)
if err != nil {
writeError(w, r, http.StatusBadRequest, codeInvalidInput, err.Error())
return nil, delimiter, false
}
return id, delimiter, true
}
// checkBodyIdentifier enforces the spec rule that a route and a body naming
// different objects is a bad request rather than a silent preference.
func checkBodyIdentifier(w http.ResponseWriter, r *http.Request, id identifier, body []string) bool {
if id.matchesBody(body) {
return true
}
writeError(w, r, http.StatusBadRequest, codeInvalidInput,
"the identifier in the request body does not match the one in the route")
return false
}
func pageSize(r *http.Request) int {
if raw := r.URL.Query().Get("limit"); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 {
return parsed
}
}
return defaultPageSize
}
func boolQuery(r *http.Request, name string) bool {
value, err := strconv.ParseBool(r.URL.Query().Get(name))
return err == nil && value
}
// wants resolves a tri-state request flag: the query parameter the REST spec
// adds, else the body field, else the implementation's own choice.
func wants(r *http.Request, name string, body *bool) bool {
if boolQuery(r, name) {
return true
}
return body != nil && *body
}
// tableLocation is where a table's dataset lives when the caller does not name
// a location. It mirrors the Iceberg catalog's layout so both catalogs put a
// table of the same name in the same place.
func tableLocation(bucket string, ns []string, name string) string {
return fmt.Sprintf("s3://%s/%s/%s", bucket, strings.Join(ns, "."), name)
}
// confineLocation rejects a client-supplied table location that does not resolve
// inside the caller's own bucket, the way the Iceberg gateway confines the same
// field. The location feeds TableDataDirFromMetadataLocation, which joins it
// under /buckets and collapses any "../" segments; an unconfined location lets a
// marker write escape into another tenant's namespace.
func confineLocation(bucket, location string) error {
rest, ok := strings.CutPrefix(location, "s3://")
if !ok {
return fmt.Errorf("location must be an s3:// URI")
}
name, keys, _ := strings.Cut(rest, "/")
if name != bucket {
return fmt.Errorf("location must be within bucket %s", bucket)
}
for _, segment := range strings.Split(keys, "/") {
switch {
case segment == "." || segment == "..":
return fmt.Errorf("location must not contain a path traversal segment")
case strings.ContainsAny(segment, "\\\x00"):
return fmt.Errorf("location contains an invalid character")
}
}
return nil
}
// storageOptions builds the object_store settings a Lance client needs to reach
// the dataset. The key names are the aws_-prefixed forms Lance clients pass
// through to object_store.
func (s *Server) storageOptions(r *http.Request, bucket, location string, vend bool, canWrite func() bool) (map[string]string, error) {
options := map[string]string{}
if s.s3Endpoint != "" {
options["aws_endpoint"] = s.s3Endpoint
if strings.HasPrefix(s.s3Endpoint, "http://") {
// object_store refuses a plaintext endpoint unless told to allow it,
// and the resulting failure reads like a credential problem.
options["allow_http"] = "true"
}
}
if s.s3Region != "" {
options["aws_region"] = s.s3Region
}
if !vend || s.credentialVendor == nil {
return options, nil
}
principal := s3_constants.GetIdentityNameFromContext(r)
credentials, err := s.credentialVendor.VendTableCredentials(r.Context(), principal, bucket, locationPrefix(location), canWrite == nil || !canWrite())
if err != nil {
return nil, err
}
if credentials == nil {
return options, nil
}
options["aws_access_key_id"] = credentials.AccessKeyID
options["aws_secret_access_key"] = credentials.SecretAccessKey
if credentials.SessionToken != "" {
options["aws_session_token"] = credentials.SessionToken
}
if !credentials.Expiration.IsZero() {
options["expires_at_millis"] = strconv.FormatInt(credentials.Expiration.UnixMilli(), 10)
}
return options, nil
}
// mayUpdateTable reports whether the caller may commit to the table the
// credentials would cover, the same gate the Iceberg catalog applies so a
// read-only caller never gets write-capable storage_options.
func (s *Server) mayUpdateTable(r *http.Request, bucket string, ns []string, name string) bool {
if !s.mayWriteNamespace(r, bucket, ns) {
return false
}
req := &s3tables.UpdateTableRequest{
TableBucketARN: bucketARN(bucket),
Namespace: ns,
Name: name,
}
identityName := s3_constants.GetIdentityNameFromContext(r)
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return s.tablesManager.AuthorizeUpdateTable(r.Context(), s3tables.NewManagerClient(client), req, identityName)
})
if err != nil {
glog.V(1).Infof("lance: UpdateTable check for %s/%s failed, vending read-only: %v", bucket, name, err)
}
return err == nil
}
// mayWriteNamespace keeps the vector namespace of a vector bucket out of reach
// of s3tables grants: its index data is written only by trusted callers, and
// the vector bucket policy gates everyone else through S3 Vectors.
func (s *Server) mayWriteNamespace(r *http.Request, bucket string, ns []string) bool {
if isTrustedCaller(r.Context()) {
return true
}
err := s.tablesManager.CheckVectorNamespaceWrite(r.Context(), s.filerClient, bucket, ns)
if err != nil {
glog.V(1).Infof("lance: %s/%s is read-only to this caller: %v", bucket, strings.Join(ns, "."), err)
}
return err == nil
}
// locationPrefix strips the s3://bucket/ part of a location, leaving the key
// prefix a credential is scoped to.
func locationPrefix(location string) string {
trimmed := strings.TrimPrefix(location, "s3://")
if _, prefix, found := strings.Cut(trimmed, "/"); found {
return prefix
}
return ""
}