mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * sts: check the session role in the web identity role mapping test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7638cf2f66
commit
7da99cd760
4 files changed
+180
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user