Files
seaweedfs/weed/s3api/s3api_iceberg_credentials_test.go
T
10c66011c8 iceberg: vended credentials list only the table's directory (#13157)
s3: vended credentials list only inside their table's directory

A vended session's s3:ListBucket is conditioned on s3:prefix
{prefix, prefix/*}. The bare table path (ns/t) also matches every
sibling whose name starts with it, so a session vended for ns/t lists the
object names of ns/t2/..., ns/t_x/... and ns/t-<uuid>/... (the catalog's
own placements of other tables).

The condition is now {prefix/, prefix/*}: the table's directory only. A
client listing the table's location without the trailing slash (Java's
S3FileIO.listPrefix(location), used by remove_orphan_files) is refused
with vended credentials; reads, writes and listings of the table's
directory are unaffected.

Test: TestTablePrefixSessionPolicyRestrictsListing now expects the
slash-terminated pair; red with the bare prefix back.

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

327 lines
12 KiB
Go

package s3api
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
func TestTablePrefixSessionPolicyScopesToTheTable(t *testing.T) {
raw, err := tablePrefixSessionPolicy("warehouse", "analytics/events", false)
if err != nil {
t.Fatalf("tablePrefixSessionPolicy() error = %v", err)
}
var policy struct {
Statement []struct {
Effect string `json:"Effect"`
Action []string `json:"Action"`
Resource []string `json:"Resource"`
} `json:"Statement"`
}
if err := json.Unmarshal([]byte(raw), &policy); err != nil {
t.Fatalf("policy is not valid JSON: %v", err)
}
// objects, conditioned bucket listing, and unconditioned location lookup
if len(policy.Statement) != 3 {
t.Fatalf("policy has %d statements, want 3", len(policy.Statement))
}
objects := policy.Statement[0]
if objects.Resource[0] != "arn:aws:s3:::warehouse/analytics/events/*" {
t.Errorf("object resource = %q, want the table prefix only", objects.Resource[0])
}
if policy.Statement[1].Resource[0] != "arn:aws:s3:::warehouse" {
t.Errorf("bucket resource = %q", policy.Statement[1].Resource[0])
}
for _, statement := range policy.Statement {
if statement.Effect != "Allow" {
t.Errorf("statement effect = %q, want Allow", statement.Effect)
}
}
}
// A caller the catalog would not let commit gets a session that can read the
// table's files and nothing more.
func TestTablePrefixSessionPolicyReadOnly(t *testing.T) {
raw, err := tablePrefixSessionPolicy("warehouse", "analytics/events", true)
if err != nil {
t.Fatalf("tablePrefixSessionPolicy() error = %v", err)
}
var policy struct {
Statement []struct {
Action []string `json:"Action"`
} `json:"Statement"`
}
if err := json.Unmarshal([]byte(raw), &policy); err != nil {
t.Fatalf("policy is not valid JSON: %v", err)
}
for _, statement := range policy.Statement {
for _, action := range statement.Action {
switch action {
case "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts":
t.Errorf("read-only session policy grants %s", action)
}
}
}
if got := policy.Statement[0].Action; len(got) != 1 || got[0] != "s3:GetObject" {
t.Errorf("object actions = %v, want [s3:GetObject]", got)
}
}
// A table at the bucket root has no prefix to scope to, and vending would hand
// out read and write over every other table in the bucket.
func TestTablePrefixSessionPolicyRefusesAWholeBucket(t *testing.T) {
if _, err := tablePrefixSessionPolicy("warehouse", "", false); err == nil {
t.Error("tablePrefixSessionPolicy() error = nil, want a refusal for an empty prefix")
}
if _, err := tablePrefixSessionPolicy("warehouse", "/", false); err == nil {
t.Error("a prefix of only separators was accepted")
}
}
// GetBucketLocation carries no prefix, so conditioning it would deny location
// discovery to every vended credential.
func TestTablePrefixSessionPolicyLeavesBucketLocationUnconditioned(t *testing.T) {
raw, err := tablePrefixSessionPolicy("warehouse", "analytics/events", false)
if err != nil {
t.Fatalf("tablePrefixSessionPolicy() error = %v", err)
}
var policy struct {
Statement []struct {
Action []string `json:"Action"`
Condition map[string]any `json:"Condition"`
} `json:"Statement"`
}
if err := json.Unmarshal([]byte(raw), &policy); err != nil {
t.Fatalf("policy is not valid JSON: %v", err)
}
for _, statement := range policy.Statement {
for _, action := range statement.Action {
if action == "s3:GetBucketLocation" && statement.Condition != nil {
t.Errorf("s3:GetBucketLocation carries a condition it can never satisfy: %v", statement.Condition)
}
if action == "s3:ListBucketMultipartUploads" {
t.Error("s3:ListBucketMultipartUploads is granted; it cannot be scoped by prefix")
}
}
}
}
func TestIcebergSessionNameIsBounded(t *testing.T) {
name := icebergSessionName(strings.Repeat("principal", 10), "warehouse", "ns/table", "")
if len(name) > 64 {
t.Errorf("session name is %d chars, want at most 64", len(name))
}
for _, r := range name {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
default:
t.Errorf("session name %q contains %q, which AWS rejects", name, r)
}
}
}
// Vending stays off until an operator names a role, so the catalog keeps
// telling clients to use their own credentials.
func TestVendTableCredentialsDisabledWithoutRole(t *testing.T) {
s3a := &S3ApiServer{}
credentials, err := s3a.VendTableCredentials(context.Background(), "admin", "warehouse", "ns/t", false, 0)
if err != nil {
t.Fatalf("VendTableCredentials() error = %v, want nil", err)
}
if credentials != nil {
t.Errorf("VendTableCredentials() = %v, want nil while no role is configured", credentials)
}
}
func TestVendTableCredentialsNeedsSTS(t *testing.T) {
s3a := &S3ApiServer{}
s3a.SetIcebergCredentialRole("arn:aws:iam::role/IcebergTableAccess", 3600)
if _, err := s3a.VendTableCredentials(context.Background(), "admin", "warehouse", "ns/t", false, 0); err == nil {
t.Error("VendTableCredentials() error = nil, want an error when STS is not configured")
}
}
// Listing is granted on the bucket, so the prefix condition is what keeps a
// vended credential from enumerating other tables.
func TestTablePrefixSessionPolicyRestrictsListing(t *testing.T) {
raw, err := tablePrefixSessionPolicy("warehouse", "analytics/events", false)
if err != nil {
t.Fatalf("tablePrefixSessionPolicy() error = %v", err)
}
var policy struct {
Statement []struct {
Action []string `json:"Action"`
Condition map[string]map[string][]string `json:"Condition"`
} `json:"Statement"`
}
if err := json.Unmarshal([]byte(raw), &policy); err != nil {
t.Fatalf("policy is not valid JSON: %v", err)
}
var bucketStatement *struct {
Action []string `json:"Action"`
Condition map[string]map[string][]string `json:"Condition"`
}
for i := range policy.Statement {
for _, action := range policy.Statement[i].Action {
if action == "s3:ListBucket" {
bucketStatement = &policy.Statement[i]
}
}
}
if bucketStatement == nil {
t.Fatal("no statement grants s3:ListBucket")
}
prefixes := bucketStatement.Condition["StringLike"]["s3:prefix"]
// the table's directory, slash included: the bare prefix would also match
// sibling tables (analytics/events2/..., analytics/events-<uuid>/...)
want := map[string]bool{"analytics/events/": true, "analytics/events/*": true}
if len(prefixes) != len(want) {
t.Fatalf("s3:prefix = %v, want %v", prefixes, want)
}
for _, prefix := range prefixes {
if !want[prefix] {
t.Errorf("s3:prefix contains %q, which is outside the table", prefix)
}
}
}
// A location carrying a wildcard would widen the resource pattern to sibling
// tables, so it is refused instead of vended.
func TestTablePrefixSessionPolicyRefusesWildcards(t *testing.T) {
for _, prefix := range []string{"analytics/*", "analytics/ev?nts", "*"} {
if _, err := tablePrefixSessionPolicy("warehouse", prefix, false); err == nil {
t.Errorf("tablePrefixSessionPolicy(%q) error = nil, want a refusal", prefix)
}
}
if _, err := tablePrefixSessionPolicy("ware*house", "analytics/events", false); err == nil {
t.Error("a wildcard in the bucket name was accepted")
}
}
// vendLifetime vends with requestedSeconds and returns the session's lifetime
// as its JWT states it (exp - iat), checking the expiry handed to the client
// is the JWT's.
func vendLifetime(t *testing.T, s3a *S3ApiServer, requestedSeconds int64) int64 {
t.Helper()
ctx := s3_constants.SetAccessKeyIdInContext(context.Background(), sharedKeyA)
ctx = s3_constants.SetStoredAccessKeyIdInContext(ctx, sharedKeyA, sharedSecretA)
creds, err := s3a.VendTableCredentials(ctx, "shared-user", "warehouse", "ns/t", false, requestedSeconds)
require.NoError(t, err)
require.NotNil(t, creds)
parts := strings.Split(creds.SessionToken, ".")
require.Len(t, parts, 3)
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
require.NoError(t, err)
var claims struct {
Exp int64 `json:"exp"`
Iat int64 `json:"iat"`
MaxDur int64 `json:"max_dur"`
}
require.NoError(t, json.Unmarshal(payload, &claims))
require.NotZero(t, claims.Exp)
require.NotZero(t, claims.Iat)
require.NotZero(t, claims.MaxDur)
assert.Equal(t, claims.Exp, creds.Expiration.Unix(), "the client is told the JWT's expiry")
// exp is set a moment before iat and both are whole seconds, so a second
// boundary between the two reads one second short.
assert.InDelta(t, claims.MaxDur, claims.Exp-claims.Iat, 1, "the JWT's exp - iat is its lifetime")
return claims.MaxDur
}
// A vend may ask for a shorter session (X-SeaweedFS-Credential-Duration-Seconds), never
// a longer one, and never below the catalog's floor (900 s unless set).
func TestVendDurationRequestOnlyShortensTheSession(t *testing.T) {
for _, tc := range []struct {
name string
floor, requested int64
wantLifetimeSecond int64
}{
{"nothing asked keeps the configured lifetime", 60, 0, 3600},
{"a shorter session is honoured", 60, 120, 120},
{"the floor itself is honoured", 60, 60, 60},
{"a longer session is capped", 60, 7200, 3600},
{"below the floor is raised to it", 60, 30, 60},
{"floor unset keeps 900", 0, 120, 900},
{"floor 900 keeps 900", 900, 120, 900},
{"a floor above 900 is 900", 1200, 120, 900},
} {
t.Run(tc.name, func(t *testing.T) {
s3a := vendingServer(t)
s3a.SetIcebergCredentialMinDuration(tc.floor)
assert.Equal(t, tc.wantLifetimeSecond, vendLifetime(t, s3a, tc.requested))
})
}
}
// The catalog's floor is its own: with it at 60 s the vend gets 60 s (positive
// control) while an STS AssumeRole for 60 s on the same server is refused.
func TestVendFloorDoesNotLowerAssumeRole(t *testing.T) {
s3a := vendingServer(t)
s3a.SetIcebergCredentialMinDuration(60)
require.Equal(t, int64(60), vendLifetime(t, s3a, 60), "positive control: the catalog vends 60 s")
form := url.Values{"Action": {"AssumeRole"}, "DurationSeconds": {"60"}}
r, err := http.NewRequest(http.MethodPost, "/", strings.NewReader(form.Encode()))
require.NoError(t, err)
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
_, _, err = NewSTSHandlers(s3a.stsService(), s3a.iam).parseDurationSeconds(r)
assert.Error(t, err, "AssumeRole keeps the 900 s floor")
sixty := int64(60)
_, err = s3a.stsService().AssumeRoleWithCredentials(context.Background(), &sts.AssumeRoleWithCredentialsRequest{
RoleArn: "arn:aws:iam::role/IcebergTableAccess", Username: "u", Password: "p",
RoleSessionName: "s", ProviderName: icebergVendedCredentialsProvider, DurationSeconds: &sixty,
})
require.Error(t, err)
assert.Contains(t, err.Error(), "DurationSeconds", "AssumeRoleWithCredentials keeps the 900 s floor")
}
// With no configured duration the session a caller gets without asking is
// STS's default capped at MaxSessionLength: a request between the two is not
// shorter, so it changes nothing, and is never sent to STS to be refused.
func TestVendDurationRequestRespectsMaxSessionLength(t *testing.T) {
s3a := vendingServer(t)
s3a.SetIcebergCredentialRole("arn:aws:iam::role/IcebergTableAccess", 0)
s3a.SetIcebergCredentialMinDuration(60)
s3a.stsService().Config.MaxSessionLength = sts.FlexibleDuration{Duration: 1800 * time.Second} // TokenDuration is 3600
assert.Equal(t, int64(1800), vendLifetime(t, s3a, 2000))
assert.Equal(t, int64(1800), vendLifetime(t, s3a, 0), "control: nothing asked")
assert.Equal(t, int64(600), vendLifetime(t, s3a, 600))
}
// The catalog's floor only admits a session a caller asked to shorten: a
// configured duration under 900 s is refused as it always was.
func TestVendFloorDoesNotAdmitAConfiguredDurationBelow900(t *testing.T) {
s3a := vendingServer(t)
s3a.SetIcebergCredentialRole("arn:aws:iam::role/IcebergTableAccess", 120)
s3a.SetIcebergCredentialMinDuration(60)
ctx := s3_constants.SetAccessKeyIdInContext(context.Background(), sharedKeyA)
ctx = s3_constants.SetStoredAccessKeyIdInContext(ctx, sharedKeyA, sharedSecretA)
_, err := s3a.VendTableCredentials(ctx, "shared-user", "warehouse", "ns/t", false, 0)
require.Error(t, err)
assert.Contains(t, err.Error(), "DurationSeconds must be between 900 and")
assert.Equal(t, int64(60), vendLifetime(t, s3a, 60), "control: a requested 60 s is shorter and admitted")
}