diff --git a/weed/s3api/auth_credentials.go b/weed/s3api/auth_credentials.go index 5b67c0380f..5722fab067 100644 --- a/weed/s3api/auth_credentials.go +++ b/weed/s3api/auth_credentials.go @@ -141,17 +141,37 @@ type IdentityAccessManagement struct { } type Identity struct { - Name string - Account *Account - Credentials []*Credential - Actions []Action - PolicyNames []string // Attached IAM policy names - PrincipalArn string // ARN for IAM authorization (e.g., "arn:aws:iam::account-id:user/username") - Disabled bool // User status: false = enabled (default), true = disabled - Claims map[string]interface{} // JWT claims for policy substitution - IsStatic bool // Whether identity was loaded from static config (immutable) - IdentityClaim string // Authoritative OIDC identity claim for audit logging (preferred_username/email/sub); empty for non-federated sessions - Certificates []*iam_pb.CertificateMatch + Name string + Account *Account + Credentials []*Credential + Actions []Action + permissionBoundary []Action + serviceAccountParent *Identity + PolicyNames []string // Attached IAM policy names + PrincipalArn string // ARN for IAM authorization (e.g., "arn:aws:iam::account-id:user/username") + Disabled bool // User status: false = enabled (default), true = disabled + Claims map[string]interface{} // JWT claims for policy substitution + IsStatic bool // Whether identity was loaded from static config (immutable) + IdentityClaim string // Authoritative OIDC identity claim for audit logging (preferred_username/email/sub); empty for non-federated sessions + Certificates []*iam_pb.CertificateMatch +} + +func identityForServiceAccount(parent *Identity, sa *iam_pb.ServiceAccount, credential *Credential) *Identity { + if len(sa.Actions) == 0 { + return parent + } + identity := *parent + identity.Credentials = []*Credential{credential} + identity.serviceAccountParent = parent + identity.permissionBoundary = make([]Action, 0, len(sa.Actions)) + for _, action := range sa.Actions { + identity.permissionBoundary = append(identity.permissionBoundary, Action(action)) + } + return &identity +} + +func (identity *Identity) belongsTo(parent *Identity) bool { + return identity == parent || identity != nil && identity.serviceAccountParent == parent } // Account represents a system user, a system user can @@ -959,7 +979,7 @@ func (iam *IdentityAccessManagement) ReplaceS3ApiConfiguration(config *iam_pb.S3 Expiration: sa.Expiration, // Populate expiration from service account } parentIdent.Credentials = append(parentIdent.Credentials, cred) - accessKeyIdent[sa.Credential.AccessKey] = parentIdent + accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, cred) glog.V(3).Infof("Loaded service account %s for parent %s (expiration: %d)", sa.Id, sa.ParentUser, sa.Expiration) } @@ -1169,7 +1189,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap oldIdentity := identities[existingIdx] for _, oldCred := range oldIdentity.Credentials { // Only remove if it still points to this identity - if accessKeyIdent[oldCred.AccessKey] == oldIdentity { + if accessKeyIdent[oldCred.AccessKey].belongsTo(oldIdentity) { delete(accessKeyIdent, oldCred.AccessKey) } } @@ -1209,7 +1229,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap } delete(nameToIdentity, existing.Name) for _, cred := range existing.Credentials { - if accessKeyIdent[cred.AccessKey] == existing { + if accessKeyIdent[cred.AccessKey].belongsTo(existing) { delete(accessKeyIdent, cred.AccessKey) } } @@ -1246,18 +1266,18 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap } // Check if this access key already exists in parent's credentials to avoid duplicates - alreadyExists := false + var existingCredential *Credential for _, existingCred := range parentIdent.Credentials { if existingCred.AccessKey == sa.Credential.AccessKey { - alreadyExists = true + existingCredential = existingCred break } } - if alreadyExists { + if existingCredential != nil { glog.V(3).Infof("Service account %s credential already exists for parent %s, skipping", sa.Id, sa.ParentUser) // Ensure accessKeyIdent mapping is correct - accessKeyIdent[sa.Credential.AccessKey] = parentIdent + accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, existingCredential) continue } @@ -1269,7 +1289,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap Expiration: sa.Expiration, } parentIdent.Credentials = append(parentIdent.Credentials, cred) - accessKeyIdent[sa.Credential.AccessKey] = parentIdent + accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, cred) glog.V(3).Infof("Loaded service account %s for dynamic parent %s (expiration: %d)", sa.Id, sa.ParentUser, sa.Expiration) } @@ -1381,7 +1401,7 @@ func (iam *IdentityAccessManagement) RemoveIdentity(name string) { // Remove from maps delete(iam.nameToIdentity, name) for _, cred := range identity.Credentials { - if iam.accessKeyIdent[cred.AccessKey] == identity { + if iam.accessKeyIdent[cred.AccessKey].belongsTo(identity) { delete(iam.accessKeyIdent, cred.AccessKey) } } @@ -2131,6 +2151,9 @@ func (iam *IdentityAccessManagement) authorizeRequest(r *http.Request, identity r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id) return s3err.ErrNone } + if !(action == s3_constants.ACTION_LIST && bucket == "") && !identity.allowsPermissionBoundary(r, action, bucket, object) { + return s3err.ErrAccessDenied + } // For ListBuckets, authorization is performed in the handler by iterating // through buckets and checking permissions for each. Skip the global check here. @@ -2241,7 +2264,10 @@ func (identity *Identity) CanDo(action Action, bucket string, objectKey string) if identity == nil { return false } - if identity.isAdmin() { + if !identity.allowsPermissionBoundary(nil, action, bucket, objectKey) { + return false + } + if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) { return true } for _, a := range identity.Actions { @@ -2296,6 +2322,21 @@ func (identity *Identity) CanDo(action Action, bucket string, objectKey string) return false } +func (identity *Identity) allowsPermissionBoundary(r *http.Request, action Action, bucket string, objectKey string) bool { + if identity == nil { + return false + } + if len(identity.permissionBoundary) == 0 { + return true + } + boundary := &Identity{Actions: identity.permissionBoundary} + if boundary.CanDo(action, bucket, objectKey) { + return true + } + listing := multipartListingAction(r, action) + return listing != "" && boundary.CanDo(listing, bucket, objectKey) +} + // hasListAction reports whether the identity carries any List-scoped legacy // action (e.g. "List", "List:*", "List:prefix-*") or has administrative // privileges. Used to decide whether a ListBuckets request from an anonymous @@ -2323,6 +2364,9 @@ func (identity *Identity) isAdmin() bool { if identity == nil { return false } + if len(identity.permissionBoundary) > 0 && !slices.Contains(identity.permissionBoundary, s3_constants.ACTION_ADMIN) { + return false + } return slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) } @@ -3083,6 +3127,9 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide glog.V(3).Infof("VerifyActionPermission called with nil identity for action %s on %s/%s", action, bucket, object) return s3err.ErrAccessDenied } + if !identity.allowsPermissionBoundary(r, action, bucket, object) { + return s3err.ErrAccessDenied + } switch iam.authorizationRoute(r, identity) { case authorizeViaIAMIntegration: @@ -3101,17 +3148,18 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide // No matching statement: a native bare Admin grant survives // attaching a policy (issue #11226). Scoped actions are not // consulted because inline policies flatten lossily into Actions. - if identity.isAdmin() { + if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) { return s3err.ErrNone } return s3err.ErrAccessDenied } case authorizeViaLegacyActions: - if !identity.CanDo(action, bucket, object) { + grants := &Identity{Name: identity.Name, Actions: identity.Actions} + if !grants.CanDo(action, bucket, object) { // The multipart listing routes are gated on ACTION_READ, but a // grant may name the listing operation itself. listing := multipartListingAction(r, action) - if listing == "" || !identity.CanDo(listing, bucket, object) { + if listing == "" || !grants.CanDo(listing, bucket, object) { return s3err.ErrAccessDenied } } @@ -3132,7 +3180,7 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide func (iam *IdentityAccessManagement) canListBucketsFromOwnerIndex(r *http.Request, identity *Identity) (ok bool, granted []string) { // Fail closed on a nil identity: the scan path filters every bucket out // without dereferencing it, while the index path would need its name. - if identity == nil || identity.isAdmin() { + if identity == nil || identity.isAdmin() || len(identity.permissionBoundary) > 0 { return false, nil } @@ -3275,6 +3323,9 @@ func (iam *IdentityAccessManagement) authorizeObjectKeyAction(r *http.Request, i if identity == nil { return s3err.ErrAccessDenied } + if !identity.allowsPermissionBoundary(r, action, bucket, objectKey) { + return s3err.ErrAccessDenied + } if identity.isAdmin() { return s3err.ErrNone } @@ -3365,6 +3416,9 @@ func (iam *IdentityAccessManagement) AuthorizeObjectAclWrite(r *http.Request, id // authorizeWithIAM authorizes requests using the IAM integration policy engine func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode { + if !identity.allowsPermissionBoundary(r, action, bucket, object) { + return s3err.ErrAccessDenied + } ctx := r.Context() // The evaluation below consults the bucket-policy: mirror, so the @@ -3392,7 +3446,7 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity // an explicit Deny in an attached policy still wins. This runs before the // auth-path switch so an Admin identity without a session principal or // PrincipalArn is still authorized through its native grant. - if identity.isAdmin() { + if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) { s3Action, resourceArn := resolveS3AuthTarget(action, bucket, object, r) principal := buildPrincipalARN(identity, r) if !iam.isActionExplicitlyDeniedByIAM(r, identity, principal, s3Action, resourceArn) { diff --git a/weed/s3api/auth_credentials_upsert_test.go b/weed/s3api/auth_credentials_upsert_test.go index 9bf045c0c4..46336f64d4 100644 --- a/weed/s3api/auth_credentials_upsert_test.go +++ b/weed/s3api/auth_credentials_upsert_test.go @@ -3,12 +3,14 @@ package s3api import ( "context" "net/http" + "net/http/httptest" "strings" "sync" "sync/atomic" "testing" "time" + "github.com/gorilla/mux" "github.com/seaweedfs/seaweedfs/weed/credential" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine" @@ -438,3 +440,134 @@ func TestUpsertIdentityKeepsServiceAccountKeys(t *testing.T) { _, _, found = s3a.iam.LookupByAccessKey("AKPACS") assert.True(t, found) } + +func TestServiceAccountActionsLimitParent(t *testing.T) { + parent := &iam_pb.Identity{ + Name: "parent", + Credentials: []*iam_pb.Credential{{AccessKey: "AKPARENT", SecretKey: "parent-secret"}}, + Actions: []string{"Admin"}, + } + serviceAccount := &iam_pb.ServiceAccount{ + Id: "sa:parent:restricted", + ParentUser: "parent", + Actions: []string{"Read"}, + Credential: &iam_pb.Credential{AccessKey: "AKSERVICE", SecretKey: "service-secret", Status: "Active"}, + } + s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{parent}) + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{parent}, + ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount}, + })) + + writeRequest, err := http.NewRequest(http.MethodPut, "http://s3/bucket/object", nil) + require.NoError(t, err) + readRequest, err := http.NewRequest(http.MethodGet, "http://s3/bucket/object", nil) + require.NoError(t, err) + iamRequest, err := http.NewRequest(http.MethodPost, "http://iam/", nil) + require.NoError(t, err) + + assertPermissions := func() { + resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE") + require.True(t, found) + assert.Equal(t, "parent", resolved.Name) + assert.Equal(t, s3err.ErrAccessDenied, + s3a.iam.VerifyActionPermission(writeRequest, resolved, s3_constants.ACTION_WRITE, "bucket", "object")) + assert.Equal(t, s3err.ErrNone, + s3a.iam.VerifyActionPermission(readRequest, resolved, s3_constants.ACTION_READ, "bucket", "object")) + assert.Equal(t, s3err.ErrAccessDenied, + s3a.iam.AuthorizeIamAction(iamRequest, resolved, "CreateAccessKey", "parent")) + } + + assertPermissions() + + withPolicy := &iam_pb.Identity{ + Name: parent.Name, + Credentials: parent.Credentials, + Actions: parent.Actions, + PolicyNames: []string{"ListBucketsOnly"}, + } + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{withPolicy}, + ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount}, + Policies: []*iam_pb.Policy{{ + Name: "ListBucketsOnly", + Content: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}`, + }}, + })) + assertPermissions() + s3a.iam.SetIAMIntegration(NewS3IAMIntegration(newTestIAMManager(t), "")) + assertPermissions() + + ctx := context.Background() + require.NoError(t, s3a.iam.credentialManager.CreateServiceAccount(ctx, serviceAccount)) + pushed, err := s3a.iam.credentialManager.GetUser(ctx, "parent") + require.NoError(t, err) + require.NoError(t, s3a.iam.UpsertIdentity(pushed)) + assertPermissions() + + inherited := &iam_pb.ServiceAccount{ + Id: serviceAccount.Id, + ParentUser: serviceAccount.ParentUser, + Credential: serviceAccount.Credential, + } + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{parent}, + ServiceAccounts: []*iam_pb.ServiceAccount{inherited}, + })) + resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE") + require.True(t, found) + assert.Equal(t, s3err.ErrNone, + s3a.iam.VerifyActionPermission(writeRequest, resolved, s3_constants.ACTION_WRITE, "bucket", "object")) + + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{parent}, + ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount}, + })) + require.NoError(t, s3a.iam.MergeS3ApiConfiguration(&iam_pb.S3ApiConfiguration{}, false, true)) + _, _, found = s3a.iam.LookupByAccessKey("AKSERVICE") + assert.False(t, found) + + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{parent}, + ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount}, + })) + s3a.iam.RemoveIdentity("parent") + _, _, found = s3a.iam.LookupByAccessKey("AKSERVICE") + assert.False(t, found) +} + +func TestServiceAccountActionsAllowScopedUploadListing(t *testing.T) { + for _, parentAction := range []string{"Admin", "Read"} { + t.Run(parentAction, func(t *testing.T) { + testServiceAccountScopedUploadListing(t, parentAction) + }) + } +} + +func testServiceAccountScopedUploadListing(t *testing.T, parentAction string) { + parent := &iam_pb.Identity{ + Name: "parent", + Credentials: []*iam_pb.Credential{{AccessKey: "AKPARENT", SecretKey: "parent-secret"}}, + Actions: []string{parentAction}, + } + s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{parent}) + require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{ + Identities: []*iam_pb.Identity{parent}, + ServiceAccounts: []*iam_pb.ServiceAccount{{ + Id: "sa:parent:uploads", + ParentUser: "parent", + Actions: []string{"ListBucketMultipartUploads:demo"}, + Credential: &iam_pb.Credential{AccessKey: "AKSERVICE", SecretKey: "service-secret"}, + }}, + })) + resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE") + require.True(t, found) + + uploads := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/demo?uploads", nil), map[string]string{"bucket": "demo"}) + assert.Equal(t, s3err.ErrNone, s3a.iam.VerifyActionPermission(uploads, resolved, s3_constants.ACTION_READ, "demo", "")) + assert.Equal(t, s3err.ErrNone, s3a.iam.authorizeRequest(uploads, resolved, s3_constants.ACTION_READ)) + + get := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/demo/key", nil), map[string]string{"bucket": "demo", "object": "key"}) + assert.Equal(t, s3err.ErrAccessDenied, s3a.iam.VerifyActionPermission(get, resolved, s3_constants.ACTION_READ, "demo", "key")) + assert.Equal(t, s3err.ErrAccessDenied, s3a.iam.authorizeRequest(get, resolved, s3_constants.ACTION_READ)) +} diff --git a/weed/s3api/s3api_bucket_handlers.go b/weed/s3api/s3api_bucket_handlers.go index d69b4f857a..bf9f62bd7d 100644 --- a/weed/s3api/s3api_bucket_handlers.go +++ b/weed/s3api/s3api_bucket_handlers.go @@ -158,6 +158,9 @@ func (s3a *S3ApiServer) bucketVisibleToIdentity(r *http.Request, bucket, owner s if !s3a.iam.isEnabled() { return true } + if !identity.allowsPermissionBoundary(r, s3_constants.ACTION_LIST, bucket, "") { + return false + } if isBucketOwnedByIdentity(owner, identity) { return true } diff --git a/weed/s3api/s3api_embedded_iam.go b/weed/s3api/s3api_embedded_iam.go index 205824f0df..8c5611dcdc 100644 --- a/weed/s3api/s3api_embedded_iam.go +++ b/weed/s3api/s3api_embedded_iam.go @@ -2693,12 +2693,6 @@ func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identit if identity == nil || identity.Name == s3_constants.AccountAnonymousId { return s3err.ErrAccessDenied } - if !iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) { - return s3err.ErrNone - } - if identity.isAdmin() { - return s3err.ErrNone - } // Self-target actions authorize against the target identity's ARN. The // account segment stays empty so existing arn:aws:iam:::* wildcard // grants keep matching. @@ -2713,6 +2707,15 @@ func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identit } resource = fmt.Sprintf("arn:aws:iam:::user/%s", target) } + if !identity.allowsPermissionBoundary(r, Action("iam:"+action), resource, "") { + return s3err.ErrAccessDenied + } + if !iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) { + return s3err.ErrNone + } + if identity.isAdmin() { + return s3err.ErrNone + } return iam.VerifyActionPermission(r, identity, Action("iam:"+action), resource, "") } diff --git a/weed/s3api/s3api_sts.go b/weed/s3api/s3api_sts.go index 51e0c237b8..0bc950dffc 100644 --- a/weed/s3api/s3api_sts.go +++ b/weed/s3api/s3api_sts.go @@ -426,8 +426,8 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) { fmt.Errorf("user %s is not authorized to assume role %s", identity.Name, roleArn)) return } - if h.iam.isActionExplicitlyDeniedByIAM(r, identity, callerArn, sts.ActionAssumeRole, roleArn) { - glog.V(2).Infof("AssumeRole: identity policy explicitly denies %s assuming %s", identity.Name, roleArn) + if !identity.allowsPermissionBoundary(r, Action(sts.ActionAssumeRole), "", "") || h.iam.isActionExplicitlyDeniedByIAM(r, identity, callerArn, sts.ActionAssumeRole, roleArn) { + glog.V(2).Infof("AssumeRole: identity policy denies %s assuming %s", identity.Name, roleArn) h.writeSTSErrorResponse(w, r, STSErrAccessDenied, fmt.Errorf("user %s is not authorized to assume role %s", identity.Name, roleArn)) return @@ -437,7 +437,7 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) { // session ends up with an empty role name in its assumed-role ARN. roleArn = h.callerPrincipalArn(identity) glog.V(2).Infof("AssumeRole: no RoleArn provided, defaulting to caller identity: %s", roleArn) - if authErr := h.iam.VerifyActionPermission(r, identity, Action(sts.ActionAssumeRole), "", ""); authErr != s3err.ErrNone { + if len(identity.permissionBoundary) > 0 || h.iam.VerifyActionPermission(r, identity, Action(sts.ActionAssumeRole), "", "") != s3err.ErrNone { glog.Warningf("AssumeRole: caller %s attempted to assume role without RoleArn and lacks global sts:AssumeRole permission", identity.Name) h.writeSTSErrorResponse(w, r, STSErrAccessDenied, fmt.Errorf("access denied")) return @@ -722,7 +722,7 @@ func (h *STSHandlers) handleGetFederationToken(w http.ResponseWriter, r *http.Re glog.V(2).Infof("GetFederationToken: caller identity=%s, name=%s", identity.Name, name) // Check if the caller is authorized to call GetFederationToken - if authErr := h.iam.VerifyActionPermission(r, identity, Action(sts.ActionGetFederationToken), "", ""); authErr != s3err.ErrNone { + if len(identity.permissionBoundary) > 0 || h.iam.VerifyActionPermission(r, identity, Action(sts.ActionGetFederationToken), "", "") != s3err.ErrNone { glog.V(2).Infof("GetFederationToken: caller %s is not authorized to call GetFederationToken", identity.Name) h.writeSTSErrorResponse(w, r, STSErrAccessDenied, fmt.Errorf("user %s is not authorized to call GetFederationToken", identity.Name)) diff --git a/weed/s3api/s3api_sts_assume_role_authz_test.go b/weed/s3api/s3api_sts_assume_role_authz_test.go index c293f4d48f..a80ff4572d 100644 --- a/weed/s3api/s3api_sts_assume_role_authz_test.go +++ b/weed/s3api/s3api_sts_assume_role_authz_test.go @@ -58,7 +58,22 @@ func TestAssumeRole_NonAdminCallerAuthorizedByTrustPolicy(t *testing.T) { Actions: []string{"Read", "Write", "List", "Tagging"}, PolicyNames: []string{"DenyAssumeRole"}, }, + { + Name: "warehouse-admin", + Actions: []string{"Admin"}, + }, }, + ServiceAccounts: []*iam_pb.ServiceAccount{{ + Id: "sa:lakekeeper:readonly", + ParentUser: "lakekeeper", + Actions: []string{"Read"}, + Credential: &iam_pb.Credential{AccessKey: "lakekeeperreadkey", SecretKey: "lakekeeperreadsecret"}, + }, { + Id: "sa:warehouse-admin:sts", + ParentUser: "warehouse-admin", + Actions: []string{"Read", "sts:AssumeRole", "sts:GetFederationToken"}, + Credential: &iam_pb.Credential{AccessKey: "adminstskey", SecretKey: "adminstssecret"}, + }}, })) stsHandlers := NewSTSHandlers(manager.GetSTSService(), iam) @@ -173,6 +188,43 @@ func TestAssumeRole_NonAdminCallerAuthorizedByTrustPolicy(t *testing.T) { assert.Equal(t, http.StatusForbidden, rec.Code, "explicit identity-side deny must block AssumeRole even when the trust policy admits the caller") }) + t.Run("restricted service account cannot assume its parent's roles", func(t *testing.T) { + require.NoError(t, manager.CreateRole(ctx, "", "ParentWarehouse", &integration.RoleDefinition{ + RoleName: "ParentWarehouse", + TrustPolicy: &policy.PolicyDocument{ + Version: "2012-10-17", + Statement: []policy.Statement{{ + Effect: "Allow", + Principal: map[string]interface{}{"AWS": "arn:aws:iam::" + defaultAccountID + ":user/lakekeeper"}, + Action: []string{"sts:AssumeRole"}, + }}, + }, + AttachedPolicies: []string{"WarehouseAccess"}, + })) + rec := assume(t, accessKey, secretKey, "ParentWarehouse") + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + rec = assume(t, "lakekeeperreadkey", "lakekeeperreadsecret", "ParentWarehouse") + assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + }) + + t.Run("restricted service account cannot mint a session for its parent", func(t *testing.T) { + for _, action := range []string{"AssumeRole", "GetFederationToken"} { + body := url.Values{"Action": {action}, "Version": {"2011-06-15"}, "RoleSessionName": {"self"}, "Name": {"self"}}.Encode() + req, err := newTestRequest(http.MethodPost, "http://sts.seaweedfs.test/", int64(len(body)), strings.NewReader(body)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + require.NoError(t, signRequestV4(req, "adminstskey", "adminstssecret")) + rec := httptest.NewRecorder() + if action == "AssumeRole" { + stsHandlers.handleAssumeRole(rec, req) + } else { + stsHandlers.handleGetFederationToken(rec, req) + } + assert.Equal(t, http.StatusForbidden, rec.Code, "%s: %s", action, rec.Body.String()) + } + }) + t.Run("session policy explicit deny blocks role chaining", func(t *testing.T) { require.NoError(t, manager.CreateRole(ctx, "", "ChainWarehouse", &integration.RoleDefinition{ RoleName: "ChainWarehouse",