From 7da99cd760bf5ecd018e1a371ec70988f95741be Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Wed, 25 Nov 2026 13:08:50 -0800 Subject: [PATCH] sts: honor the provider role mapping for web identity roles it names (#12982) * sts: honor the provider role mapping for web identity roles it names AssumeRoleWithWebIdentity only checked the role's trust policy, so with trust policies that allow the provider without claim conditions any token from that provider could assume any of its roles, including ones the provider's roleMapping assigns to other claim values. Bearer auth already uses the mapped roles. A role named by the mapping (a rule or the default role) is now issued only to tokens the mapping gives that role; roles the mapping does not name keep the trust-policy-only check. Co-Authored-By: Claude Opus 5.5 * sts: trim role mapping targets when checking which roles the mapping names Bearer auth trims mapped roles, so a padded target still assigns that role; without the trim the web identity check treated the role as unnamed and left it to the trust policy alone. Co-Authored-By: Claude Opus 5.5 * sts: compare the provider's mapped roles as a list, not a comma-split string The OIDC provider joins mapped roles with commas, and role names may contain commas, so splitting the joined attribute could match a piece of one mapped role against a different role, or miss the mapped role. Co-Authored-By: Claude Opus 5.5 * sts: check the session role in the web identity role mapping test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../web_identity_role_mapping_test.go | 136 ++++++++++++++++++ weed/iam/oidc/oidc_provider.go | 9 ++ weed/iam/providers/provider.go | 3 + weed/iam/sts/sts_service.go | 32 +++++ 4 files changed, 180 insertions(+) create mode 100644 weed/iam/integration/web_identity_role_mapping_test.go diff --git a/weed/iam/integration/web_identity_role_mapping_test.go b/weed/iam/integration/web_identity_role_mapping_test.go new file mode 100644 index 0000000000..7ccee80ba1 --- /dev/null +++ b/weed/iam/integration/web_identity_role_mapping_test.go @@ -0,0 +1,136 @@ +package integration + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/seaweedfs/seaweedfs/weed/iam/oidc" + "github.com/seaweedfs/seaweedfs/weed/iam/policy" + "github.com/seaweedfs/seaweedfs/weed/iam/providers" + "github.com/seaweedfs/seaweedfs/weed/iam/sts" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWebIdentityRoleMappingLimitsNamedRoles(t *testing.T) { + ctx := context.Background() + + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]interface{}{ + "keys": []map[string]interface{}{{ + "kty": "RSA", + "kid": "mapping-key", + "use": "sig", + "alg": "RS256", + "n": base64.RawURLEncoding.EncodeToString(key.PublicKey.N.Bytes()), + "e": "AQAB", + }}, + }) + })) + defer server.Close() + + provider := oidc.NewOIDCProvider("keycloak") + require.NoError(t, provider.Initialize(&oidc.OIDCConfig{ + Issuer: server.URL, + ClientID: "test-client", + JWKSUri: server.URL + "/jwks", + RoleMapping: &providers.RoleMapping{ + Rules: []providers.MappingRule{ + {Claim: "groups", Value: "admins", Role: "arn:aws:iam::role/AdminRole"}, + {Claim: "groups", Value: "readers", Role: "arn:aws:iam::role/ReadRole"}, + {Claim: "groups", Value: "auditors", Role: " arn:aws:iam::role/AuditRole "}, + {Claim: "groups", Value: "leads", Role: "arn:aws:iam::role/AdminRole,Lead"}, + }, + DefaultRole: "arn:aws:iam::role/GuestRole", + }, + })) + + iamManager := NewIAMManager() + require.NoError(t, iamManager.Initialize(&IAMConfig{ + STS: &sts.STSConfig{ + TokenDuration: sts.FlexibleDuration{Duration: time.Hour}, + MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour}, + Issuer: "test-sts", + SigningKey: []byte("test-signing-key-32-characters-long"), + }, + Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"}, + Roles: &RoleStoreConfig{StoreType: "memory"}, + }, func() string { return "localhost:8888" })) + require.NoError(t, iamManager.RegisterIdentityProvider(provider)) + + for _, roleName := range []string{"AdminRole", "ReadRole", "AuditRole", "AdminRole,Lead", "GuestRole", "UnmappedRole"} { + require.NoError(t, iamManager.CreateRole(ctx, "", roleName, &RoleDefinition{ + RoleName: roleName, + TrustPolicy: &policy.PolicyDocument{ + Version: "2012-10-17", + Statement: []policy.Statement{{ + Effect: "Allow", + Principal: map[string]interface{}{"Federated": "keycloak"}, + Action: []string{"sts:AssumeRoleWithWebIdentity"}, + }}, + }, + })) + } + + signJWT := func(groups ...string) string { + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + "iss": server.URL, + "sub": "mapping-user", + "aud": "test-client", + "exp": time.Now().Add(time.Hour).Unix(), + "iat": time.Now().Unix(), + "groups": groups, + }) + token.Header["kid"] = "mapping-key" + signed, err := token.SignedString(key) + require.NoError(t, err) + return signed + } + + tests := []struct { + groups []string + role string + allowed bool + }{ + {[]string{"readers"}, "AdminRole", false}, + {[]string{"readers"}, "GuestRole", false}, + {[]string{"readers"}, "ReadRole", true}, + {[]string{"readers"}, "UnmappedRole", true}, + {[]string{"admins"}, "AdminRole", true}, + {[]string{"admins", "readers"}, "ReadRole", true}, + {[]string{"readers"}, "AuditRole", false}, + {[]string{"auditors"}, "AuditRole", true}, + {[]string{"leads"}, "AdminRole", false}, + {[]string{"leads"}, "AdminRole,Lead", true}, + {[]string{"admins"}, "AdminRole,Lead", false}, + {nil, "GuestRole", true}, + {nil, "AdminRole", false}, + {nil, "ReadRole", false}, + } + for _, tc := range tests { + resp, err := iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{ + RoleArn: "arn:aws:iam::role/" + tc.role, + WebIdentityToken: signJWT(tc.groups...), + RoleSessionName: "mapping-check", + }) + if tc.allowed { + require.NoError(t, err, "groups %v assuming %s", tc.groups, tc.role) + session, err := iamManager.GetSTSService().ValidateSessionToken(ctx, resp.Credentials.SessionToken) + require.NoError(t, err) + assert.Equal(t, "arn:aws:iam::role/"+tc.role, session.RoleArn) + } else { + assert.Error(t, err, "groups %v assuming %s", tc.groups, tc.role) + assert.Nil(t, resp, "groups %v assuming %s", tc.groups, tc.role) + } + } +} diff --git a/weed/iam/oidc/oidc_provider.go b/weed/iam/oidc/oidc_provider.go index d2e29efc0a..3620005f4c 100644 --- a/weed/iam/oidc/oidc_provider.go +++ b/weed/iam/oidc/oidc_provider.go @@ -354,6 +354,14 @@ func (p *OIDCProvider) GetIssuer() string { return p.config.Issuer } +// GetRoleMapping returns the configured claim-to-role mapping, or nil +func (p *OIDCProvider) GetRoleMapping() *providers.RoleMapping { + if p.config == nil { + return nil + } + return p.config.RoleMapping +} + // Initialize initializes the OIDC provider with configuration func (p *OIDCProvider) Initialize(config interface{}) error { if config == nil { @@ -568,6 +576,7 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide Issuer: claims.Issuer, PrincipalTags: filterPrincipalTags(extractPrincipalTags(claims.Claims), p.config.AllowedPrincipalTagKeys), ClaimPolicies: extractClaimPolicies(claims.Claims, p.config.PolicyClaim), + MappedRoles: roles, } // Pass the token expiration to limit session duration diff --git a/weed/iam/providers/provider.go b/weed/iam/providers/provider.go index 8545907247..434bc08571 100644 --- a/weed/iam/providers/provider.go +++ b/weed/iam/providers/provider.go @@ -72,6 +72,9 @@ type ExternalIdentity struct { // policy mode or the claim was absent. ClaimPolicies []string `json:"claimPolicies,omitempty"` + // MappedRoles are the roles the provider's role mapping assigned. + MappedRoles []string `json:"mappedRoles,omitempty"` + // TokenExpiration is the expiration time of the source identity token // This is used to limit session duration to not exceed the token's exp claim TokenExpiration *time.Time `json:"tokenExpiration,omitempty"` diff --git a/weed/iam/sts/sts_service.go b/weed/iam/sts/sts_service.go index 81e7ea39f1..1857c5d9b4 100644 --- a/weed/iam/sts/sts_service.go +++ b/weed/iam/sts/sts_service.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "strconv" + "strings" "sync" "time" @@ -624,6 +625,9 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass // claim-mode the IDP is the sole authority for both authentication and // authorization, so there is no role definition to consult. if !claimMode { + if roleMappingRefuses(provider, request.RoleArn, externalIdentity) { + return nil, fmt.Errorf("role assumption denied: the provider's role mapping does not assign %s to this token", request.RoleArn) + } if err := s.validateRoleAssumptionForWebIdentity(ctx, request.RoleArn, request.WebIdentityToken, request.DurationSeconds); err != nil { return nil, fmt.Errorf("role assumption denied: %w", err) } @@ -1093,6 +1097,34 @@ func (s *STSService) extractIssuerFromJWT(token string) (string, error) { return issuer, nil } +// roleMappingRefuses reports whether the provider's role mapping names the +// role and did not map this identity to it, the role set Bearer auth uses. +// Roles the mapping does not name are left to the trust policy. +func roleMappingRefuses(provider providers.IdentityProvider, roleArn string, identity *providers.ExternalIdentity) bool { + p, ok := provider.(interface{ GetRoleMapping() *providers.RoleMapping }) + if !ok { + return false + } + mapping := p.GetRoleMapping() + roleName := utils.ExtractRoleNameFromArn(roleArn) + if mapping == nil || roleName == "" { + return false + } + named := utils.ExtractRoleNameFromArn(strings.TrimSpace(mapping.DefaultRole)) == roleName + for _, rule := range mapping.Rules { + named = named || utils.ExtractRoleNameFromArn(strings.TrimSpace(rule.Role)) == roleName + } + if !named { + return false + } + for _, mapped := range identity.MappedRoles { + if utils.ExtractRoleNameFromArn(strings.TrimSpace(mapped)) == roleName { + return false + } + } + return true +} + // validateRoleAssumptionForWebIdentity validates role assumption for web identity tokens // This method performs complete trust policy validation to prevent unauthorized role assumptions func (s *STSService) validateRoleAssumptionForWebIdentity(ctx context.Context, roleArn string, webIdentityToken string, durationSeconds *int64) error {