Files
seaweedfs/weed/s3api/s3api_iceberg_vended_session_test.go
T
442e0a24c6 iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s (#13138)
* iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s

## Problem

The Iceberg REST catalog vends table-scoped S3 sessions on load and create with one process-wide lifetime, `-iceberg.credentialDurationSeconds` (default 3600). A client has no way to ask for less, and nothing can go below STS's 900 s floor. Some deployments want short sessions for some callers (a one-off read, a session handed to a less trusted process) without shortening them for every client: a process-wide 900 already breaks clients that keep a loaded table object for longer than its session (PyIceberg does not refresh vended credentials; DuckDB, Spark and Trino re-load and are fine).

The Iceberg REST spec has no parameter for a credential lifetime. The precedent is `DurationSeconds` on AWS STS and on Lake Formation's `GetTemporaryGlueTableCredentials`.

## Fix

- **Request header** `X-SeaweedFS-Credential-Duration-Seconds` on a load or create that asks for vended credentials (`X-Iceberg-Access-Delegation: vended-credentials`). A positive whole number of at most 9 digits is passed to the vendor; a missing, malformed, zero, signed or overlong value is ignored without an error, so clients that never send it see no change.
- **It can only shorten a session.** The vended lifetime is `min(asked, configured)`; with no configured duration the ceiling is STS's `TokenDuration`, capped at `MaxSessionLength` as STS caps it. A request at or above the ceiling changes nothing (the configured duration is sent, as before).
- **Floor:** new `-iceberg.credentialMinDurationSeconds` (`-s3.iceberg.credentialMinDurationSeconds` on `weed server` and `weed mini`), **default 900, which keeps today's behaviour exactly.** A request below the floor is raised to it. Values outside 1-900 mean 900, with a warning at startup; the setting can only lower the floor.
- **STS:** `AssumeRoleForPrincipalRequest` gains `MinDurationSeconds`, a per-request floor honoured only within (0, 900]. Only the catalog's vend sets it, and only when the client actually shortened the session: a vend at the configured duration keeps the 900 s floor (so a configured `credentialDurationSeconds` under 900 is still refused), and AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials and every other action keep 900 through the unchanged `validateSessionDurationSeconds`. `MinSessionDurationSeconds` names the 900.
- **Caching:** load answers now send `Vary: X-Iceberg-Access-Delegation, X-SeaweedFS-Credential-Duration-Seconds`, so a cache never hands a session vended for one lifetime to a request that asked for another.
- The client learns the lifetime it got from `s3.session-token-expires-at-ms`, as today. The Lance namespace vend passes 0 (unchanged).

## Tests

- `weed/s3api`: `TestVendDurationRequestOnlyShortensTheSession` (real STS and trust policy; the lifetime read from the session JWT's `exp - iat` and `max_dur`): nothing asked keeps 3600; 120 honoured; 60 at a floor of 60; 7200 capped to 3600; 30 raised to a floor of 60; floor unset, 900 or 1200 keeps 900. `TestVendFloorDoesNotLowerAssumeRole`: with the floor at 60 the vend mints 60 s (positive control) while AssumeRole and AssumeRoleWithCredentials on the same server refuse 60 s. `TestVendDurationRequestRespectsMaxSessionLength`, `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`.
- `weed/iam/sts`: `TestSessionFloorIsLoweredOnlyForTheRequestThatAsks`.
- `weed/s3api/iceberg`: `TestCredentialDurationHeaderReachesTheVendor` (the accepted and ignored header forms), and the Vary test updated.
- Each rule undone turns its test red (request ignored: `TestVendDurationRequestOnlyShortensTheSession`, `…RespectsMaxSessionLength`; floor applied to every vend: `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`).
- `go vet` and `go test` of `weed/s3api`, `weed/s3api/iceberg`, `weed/iam/sts`, `weed/iam/integration`, `weed/command` pass, `-race` on `weed/s3api/iceberg`, and `weed` builds.

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

* iceberg: let a shortened vend fit a caller credential with less than 900 s left

A vend the caller shortened below 900 s (with a lower catalog floor)
needs only that floor of the caller's credential to remain, not 900 s.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 10:52:41 -08:00

292 lines
13 KiB
Go

package s3api
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
// vendingServer is an S3ApiServer whose catalog role trusts the vendor, with
// the identity of newSharedIdentityIAM (one identity, two keys).
func vendingServer(t *testing.T) *S3ApiServer {
t.Helper()
mgr := newTestIAMManager(t)
require.NoError(t, mgr.CreateRole(context.Background(), "", "IcebergTableAccess", &integration.RoleDefinition{
RoleName: "IcebergTableAccess",
TrustPolicy: &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Principal: map[string]interface{}{"Federated": icebergVendedCredentialsProvider},
Action: []string{"sts:AssumeRoleWithCredentials"},
}},
},
}))
iam := newSharedIdentityIAM()
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
s3a := &S3ApiServer{iam: iam}
s3a.SetIcebergCredentialRole("arn:aws:iam::role/IcebergTableAccess", 3600)
return s3a
}
// vend mints table credentials for principal as if its request had been
// signed with accessKey ("" for a request that recorded none); a non-empty
// secret marks the credential as a stored identity's, as a verifier would.
func vend(t *testing.T, s3a *S3ApiServer, principal, accessKey, secret string) *VendedCredentials {
t.Helper()
ctx := context.Background()
if accessKey != "" {
ctx = s3_constants.SetAccessKeyIdInContext(ctx, accessKey)
}
if secret != "" {
ctx = s3_constants.SetStoredAccessKeyIdInContext(ctx, accessKey, secret)
}
creds, err := s3a.VendTableCredentials(ctx, principal, "warehouse", "ns/t", false, 0)
require.NoError(t, err)
require.NotNil(t, creds)
return creds
}
// use validates a vended session the way a data-path request carrying it is
// validated.
func use(t *testing.T, s3a *S3ApiServer, creds *VendedCredentials) s3err.ErrorCode {
t.Helper()
r, err := newTestRequest("GET", "https://example.com/warehouse/ns/t/data/f.parquet", 0, nil)
require.NoError(t, err)
_, _, errCode := s3a.iam.validateSTSSessionToken(r, creds.SessionToken, creds.AccessKeyID)
return errCode
}
func sessionInfo(t *testing.T, s3a *S3ApiServer, creds *VendedCredentials) *sts.SessionInfo {
t.Helper()
info, err := s3a.stsService().ValidateSessionToken(context.Background(), creds.SessionToken)
require.NoError(t, err)
return info
}
func TestVendedSessionEndsWithItsAccessKey(t *testing.T) {
s3a := vendingServer(t)
sessionA := vend(t, s3a, "shared-user", sharedKeyA, sharedSecretA)
sessionB := vend(t, s3a, "shared-user", sharedKeyB, sharedSecretB)
require.Equal(t, s3err.ErrNone, use(t, s3a, sessionA), "control: the session works while its key does")
require.Equal(t, s3err.ErrNone, use(t, s3a, sessionB))
identity := s3a.iam.nameToIdentity["shared-user"]
identity.Credentials[0].Status = iamAccessKeyStatusInactive
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, sessionA), "key A deactivated")
assert.Equal(t, s3err.ErrNone, use(t, s3a, sessionB), "the session vended through key B keeps working")
identity.Credentials[0].Status = iamAccessKeyStatusActive
assert.Equal(t, s3err.ErrNone, use(t, s3a, sessionA), "key A reactivated")
identity.Credentials[0].Expiration = time.Now().Add(-time.Minute).Unix()
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, sessionA), "key A expired")
identity.Credentials[0].Expiration = 0
identity.Credentials = identity.Credentials[1:]
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, sessionA), "key A deleted")
assert.Equal(t, s3err.ErrNone, use(t, s3a, sessionB), "the session vended through key B keeps working")
}
func TestVendedSessionEndsWithItsIdentity(t *testing.T) {
s3a := vendingServer(t)
session := vend(t, s3a, "shared-user", sharedKeyA, sharedSecretA)
require.Equal(t, s3err.ErrNone, use(t, s3a, session))
s3a.iam.nameToIdentity["shared-user"].Disabled = true
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, session), "identity disabled")
s3a.iam.nameToIdentity["shared-user"].Disabled = false
assert.Equal(t, s3err.ErrNone, use(t, s3a, session), "identity enabled again")
delete(s3a.iam.nameToIdentity, "shared-user")
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, session), "identity deleted")
}
// A caller that is not a stored identity (a caller signing with another STS
// session's key, an OIDC user, a request that recorded no key) still gets
// credentials, unbound as before: binding them would refuse every request
// made with them.
func TestVendedSessionIsBoundOnlyForAStoredIdentitysKey(t *testing.T) {
s3a := vendingServer(t)
control := sessionInfo(t, s3a, vend(t, s3a, "shared-user", sharedKeyA, sharedSecretA))
assert.Equal(t, sharedKeyA, control.SourceAccessKeyId, "control")
assert.Equal(t, sharedKeyA, control.BoundAccessKeyId, "control")
for _, tc := range []struct{ principal, key, why string }{
{"47ad4828c45b3f337bc3146081ba8f0f", "ASIATEMPORARYKEY0001", "an STS session's subject and temporary key"},
{"shared-user", "ASIATEMPORARYKEY0001", "an STS session whose subject names a stored identity"},
{"alice@example.com", "", "an OIDC user"},
{"shared-user", "", "no recorded key"},
} {
session := vend(t, s3a, tc.principal, tc.key, "")
info := sessionInfo(t, s3a, session)
assert.Equal(t, tc.key, info.SourceAccessKeyId, tc.why)
assert.Empty(t, info.BoundAccessKeyId, tc.why)
assert.Equal(t, s3err.ErrNone, use(t, s3a, session), tc.why)
}
}
// Tokens minted before the binding existed record the caller's key under the
// audit claim only. Validating them as bound would end live table credentials
// at upgrade — a chained STS caller's key can never resolve to a stored
// credential. They stay valid until expiry, as they always did.
func TestLegacyVendedSessionStaysUnbound(t *testing.T) {
iam := newSharedIdentityIAM()
iam.iamIntegration = &MockIAMIntegration{
validateSessionFunc: func(ctx context.Context, token string) (*sts.SessionInfo, error) {
return &sts.SessionInfo{
SessionId: "sid",
AssumedRoleUser: "arn:aws:sts::assumed-role/Reader/session",
Principal: "arn:aws:sts::assumed-role/Reader/session",
IdentityProvider: icebergVendedCredentialsProvider,
ExternalUserId: "someone-not-in-the-identity-table",
SourceAccessKeyId: "ASIATEMPORARYKEY0001",
Credentials: &sts.Credentials{AccessKeyId: "ASIALEGACY", SecretAccessKey: "secret"},
ExpiresAt: time.Now().Add(time.Hour),
}, nil
},
}
r, err := newTestRequest("GET", "https://example.com/bucket/f.parquet", 0, nil)
require.NoError(t, err)
_, _, errCode := iam.validateSTSSessionToken(r, "token", "ASIALEGACY")
assert.Equal(t, s3err.ErrNone, errCode)
}
// A key re-created under the same id with a different secret does not revive
// sessions bound to the deleted original: the fingerprint recorded at mint
// time no longer matches.
func TestRecreatedKeyDoesNotReviveVendedSession(t *testing.T) {
s3a := vendingServer(t)
session := vend(t, s3a, "shared-user", sharedKeyA, sharedSecretA)
require.Equal(t, s3err.ErrNone, use(t, s3a, session))
identity := s3a.iam.nameToIdentity["shared-user"]
identity.Credentials[0] = &Credential{AccessKey: sharedKeyA, SecretKey: "recreated-secret"}
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, session), "same id, different secret")
identity.Credentials[0] = &Credential{AccessKey: sharedKeyA, SecretKey: sharedSecretA}
assert.Equal(t, s3err.ErrNone, use(t, s3a, session), "the identical credential is indistinguishable")
}
// A session for a stored identity stays bound even when the key no longer
// resolves at vend time — revoked between the request's authentication and
// the vend, or held by a different identity now. The session dies on its
// first request instead of living unbound until it expires.
func TestVendedSessionStaysBoundWhenTheKeyIsGoneAtVend(t *testing.T) {
s3a := vendingServer(t)
identity := s3a.iam.nameToIdentity["shared-user"]
identity.Credentials = identity.Credentials[1:] // sharedKeyA revoked mid-request
session := vend(t, s3a, "shared-user", sharedKeyA, sharedSecretA)
assert.Equal(t, sharedKeyA, sessionInfo(t, s3a, session).SourceAccessKeyId, "still bound")
assert.Equal(t, s3err.ErrInvalidAccessKeyID, use(t, s3a, session), "the dead key's session is refused")
}
// Only sessions the catalog vended are bound; any other STS session (web
// identity, AssumeRole) is validated as before.
func TestOtherSessionsAreNotBoundToAKey(t *testing.T) {
iam := newSharedIdentityIAM()
iam.iamIntegration = &MockIAMIntegration{
validateSessionFunc: func(ctx context.Context, token string) (*sts.SessionInfo, error) {
return &sts.SessionInfo{
SessionId: "sid",
AssumedRoleUser: "arn:aws:sts::assumed-role/Reader/session",
Principal: "arn:aws:sts::assumed-role/Reader/session",
IdentityProvider: "oidc-provider",
ExternalUserId: "someone-not-in-the-identity-table",
SourceAccessKeyId: "AKIAGONE",
Credentials: &sts.Credentials{AccessKeyId: "ASIAWEBID", SecretAccessKey: "secret"},
ExpiresAt: time.Now().Add(time.Hour),
}, nil
},
}
r, err := newTestRequest("GET", "https://example.com/bucket/f.parquet", 0, nil)
require.NoError(t, err)
_, _, errCode := iam.validateSTSSessionToken(r, "token", "ASIAWEBID")
assert.Equal(t, s3err.ErrNone, errCode)
}
// The check on the request path is one read-locked map lookup and a scan of
// one identity's keys.
func BenchmarkVendedSessionKeyLive(b *testing.B) {
iam := newSharedIdentityIAM()
for i := 0; i < 1000; i++ {
name := fmt.Sprintf("user-%04d", i)
iam.nameToIdentity[name] = &Identity{Name: name, Credentials: []*Credential{{AccessKey: name}}}
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if iam.vendedSessionKeyLive("shared-user", sharedKeyB, "") != s3err.ErrNone {
b.Fatal("refused")
}
}
}
// A caller whose own credential expires (an STS session's key) gets a session
// that ends no later than that credential, or none when less than the
// shortest STS session remains.
func TestVendedSessionEndsWithTheCallersCredential(t *testing.T) {
s3a := vendingServer(t)
vendExpiring := func(remaining time.Duration) (*VendedCredentials, time.Time) {
r := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/", nil))
ctx := s3_constants.SetAccessKeyIdInContext(r.Context(), "ASIATEMPORARYKEY0001")
expiresAt := time.Now().Add(remaining).Truncate(time.Second)
s3_constants.RecordCredentialExpiration(ctx, expiresAt.Unix())
creds, err := s3a.VendTableCredentials(ctx, "47ad4828c45b3f337bc3146081ba8f0f", "warehouse", "ns/t", false, 0)
require.NoError(t, err)
return creds, expiresAt
}
creds, expiresAt := vendExpiring(20 * time.Minute)
require.NotNil(t, creds)
assert.True(t, creds.Expiration.Equal(expiresAt), "session ends at %v, the caller's credential at %v", creds.Expiration, expiresAt)
assert.Equal(t, s3err.ErrNone, use(t, s3a, creds))
creds, expiresAt = vendExpiring(3 * time.Hour)
require.NotNil(t, creds)
assert.WithinDuration(t, time.Now().Add(time.Hour), creds.Expiration, 5*time.Second, "the configured duration applies when the caller outlives it")
creds, _ = vendExpiring(10 * time.Minute)
assert.Nil(t, creds, "less than the shortest STS session remains")
}
// A vend the caller shortened below 900 s needs only the catalog's floor of
// the caller's credential to remain.
func TestShortenedVendFitsTheCallersRemainingCredential(t *testing.T) {
s3a := vendingServer(t)
s3a.SetIcebergCredentialMinDuration(60)
vendExpiring := func(remaining time.Duration, requestedSeconds int64) *VendedCredentials {
r := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/", nil))
ctx := s3_constants.SetAccessKeyIdInContext(r.Context(), "ASIATEMPORARYKEY0001")
s3_constants.RecordCredentialExpiration(ctx, time.Now().Add(remaining).Unix())
creds, err := s3a.VendTableCredentials(ctx, "47ad4828c45b3f337bc3146081ba8f0f", "warehouse", "ns/t", false, requestedSeconds)
require.NoError(t, err)
return creds
}
creds := vendExpiring(10*time.Minute, 120)
require.NotNil(t, creds, "a 120 s session fits in the 10 minutes left")
assert.WithinDuration(t, time.Now().Add(120*time.Second), creds.Expiration, 5*time.Second)
assert.Equal(t, s3err.ErrNone, use(t, s3a, creds))
creds = vendExpiring(90*time.Second, 120)
require.NotNil(t, creds, "the floor of 60 s fits in the 90 s left")
assert.WithinDuration(t, time.Now().Add(90*time.Second), creds.Expiration, 5*time.Second, "capped at the caller's credential")
assert.Nil(t, vendExpiring(30*time.Second, 120), "less than the catalog's floor remains")
assert.Nil(t, vendExpiring(10*time.Minute, 0), "a vend at the configured duration keeps the 900 s threshold")
}