Files
seaweedfs/weed/s3api/s3api_iceberg_session_name_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

101 lines
4.3 KiB
Go

package s3api
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"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/s3api/s3_constants"
)
func TestIcebergSessionNameWithoutKeyIsUnchanged(t *testing.T) {
assert.Equal(t, "iceberg-analytics-ns-t", icebergSessionName("analytics", "b", "ns/t", ""))
assert.Equal(t, "iceberg-anonymous-ns-t", icebergSessionName("anonymous", "b", "ns/t", ""))
}
func TestIcebergSessionNameEndsWithTheKeyTag(t *testing.T) {
a := icebergSessionName("analytics", "b", "ns/t", sharedKeyA)
b := icebergSessionName("analytics", "b", "ns/t", sharedKeyB)
assert.NotEqual(t, a, b, "two keys of one identity must give distinguishable session names")
for _, name := range []string{a, b} {
assert.True(t, strings.HasPrefix(name, "iceberg-analytics-ns-t-k"), name)
assert.Len(t, name, len("iceberg-analytics-ns-t-k")+icebergSessionKeyTagLength)
}
assert.Equal(t, a, icebergSessionName("analytics", "b", "ns/t", sharedKeyA), "the tag is stable")
assert.NotContains(t, a, sharedKeyA, "the name carries a hash, not the key id")
}
// A long identity and table give way to the tag; the tag is never cut.
func TestIcebergSessionNameKeepsTheWholeTagWithinTheLimit(t *testing.T) {
principal := "svc-0b6f6d1c-6f1e-4c1a-9f57-3a8f4c0f1d2e"
name := icebergSessionName(principal, "b", "a_long_namespace/a_long_table_name", sharedKeyA)
tag := icebergSessionKeyTag(sharedKeyA)
assert.LessOrEqual(t, len(name), 64)
assert.True(t, strings.HasSuffix(name, tag), name)
assert.True(t, strings.HasPrefix(name, "iceberg-"+principal), name)
for _, r := range name {
ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_'
assert.True(t, ok, "session name %q contains %q", name, r)
}
long := icebergSessionName(strings.Repeat("principal", 10), "b", "ns/t", sharedKeyB)
assert.Len(t, long, 64)
assert.True(t, strings.HasSuffix(long, icebergSessionKeyTag(sharedKeyB)))
}
// The vendor reads the caller's key from the request context.
func TestVendTableCredentialsReadsTheKeyFromTheContext(t *testing.T) {
ctx := s3_constants.SetAccessKeyIdInContext(context.Background(), sharedKeyA)
assert.Equal(t, sharedKeyA, s3_constants.AccessKeyIdFromContext(ctx))
assert.Equal(t, "", s3_constants.AccessKeyIdFromContext(context.Background()))
}
// VendTableCredentials mints a real session from the caller's key: the session
// name ends with the key's tag and the token carries the key id.
func TestVendTableCredentialsRecordsTheCallersKey(t *testing.T) {
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)
for _, k := range []struct{ id, secret string }{{sharedKeyA, sharedSecretA}, {sharedKeyB, sharedSecretB}, {"", ""}} {
key := k.id
ctx := context.Background()
if key != "" {
// As the catalog's auth does: the holder is installed, the verifier records into it.
r := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodGet, "/", nil))
s3_constants.RecordAccessKeyId(r.Context(), key)
s3_constants.RecordStoredAccessKeyId(r.Context(), k.id, k.secret)
ctx = r.Context()
}
creds, err := s3a.VendTableCredentials(ctx, "shared-user", "warehouse", "ns/t", false, 0)
require.NoError(t, err)
require.NotNil(t, creds)
info, err := s3a.stsService().ValidateSessionToken(context.Background(), creds.SessionToken)
require.NoError(t, err)
assert.Equal(t, key, info.SourceAccessKeyId, "key %q", key)
assert.Equal(t, icebergSessionName("shared-user", "warehouse", "ns/t", key), info.SessionName, "key %q", key)
if key != "" {
assert.Contains(t, info.SessionName, icebergSessionKeyTag(key))
}
}
}