mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-25 14:30:43 +01:00
* iam/oidc: reject reused jti claims with a bounded replay cache * iam/sts: pass jti replay settings through convertToOIDCConfig * iam/oidc: keep consumed jtis and stop the cleanup worker across re-init Re-initializing a provider reset the JTI store, so an already-used token could be presented again after a config refresh; the store is now allocated once and survives Initialize. The cleanup worker is stopped on every re-init (previously only when protection stayed enabled), is started only after the rest of Initialize has succeeded, and Shutdown no longer consumes a permanent sync.Once, so a re-initialized worker can be stopped again. * iam/oidc: enforce the jti replay cache bound for every token Tokens without a usable jti claim skipped the cache entirely and stayed reusable; they are now keyed by the token's own fingerprint so a repeat presentation is still a replay. Tokens without exp previously failed as expired on first use; their entry now gets a bounded retention. The replay test-and-set now runs before any capacity work so replayed tokens cannot each trigger a full-cache scan, the entry count is incremented as part of the insert so concurrent validations cannot overshoot the bound, and a guaranteed serialized sweep runs before a capacity rejection while opportunistic sweeps are rate limited and confined to one at a time. Raw token identifiers are no longer written to logs or errors, a stable fingerprint is logged instead. * iam/sts: shut down providers dropped by the managed-provider swap Each managed OIDC provider runs a background JTI cleanup worker, but SetIAMManagedOIDCProviders replaced the provider map without stopping the old providers, so every refresh leaked goroutines. Providers absent from the new map are now shut down; providers that stay keep running. * iam/integration: reuse providers across refreshes for unchanged records Every refresh rebuilt providers from their records, so a refreshed provider forgot the JTIs it had already consumed and an already-used token could be presented again. Records are now fingerprinted and an unchanged record reuses its provider, keeping the consumed-token cache; changed records are rebuilt, removed records are dropped, and the swap in STS releases the workers of whatever is no longer referenced. * iam/oidc: consume replay entries only on the single-use exchange path Bearer authentication validates the same token on every request, so consuming it in shared ValidateToken/Authenticate made every token single-use and rejected all but the first request. The replay check now runs only for the STS exchange via AuthenticateSingleUse; bearer paths validate without consuming. A token without exp also no longer gets a bounded replay entry that ages out while the token stays valid: its entry is kept until the capacity bound evicts it, so it can never become usable again. * iam/oidc: keep the mock provider on the mock path for single-use calls * iam/oidc: require exp on single-use tokens A cache slot frees only by expiry, so an expiry-less entry would hold it forever; a burst of distinct tokens could exhaust the bound permanently and block every later exchange. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: give each web-identity test token a unique jti Subtests minted tokens with identical claims inside one second, so the exchange saw the same token fingerprint twice and the second call read as a replay. Each exchange now carries its own jti. * iam/oidc: carry the consumed-token replay store across provider rebuilds A record change rebuilds the managed provider with a fresh JTI store, so a token consumed before the rebuild could be presented again until it expired. The new provider adopts the replaced provider's replay store before it is published, and the replaced provider is shut down so only one cleanup worker sweeps the shared store. * iam/oidc: stop the cleanup worker of providers dropped from the store A refresh removed the provider object from the managed cache but left its JTI cleanup goroutine running for the life of the process. * iam/oidc: merge a provider's consumed replay entries into another's store MergeReplayStateFrom folds one provider's consumed-token entries into another's, skipping already-expired ones. Unlike AdoptReplayStateFrom it swaps no pointers, so it is safe on a provider still serving validators. * iam/integration: share one provider and replay store across identical issuer records Records for the same issuer URL with identical validation settings now reuse a single provider, so a token consumed through one account's record is rejected through the other's — previously each record owned a separate jti store and a spent token could be replayed cross-account. A superseded provider's consumed entries merge into the shared store so no rejection is lost, and a removed or rebuilt provider is only shut down once no remaining record references it. * iam/oidc: hand the superseded provider's live replay store to the shared one * iam/oidc: carry merged replay entries without charging the capacity bound * iam/oidc: key the jti-less replay fingerprint on the signed input Hashing the whole token lets ECDSA signature malleability (s -> N-s) mint a second cache key for identical claims, so a consumed token could be replayed for another exchange. Key the fallback on header.payload instead. * iam/oidc: publish the jti cache bound before the enabled flag Initialize stored jtiEnabled ahead of jtiMaxSize, so a provider flipped from disabled to enabled exposed enabled=true with a zero bound for a window; a single-use validation landing there would compute newCount > maxSize and reject with "JTI cache capacity exceeded". Store the bound first so the flag is the last thing published. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
320 lines
9.2 KiB
Go
320 lines
9.2 KiB
Go
package sts
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/iam/ldap"
|
|
"github.com/seaweedfs/seaweedfs/weed/iam/oidc"
|
|
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
|
)
|
|
|
|
// ProviderFactory creates identity providers from configuration
|
|
type ProviderFactory struct{}
|
|
|
|
// NewProviderFactory creates a new provider factory
|
|
func NewProviderFactory() *ProviderFactory {
|
|
return &ProviderFactory{}
|
|
}
|
|
|
|
// CreateProvider creates an identity provider from configuration
|
|
func (f *ProviderFactory) CreateProvider(config *ProviderConfig) (providers.IdentityProvider, error) {
|
|
if config == nil {
|
|
return nil, fmt.Errorf(ErrConfigCannotBeNil)
|
|
}
|
|
|
|
if config.Name == "" {
|
|
return nil, fmt.Errorf(ErrProviderNameEmpty)
|
|
}
|
|
|
|
if config.Type == "" {
|
|
return nil, fmt.Errorf(ErrProviderTypeEmpty)
|
|
}
|
|
|
|
if !config.Enabled {
|
|
glog.V(2).Infof("Provider %s is disabled, skipping", config.Name)
|
|
return nil, nil
|
|
}
|
|
|
|
glog.V(2).Infof("Creating provider: name=%s, type=%s", config.Name, config.Type)
|
|
|
|
switch config.Type {
|
|
case ProviderTypeOIDC:
|
|
return f.createOIDCProvider(config)
|
|
case ProviderTypeLDAP:
|
|
return f.createLDAPProvider(config)
|
|
case ProviderTypeSAML:
|
|
return f.createSAMLProvider(config)
|
|
default:
|
|
return nil, fmt.Errorf(ErrUnsupportedProviderType, config.Type)
|
|
}
|
|
}
|
|
|
|
// createOIDCProvider creates an OIDC provider from configuration
|
|
func (f *ProviderFactory) createOIDCProvider(config *ProviderConfig) (providers.IdentityProvider, error) {
|
|
oidcConfig, err := f.convertToOIDCConfig(config.Config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to convert OIDC config: %w", err)
|
|
}
|
|
|
|
provider := oidc.NewOIDCProvider(config.Name)
|
|
if err := provider.Initialize(oidcConfig); err != nil {
|
|
return nil, fmt.Errorf("failed to initialize OIDC provider: %w", err)
|
|
}
|
|
|
|
return provider, nil
|
|
}
|
|
|
|
// createLDAPProvider creates an LDAP provider from configuration
|
|
func (f *ProviderFactory) createLDAPProvider(config *ProviderConfig) (providers.IdentityProvider, error) {
|
|
provider := ldap.NewLDAPProvider(config.Name)
|
|
if err := provider.Initialize(config.Config); err != nil {
|
|
return nil, fmt.Errorf("failed to initialize LDAP provider: %w", err)
|
|
}
|
|
return provider, nil
|
|
}
|
|
|
|
// createSAMLProvider creates a SAML provider from configuration
|
|
func (f *ProviderFactory) createSAMLProvider(config *ProviderConfig) (providers.IdentityProvider, error) {
|
|
// TODO: Implement SAML provider when available
|
|
return nil, fmt.Errorf("SAML provider not implemented yet")
|
|
}
|
|
|
|
// convertToOIDCConfig converts generic config map to OIDC config struct
|
|
func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{}) (*oidc.OIDCConfig, error) {
|
|
config := &oidc.OIDCConfig{}
|
|
|
|
// Required fields
|
|
if issuer, ok := configMap[ConfigFieldIssuer].(string); ok {
|
|
config.Issuer = issuer
|
|
} else {
|
|
return nil, fmt.Errorf(ErrIssuerRequired)
|
|
}
|
|
|
|
clientIDPresent := false
|
|
if clientID, ok := configMap[ConfigFieldClientID].(string); ok && clientID != "" {
|
|
config.ClientID = clientID
|
|
clientIDPresent = true
|
|
}
|
|
// Accept the AWS-compatible plural form. Either field satisfies the
|
|
// "at least one client id" requirement; both can be set together.
|
|
if rawList, ok := configMap[ConfigFieldClientIDs]; ok {
|
|
if list, err := f.convertToStringSlice(rawList); err == nil && len(list) > 0 {
|
|
config.ClientIDs = list
|
|
clientIDPresent = true
|
|
}
|
|
}
|
|
if !clientIDPresent {
|
|
return nil, fmt.Errorf(ErrClientIDRequired)
|
|
}
|
|
|
|
// Optional fields
|
|
if clientSecret, ok := configMap[ConfigFieldClientSecret].(string); ok {
|
|
config.ClientSecret = clientSecret
|
|
}
|
|
|
|
if jwksUri, ok := configMap[ConfigFieldJWKSUri].(string); ok {
|
|
config.JWKSUri = jwksUri
|
|
}
|
|
|
|
if userInfoUri, ok := configMap[ConfigFieldUserInfoUri].(string); ok {
|
|
config.UserInfoUri = userInfoUri
|
|
}
|
|
|
|
// Convert scopes array
|
|
if scopesInterface, ok := configMap[ConfigFieldScopes]; ok {
|
|
scopes, err := f.convertToStringSlice(scopesInterface)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to convert scopes: %w", err)
|
|
}
|
|
config.Scopes = scopes
|
|
}
|
|
|
|
if tlsCaCert, ok := configMap[ConfigFieldTLSCACert].(string); ok {
|
|
config.TLSCACert = tlsCaCert
|
|
}
|
|
|
|
if rawThumbprints, ok := configMap[ConfigFieldThumbprints]; ok {
|
|
if list, err := f.convertToStringSlice(rawThumbprints); err == nil {
|
|
config.Thumbprints = list
|
|
}
|
|
}
|
|
|
|
if rawAllowed, ok := configMap[ConfigFieldAllowedPrincipalTagKeys]; ok {
|
|
if list, err := f.convertToStringSlice(rawAllowed); err == nil {
|
|
config.AllowedPrincipalTagKeys = list
|
|
}
|
|
}
|
|
|
|
if policyClaim, ok := configMap[ConfigFieldPolicyClaim].(string); ok {
|
|
config.PolicyClaim = policyClaim
|
|
}
|
|
|
|
if tlsInsecureSkipVerify, ok := configMap[ConfigFieldTLSInsecureSkipVerify].(bool); ok {
|
|
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
|
}
|
|
|
|
if enabled, ok := configMap[ConfigFieldJTIReplayProtectionEnabled].(bool); ok {
|
|
config.JTIReplayProtectionEnabled = &enabled
|
|
}
|
|
|
|
switch maxSize := configMap[ConfigFieldJTICacheMaxSize].(type) {
|
|
case float64:
|
|
config.JTICacheMaxSize = int(maxSize)
|
|
case int:
|
|
config.JTICacheMaxSize = maxSize
|
|
case json.Number:
|
|
if n, err := maxSize.Int64(); err == nil {
|
|
config.JTICacheMaxSize = int(n)
|
|
}
|
|
}
|
|
|
|
// Convert claims mapping
|
|
if claimsMapInterface, ok := configMap["claimsMapping"]; ok {
|
|
claimsMap, err := f.convertToStringMap(claimsMapInterface)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to convert claimsMapping: %w", err)
|
|
}
|
|
config.ClaimsMapping = claimsMap
|
|
}
|
|
|
|
// Convert role mapping
|
|
if roleMappingInterface, ok := configMap["roleMapping"]; ok {
|
|
roleMapping, err := f.convertToRoleMapping(roleMappingInterface)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to convert roleMapping: %w", err)
|
|
}
|
|
config.RoleMapping = roleMapping
|
|
}
|
|
|
|
glog.V(3).Infof("Converted OIDC config: issuer=%s, clientId=%s, jwksUri=%s",
|
|
config.Issuer, config.ClientID, config.JWKSUri)
|
|
|
|
return config, nil
|
|
}
|
|
|
|
// convertToStringSlice converts interface{} to []string
|
|
func (f *ProviderFactory) convertToStringSlice(value interface{}) ([]string, error) {
|
|
switch v := value.(type) {
|
|
case []string:
|
|
return v, nil
|
|
case []interface{}:
|
|
result := make([]string, len(v))
|
|
for i, item := range v {
|
|
if str, ok := item.(string); ok {
|
|
result[i] = str
|
|
} else {
|
|
return nil, fmt.Errorf("non-string item in slice: %v", item)
|
|
}
|
|
}
|
|
return result, nil
|
|
default:
|
|
return nil, fmt.Errorf("cannot convert %T to []string", value)
|
|
}
|
|
}
|
|
|
|
// convertToStringMap converts interface{} to map[string]string
|
|
func (f *ProviderFactory) convertToStringMap(value interface{}) (map[string]string, error) {
|
|
switch v := value.(type) {
|
|
case map[string]string:
|
|
return v, nil
|
|
case map[string]interface{}:
|
|
result := make(map[string]string)
|
|
for key, val := range v {
|
|
if str, ok := val.(string); ok {
|
|
result[key] = str
|
|
} else {
|
|
return nil, fmt.Errorf("non-string value for key %s: %v", key, val)
|
|
}
|
|
}
|
|
return result, nil
|
|
default:
|
|
return nil, fmt.Errorf("cannot convert %T to map[string]string", value)
|
|
}
|
|
}
|
|
|
|
// LoadProvidersFromConfig creates providers from configuration
|
|
func (f *ProviderFactory) LoadProvidersFromConfig(configs []*ProviderConfig) (map[string]providers.IdentityProvider, error) {
|
|
providersMap := make(map[string]providers.IdentityProvider)
|
|
|
|
for _, config := range configs {
|
|
if config == nil {
|
|
glog.V(1).Infof("Skipping nil provider config")
|
|
continue
|
|
}
|
|
|
|
glog.V(2).Infof("Loading provider: %s (type: %s, enabled: %t)",
|
|
config.Name, config.Type, config.Enabled)
|
|
|
|
if !config.Enabled {
|
|
glog.V(2).Infof("Provider %s is disabled, skipping", config.Name)
|
|
continue
|
|
}
|
|
|
|
provider, err := f.CreateProvider(config)
|
|
if err != nil {
|
|
glog.Errorf("Failed to create provider %s: %v", config.Name, err)
|
|
return nil, fmt.Errorf("failed to create provider %s: %w", config.Name, err)
|
|
}
|
|
|
|
if provider != nil {
|
|
providersMap[config.Name] = provider
|
|
glog.V(1).Infof("Successfully loaded provider: %s", config.Name)
|
|
}
|
|
}
|
|
|
|
glog.V(1).Infof("Loaded %d identity providers from configuration", len(providersMap))
|
|
return providersMap, nil
|
|
}
|
|
|
|
// convertToRoleMapping converts interface{} to *providers.RoleMapping
|
|
func (f *ProviderFactory) convertToRoleMapping(value interface{}) (*providers.RoleMapping, error) {
|
|
roleMappingMap, ok := value.(map[string]interface{})
|
|
if !ok {
|
|
return nil, fmt.Errorf("roleMapping must be an object")
|
|
}
|
|
|
|
roleMapping := &providers.RoleMapping{}
|
|
|
|
// Convert rules
|
|
if rulesInterface, ok := roleMappingMap["rules"]; ok {
|
|
rulesSlice, ok := rulesInterface.([]interface{})
|
|
if !ok {
|
|
return nil, fmt.Errorf("rules must be an array")
|
|
}
|
|
|
|
rules := make([]providers.MappingRule, len(rulesSlice))
|
|
for i, ruleInterface := range rulesSlice {
|
|
ruleMap, ok := ruleInterface.(map[string]interface{})
|
|
if !ok {
|
|
return nil, fmt.Errorf("rule must be an object")
|
|
}
|
|
|
|
rule := providers.MappingRule{}
|
|
if claim, ok := ruleMap["claim"].(string); ok {
|
|
rule.Claim = claim
|
|
}
|
|
if value, ok := ruleMap["value"].(string); ok {
|
|
rule.Value = value
|
|
}
|
|
if role, ok := ruleMap["role"].(string); ok {
|
|
rule.Role = role
|
|
}
|
|
if condition, ok := ruleMap["condition"].(string); ok {
|
|
rule.Condition = condition
|
|
}
|
|
|
|
rules[i] = rule
|
|
}
|
|
roleMapping.Rules = rules
|
|
}
|
|
|
|
// Convert default role
|
|
if defaultRole, ok := roleMappingMap["defaultRole"].(string); ok {
|
|
roleMapping.DefaultRole = defaultRole
|
|
}
|
|
|
|
return roleMapping, nil
|
|
}
|