mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
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>
314 lines
12 KiB
Go
314 lines
12 KiB
Go
package s3api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
)
|
|
|
|
// icebergVendedCredentialsProvider names the origin recorded on sessions the
|
|
// catalog mints, so audit trails can tell them apart from ordinary logins.
|
|
const icebergVendedCredentialsProvider = "iceberg-catalog"
|
|
|
|
// SetIcebergCredentialRole configures the role the Iceberg catalog assumes when
|
|
// a client asks for vended credentials. Vending stays off until it is set.
|
|
func (s3a *S3ApiServer) SetIcebergCredentialRole(roleArn string, durationSeconds int64) {
|
|
s3a.icebergCredentialRole = strings.TrimSpace(roleArn)
|
|
s3a.icebergCredentialDuration = durationSeconds
|
|
}
|
|
|
|
// SetIcebergCredentialMinDuration sets the shortest session a vend may ask
|
|
// for (the catalog's own floor, below STS's 900 s for other actions). Values
|
|
// outside (0, 900] keep the 900 s floor.
|
|
func (s3a *S3ApiServer) SetIcebergCredentialMinDuration(minSeconds int64) {
|
|
s3a.icebergCredentialMinDuration = minSeconds
|
|
}
|
|
|
|
// icebergCredentialFloor is the effective floor of a catalog-vended session.
|
|
func (s3a *S3ApiServer) icebergCredentialFloor() int64 {
|
|
if m := s3a.icebergCredentialMinDuration; m > 0 && m <= sts.MinSessionDurationSeconds {
|
|
return m
|
|
}
|
|
return sts.MinSessionDurationSeconds
|
|
}
|
|
|
|
// icebergVendDuration is the DurationSeconds of one vend: the configured
|
|
// duration, or the caller's requested one raised to the catalog's floor when
|
|
// that is shorter than the session it would otherwise get. A request can only
|
|
// shorten a session; requestedSeconds <= 0 (nothing asked) keeps the
|
|
// configured duration exactly, 0 leaving the lifetime to STS's default.
|
|
// shortened reports that the requested duration was used, which is the only
|
|
// case the catalog's floor may apply to (a configured duration keeps STS's
|
|
// floor, as before).
|
|
func (s3a *S3ApiServer) icebergVendDuration(stsService *sts.STSService, requestedSeconds int64) (duration int64, shortened bool) {
|
|
configured := s3a.icebergCredentialDuration
|
|
if requestedSeconds <= 0 {
|
|
return configured, false
|
|
}
|
|
// The session the caller gets without asking: the configured duration or
|
|
// STS's default, capped at MaxSessionLength as STS caps it.
|
|
ceiling := configured
|
|
if stsService != nil && stsService.Config != nil {
|
|
if ceiling <= 0 {
|
|
ceiling = int64(stsService.Config.TokenDuration.Duration / time.Second)
|
|
}
|
|
if limit := int64(stsService.Config.MaxSessionLength.Duration / time.Second); limit > 0 && ceiling > limit {
|
|
ceiling = limit
|
|
}
|
|
}
|
|
effective := requestedSeconds
|
|
if floor := s3a.icebergCredentialFloor(); effective < floor {
|
|
effective = floor
|
|
}
|
|
if ceiling <= 0 || effective >= ceiling {
|
|
return configured, false
|
|
}
|
|
return effective, true
|
|
}
|
|
|
|
// VendedCredentials are short-lived S3 credentials scoped to one table.
|
|
type VendedCredentials struct {
|
|
AccessKeyID string
|
|
SecretAccessKey string
|
|
SessionToken string
|
|
Expiration time.Time
|
|
}
|
|
|
|
// VendTableCredentials mints credentials that can read exactly one table's
|
|
// prefix, and write it too unless readOnly, for a caller the Iceberg catalog
|
|
// has already authenticated and authorized. Returns nil when no role is
|
|
// configured, or when the caller's own credential expires sooner than the
|
|
// shortest session this vend may get, which leaves the catalog telling the client to
|
|
// keep using its own credentials. The session never outlives the caller's
|
|
// credential.
|
|
//
|
|
// The access key the caller authenticated with (from ctx) is recorded in the
|
|
// session: a short hash of it ends the session name, so the audit log's
|
|
// requester_arn tells apart the holders of several keys on one identity. When
|
|
// the caller is a stored identity holding that key, the key id is also carried
|
|
// in the session token, binding the session to it: the session ends when the
|
|
// key is deleted or deactivated, or its identity removed or disabled
|
|
// (validateSTSSessionToken).
|
|
//
|
|
// requestedSeconds > 0 asks for a shorter session than configured
|
|
// (icebergVendDuration); it never lengthens one. 0 keeps the configured one.
|
|
func (s3a *S3ApiServer) VendTableCredentials(ctx context.Context, principal, bucket, prefix string, readOnly bool, requestedSeconds int64) (*VendedCredentials, error) {
|
|
if s3a.icebergCredentialRole == "" {
|
|
return nil, nil
|
|
}
|
|
if principal == "" {
|
|
return nil, fmt.Errorf("no principal to vend credentials for")
|
|
}
|
|
if bucket == "" {
|
|
return nil, fmt.Errorf("no bucket to scope credentials to")
|
|
}
|
|
|
|
stsService := s3a.stsService()
|
|
if stsService == nil {
|
|
return nil, fmt.Errorf("STS is not configured")
|
|
}
|
|
|
|
policy, err := tablePrefixSessionPolicy(bucket, prefix, readOnly)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
accessKey := s3_constants.AccessKeyIdFromContext(ctx)
|
|
request := &sts.AssumeRoleForPrincipalRequest{
|
|
RoleArn: s3a.icebergCredentialRole,
|
|
Principal: principal,
|
|
RoleSessionName: icebergSessionName(principal, bucket, prefix, accessKey),
|
|
ProviderName: icebergVendedCredentialsProvider,
|
|
Policy: &policy,
|
|
SourceAccessKeyId: accessKey,
|
|
}
|
|
// Bind the session to the caller's key when the caller authenticated with a
|
|
// stored identity's key — a marker its verifier records, so a caller that
|
|
// signed with an STS session key or OIDC token stays unbound even when its
|
|
// principal names a stored identity, whose session a binding would refuse
|
|
// on every request. The marker survives the key being revoked between
|
|
// authentication and this vend: the session then dies on its first request
|
|
// instead of living unbound until it expires. The binding travels under
|
|
// its own claim — SourceAccessKeyId is audit-only for compatibility with
|
|
// tokens minted before the binding existed.
|
|
if storedKey, storedSecret := s3_constants.StoredCredentialFromContext(ctx); storedKey != "" {
|
|
request.BoundAccessKeyId = storedKey
|
|
request.BoundAccessKeyFingerprint = s3_constants.StoredCredentialFingerprint(s3a.iam.stsSigningKey(), storedKey, storedSecret)
|
|
}
|
|
duration, shortened := s3a.icebergVendDuration(stsService, requestedSeconds)
|
|
if duration > 0 {
|
|
request.DurationSeconds = &duration
|
|
}
|
|
floor := sts.MinSessionDurationSeconds
|
|
if shortened {
|
|
// The catalog's floor applies to a session the caller asked to
|
|
// shorten, and to this request alone: every other STS action, and a
|
|
// vend at the configured duration, keeps the 900 s floor.
|
|
floor = s3a.icebergCredentialFloor()
|
|
request.MinDurationSeconds = floor
|
|
}
|
|
// The vended session must not outlive the caller's own credential. When
|
|
// too little of it remains for the shortest session this vend may get,
|
|
// vend nothing: the client keeps using its own credentials until they expire.
|
|
if expiresAt := s3_constants.CredentialExpirationFromContext(ctx); expiresAt > 0 {
|
|
request.NotAfter = time.Unix(expiresAt, 0)
|
|
if time.Until(request.NotAfter) < time.Duration(floor)*time.Second {
|
|
return nil, nil
|
|
}
|
|
}
|
|
|
|
resp, err := stsService.AssumeRoleForPrincipal(ctx, request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp == nil || resp.Credentials == nil {
|
|
return nil, fmt.Errorf("STS returned no credentials")
|
|
}
|
|
|
|
return &VendedCredentials{
|
|
AccessKeyID: resp.Credentials.AccessKeyId,
|
|
SecretAccessKey: resp.Credentials.SecretAccessKey,
|
|
SessionToken: resp.Credentials.SessionToken,
|
|
Expiration: resp.Credentials.Expiration,
|
|
}, nil
|
|
}
|
|
|
|
func (s3a *S3ApiServer) stsService() *sts.STSService {
|
|
if s3a.iam == nil {
|
|
return nil
|
|
}
|
|
return s3a.iam.stsService()
|
|
}
|
|
|
|
func (iam *IdentityAccessManagement) stsService() *sts.STSService {
|
|
if iam.iamIntegration == nil {
|
|
return nil
|
|
}
|
|
provider, ok := iam.iamIntegration.(IAMManagerProvider)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
manager := provider.GetIAMManager()
|
|
if manager == nil {
|
|
return nil
|
|
}
|
|
return manager.GetSTSService()
|
|
}
|
|
|
|
func (iam *IdentityAccessManagement) stsSigningKey() []byte {
|
|
if s := iam.stsService(); s != nil && s.Config != nil {
|
|
return s.Config.SigningKey
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// tablePrefixSessionPolicy narrows a session to one table's files plus the
|
|
// bucket listing that clients need to resolve them. A read-only session drops
|
|
// the write verbs: the catalog vends no more authority than the caller holds.
|
|
func tablePrefixSessionPolicy(bucket, prefix string, readOnly bool) (string, error) {
|
|
prefix = strings.Trim(prefix, "/")
|
|
// A resource pattern is matched with wildcards, so a location carrying one
|
|
// would widen the session to sibling tables. Refuse rather than escape it:
|
|
// nothing SeaweedFS generates contains these.
|
|
if strings.ContainsAny(bucket, "*?") || strings.ContainsAny(prefix, "*?") {
|
|
return "", fmt.Errorf("refusing to scope credentials to a location with wildcards: s3://%s/%s", bucket, prefix)
|
|
}
|
|
// Without a prefix there is nothing to scope to, and the session would carry
|
|
// read and write over every table in the bucket. A table registered at the
|
|
// bucket root is the only way to get here.
|
|
if prefix == "" {
|
|
return "", fmt.Errorf("refusing to scope credentials to a whole bucket: s3://%s", bucket)
|
|
}
|
|
|
|
objectActions := []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"}
|
|
if readOnly {
|
|
objectActions = []string{"s3:GetObject"}
|
|
}
|
|
|
|
policy := map[string]interface{}{
|
|
"Version": "2012-10-17",
|
|
"Statement": []map[string]interface{}{
|
|
{
|
|
"Effect": "Allow",
|
|
"Action": objectActions,
|
|
"Resource": []string{fmt.Sprintf("arn:aws:s3:::%s/%s/*", bucket, prefix)},
|
|
},
|
|
{
|
|
// Listing is granted on the bucket, so without the condition the
|
|
// session could enumerate every other table's object names; the
|
|
// trailing slash keeps sibling tables like ns/t2 out.
|
|
"Effect": "Allow",
|
|
"Action": []string{"s3:ListBucket"},
|
|
"Resource": []string{fmt.Sprintf("arn:aws:s3:::%s", bucket)},
|
|
"Condition": map[string]interface{}{
|
|
"StringLike": map[string]interface{}{
|
|
"s3:prefix": []string{prefix + "/", prefix + "/*"},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
// GetBucketLocation carries no prefix to condition on, so it sits
|
|
// in its own statement rather than being denied by one.
|
|
// ListBucketMultipartUploads is deliberately absent: Iceberg
|
|
// writers complete and abort by upload id, and granting it either
|
|
// leaks in-flight keys bucket-wide or breaks on the same missing
|
|
// prefix.
|
|
"Effect": "Allow",
|
|
"Action": []string{"s3:GetBucketLocation"},
|
|
"Resource": []string{fmt.Sprintf("arn:aws:s3:::%s", bucket)},
|
|
},
|
|
},
|
|
}
|
|
|
|
encoded, err := json.Marshal(policy)
|
|
if err != nil {
|
|
return "", fmt.Errorf("build session policy: %w", err)
|
|
}
|
|
return string(encoded), nil
|
|
}
|
|
|
|
// icebergSessionKeyTagLength is the hex length of the access key hash that ends
|
|
// a vended session's name: 48 bits, so two keys of one identity collide with
|
|
// odds of about 2^-48.
|
|
const icebergSessionKeyTagLength = 12
|
|
|
|
// icebergSessionKeyTag is "-k" and the first icebergSessionKeyTagLength hex
|
|
// digits of the SHA-256 of the access key id, or "" without a key.
|
|
func icebergSessionKeyTag(accessKey string) string {
|
|
if accessKey == "" {
|
|
return ""
|
|
}
|
|
sum := sha256.Sum256([]byte(accessKey))
|
|
return "-k" + hex.EncodeToString(sum[:])[:icebergSessionKeyTagLength]
|
|
}
|
|
|
|
// icebergSessionName builds a session name that identifies the caller, the
|
|
// table and the caller's access key in audit logs, within the 64-character AWS
|
|
// limit. The key tag is never cut: the table part gives way to it.
|
|
func icebergSessionName(principal, bucket, prefix, accessKey string) string {
|
|
name := fmt.Sprintf("iceberg-%s-%s", principal, strings.ReplaceAll(strings.Trim(prefix, "/"), "/", "-"))
|
|
if strings.Trim(prefix, "/") == "" {
|
|
name = fmt.Sprintf("iceberg-%s-%s", principal, bucket)
|
|
}
|
|
name = strings.Map(func(r rune) rune {
|
|
switch {
|
|
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
|
|
return r
|
|
default:
|
|
return '-'
|
|
}
|
|
}, name)
|
|
tag := icebergSessionKeyTag(accessKey)
|
|
if limit := 64 - len(tag); len(name) > limit {
|
|
name = name[:limit]
|
|
}
|
|
return name + tag
|
|
}
|