snapshot of https://github.com/seaweedfs/seaweedfs.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
go: build dev binaries / cleanup (push) Successful in 4s
Codespell / Check for spelling errors (push) Failing after 3s
docker: build dev containers / build-rust-binaries (amd64, x86_64-unknown-linux-musl) (push) Failing after 3s
docker: build dev containers / build-dev-containers (push) Has been skipped
docker: build dev containers / build-rust-binaries (arm64, true, aarch64-unknown-linux-musl) (push) Failing after 3s
End to End / FUSE Mount (push) Failing after 2s
EC Integration Tests / EC Integration Tests (push) Failing after 30s
FUSE DLM Integration Tests / FUSE DLM Integration Tests (push) Failing after 3s
FUSE Volume Server Failover Tests / FUSE Volume Server Failover (push) Failing after 3s
FUSE Integration Tests / FUSE Integration Testing (push) Failing after 2s
FUSE P2P Peer Chunk Sharing Integration Tests / FUSE P2P Peer Chunk Sharing (push) Failing after 3s
go: build binary / Go Vet (push) Failing after 2s
go: build binary / Go Vet 32-bit (push) Failing after 3s
go: build binary / Build (push) Failing after 4s
go: build binary / Build cross-platform (freebsd/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (darwin/arm64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/arm64) (push) Failing after 3s
go: build binary / Test (push) Failing after 2s
go: build binary / Test 32-bit (push) Failing after 3s
helm: lint and test charts / lint-test (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (11) (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (17) (push) Failing after 3s
go: build dev binaries / build_dev_linux_windows (amd64, linux) (push) Failing after 2s
go: build dev binaries / build_dev_linux_windows (amd64, windows) (push) Failing after 3s
go: build dev binaries / build_dev_darwin (amd64, darwin) (push) Has been skipped
go: build dev binaries / build_dev_darwin (arm64, darwin) (push) Has been skipped
Java Client Unit Tests / Java Unit Tests (11) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (17) (push) Failing after 2s
Java Client Unit Tests / Java Unit Tests (21) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (8) (push) Failing after 3s
Kafka Quick Test (Load Test with Schema Registry) / Kafka Client Load Test (Quick) (push) Failing after 3s
Kafka Gateway Tests / Kafka Unit Tests (unit-tests-1) (push) Failing after 11s
Kafka Gateway Tests / Kafka Integration Tests (Critical) (integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka End-to-End Tests (with SMQ) (e2e-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Consumer Group Tests (Highly Isolated) (consumer-group-1) (push) Failing after 2s
Kafka Gateway Tests / Kafka Client Compatibility (with SMQ) (client-compat-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka SMQ Integration Tests (Full Stack) (smq-integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Protocol Tests (Isolated) (protocol-1) (push) Failing after 3s
KMS Tests / KMS Provider Integration Tests (push) Failing after 2s
KMS Tests / S3 KMS End-to-End Tests (push) Failing after 3s
Master Cold Start Tests / Master Cold Start Tests (push) Failing after 4s
Metadata Subscribe Integration Tests / Metadata Subscribe Integration Tests (push) Failing after 3s
Multi-Master Tests / Multi-Master Failover Tests (push) Failing after 3s
Performance / CPU and Heap Profile (push) Failing after 2s
Performance / S3 Read/Write Benchmark (rust volume) (push) Failing after 3s
pjdfstest POSIX Compliance / pjdfstest (push) Failing after 2s
Plugin Worker Integration Tests / Plugin Worker: erasure_coding (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: vacuum (push) Failing after 3s
Rust Volume Server Tests / Rust Integration Tests (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 1) (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 1) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 3) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Distributed Tests (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Performance Tests (push) Failing after 3s
Performance / Throughput Benchmark (go volume) (push) Failing after 3s
Performance / Throughput Benchmark (rust volume) (push) Failing after 2s
Performance / S3 Read/Write Benchmark (go volume) (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: volume_balance (push) Failing after 3s
PostgreSQL Gateway Tests / PostgreSQL Basic Tests (push) Failing after 3s
Rust Volume Server Tests / Rust Unit Tests (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 3) (push) Failing after 3s
Rust Plugin Worker Tests / Rust Plugin Worker Build and Unit Tests (push) Failing after 3s
rust: build dev volume server binaries / cleanup (push) Successful in 3s
S3 ETag and ACL Tests / S3 ETag + ACL Integration Tests (push) Failing after 3s
S3 IAM Integration Tests / IAM Unit Tests (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (advanced) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (basic) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (group) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (policy-enforcement) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (sts) (push) Failing after 4s
S3 Keycloak Integration Tests / S3 Keycloak Integration Tests (push) Failing after 3s
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.11) (push) Failing after 3s
S3 PyArrow Parquet Tests / Go Unit Tests (Implicit Directory) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.12) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-amd64, x86_64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-arm64, aarch64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-linux (linux-amd64, x86_64-unknown-linux-gnu) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.9) (push) Has been cancelled
S3 Proxy Signature Tests / S3 Proxy Signature Verification Tests (push) Has been cancelled
S3 SDK V2 Route Disambiguation Tests / S3 SDK V2 Routing Tests (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (quick) (push) Has been cancelled
S3 SSE Tests / S3 SSE Compatibility Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Metadata Persistence Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Copy Operations Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Multipart Upload Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Performance Test (push) Has been cancelled
S3 SSE Tests / S3 Volume Encryption Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (comprehensive) (push) Has been cancelled
Spark Integration Tests / Spark Integration Tests (push) Failing after 2s
Telemetry Integration Tests / telemetry-integration-test (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 1) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 1) (push) Failing after 3s
Ceph S3 tests / Basic S3 tests (KV store) (push) Has been cancelled
Ceph S3 tests / S3 Versioning & Object Lock tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Unit Tests (push) Failing after 3s
Ceph S3 tests / S3 CORS tests (push) Has been cancelled
Ceph S3 tests / SeaweedFS Custom S3 Copy tests (push) Has been cancelled
Ceph S3 tests / Basic S3 tests (SQL store) (push) Has been cancelled
test s3 over https using aws-cli / awscli-tests (push) Has been cancelled
TLS Rotation Integration Tests / TLS Rotation Integration Tests (push) Has been cancelled
Vacuum Integration Tests / Vacuum Integration Tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Variables Integration Tests (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (advanced-policy) (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (basic-policy) (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (contextual-policy) (push) Failing after 4s
S3 Policy Integration Tests / Trusted Proxy Detection Tests (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Shell Integration Tests (push) Failing after 3s
Samba on FUSE Integration / samba-integration (push) Failing after 2s
SFTP Integration Tests / SFTP Integration Testing (push) Failing after 3s
terraform: validate and test modules / fmt, validate, plan-level tests (push) Failing after 3s
terraform: validate and test modules / local cluster smoke test (real weed) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 3) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 2) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 2) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 3) (push) Failing after 5s
mount: windows conformance / WinFsp conformance (push) Has been cancelled
mount: windows / Mount on Windows (push) Has been cancelled

This commit is contained in:
upstream-mirror
2026-09-16 03:23:42 +05:00
commit 89f5be005d
3997 changed files with 961970 additions and 0 deletions

View File

@@ -0,0 +1,219 @@
// This file contains mock OIDC provider implementations for testing only.
// These should NOT be used in production environments.
package oidc
import (
"context"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
)
// MockOIDCProvider is a mock implementation for testing
type MockOIDCProvider struct {
*OIDCProvider
TestTokens map[string]*providers.TokenClaims
TestUsers map[string]*providers.ExternalIdentity
}
// NewMockOIDCProvider creates a mock OIDC provider for testing
func NewMockOIDCProvider(name string) *MockOIDCProvider {
return &MockOIDCProvider{
OIDCProvider: NewOIDCProvider(name),
TestTokens: make(map[string]*providers.TokenClaims),
TestUsers: make(map[string]*providers.ExternalIdentity),
}
}
// AddTestToken adds a test token with expected claims
func (m *MockOIDCProvider) AddTestToken(token string, claims *providers.TokenClaims) {
m.TestTokens[token] = claims
}
// AddTestUser adds a test user with expected identity
func (m *MockOIDCProvider) AddTestUser(userID string, identity *providers.ExternalIdentity) {
m.TestUsers[userID] = identity
}
// Authenticate overrides the parent Authenticate method to use mock data
func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if token == "" {
return nil, fmt.Errorf("token cannot be empty")
}
// Validate token using mock validation
claims, err := m.ValidateToken(ctx, token)
if err != nil {
return nil, err
}
// Map claims to external identity
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
rawRoles, _ := claims.GetClaimStringSlice("roles")
identity := &providers.ExternalIdentity{
UserID: claims.Subject,
Email: email,
DisplayName: displayName,
Groups: groups,
Roles: rawRoles,
Provider: m.name,
}
if !claims.ExpiresAt.IsZero() {
identity.TokenExpiration = &claims.ExpiresAt
}
return identity, nil
}
// ValidateToken validates tokens using test data
func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if token == "" {
return nil, fmt.Errorf("token cannot be empty")
}
// Special test tokens
if token == "expired_token" {
return nil, fmt.Errorf("token has expired")
}
if token == "invalid_token" {
return nil, fmt.Errorf("invalid token")
}
// Try to parse as JWT token first
if len(token) > 20 && strings.Count(token, ".") >= 2 {
parsedToken, _, err := new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{})
if err == nil {
if jwtClaims, ok := parsedToken.Claims.(jwt.MapClaims); ok {
issuer, _ := jwtClaims["iss"].(string)
subject, _ := jwtClaims["sub"].(string)
audience, _ := jwtClaims["aud"].(string)
// Verify the issuer matches our configuration
if issuer == m.config.Issuer && subject != "" {
// Extract expiration and issued at times
var expiresAt, issuedAt time.Time
if exp, ok := jwtClaims["exp"].(float64); ok {
expiresAt = time.Unix(int64(exp), 0)
}
if iat, ok := jwtClaims["iat"].(float64); ok {
issuedAt = time.Unix(int64(iat), 0)
}
// Carry the token's claims through like the real provider, keeping
// the synthesized defaults for tests that rely on them
claimsMap := make(map[string]interface{}, len(jwtClaims)+2)
for k, v := range jwtClaims {
claimsMap[k] = v
}
if _, ok := claimsMap["email"]; !ok {
claimsMap["email"] = subject + "@test-domain.com"
}
if _, ok := claimsMap["name"]; !ok {
claimsMap["name"] = "Test User " + subject
}
return &providers.TokenClaims{
Subject: subject,
Issuer: issuer,
Audience: audience,
ExpiresAt: expiresAt,
IssuedAt: issuedAt,
Claims: claimsMap,
}, nil
}
}
}
}
// Check test tokens
if claims, exists := m.TestTokens[token]; exists {
return claims, nil
}
// Default test token for basic testing
if token == "valid_test_token" {
return &providers.TokenClaims{
Subject: "test-user-id",
Issuer: m.config.Issuer,
Audience: m.config.ClientID,
ExpiresAt: time.Now().Add(time.Hour),
IssuedAt: time.Now(),
Claims: map[string]interface{}{
"email": "test@example.com",
"name": "Test User",
"groups": []string{"developers", "users"},
},
}, nil
}
return nil, fmt.Errorf("unknown test token: %s", token)
}
// GetUserInfo returns test user info
func (m *MockOIDCProvider) GetUserInfo(ctx context.Context, userID string) (*providers.ExternalIdentity, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if userID == "" {
return nil, fmt.Errorf("user ID cannot be empty")
}
// Check test users
if identity, exists := m.TestUsers[userID]; exists {
return identity, nil
}
// Default test user
return &providers.ExternalIdentity{
UserID: userID,
Email: userID + "@example.com",
DisplayName: "Test User " + userID,
Provider: m.name,
}, nil
}
// SetupDefaultTestData configures common test data
func (m *MockOIDCProvider) SetupDefaultTestData() {
// Create default token claims
defaultClaims := &providers.TokenClaims{
Subject: "test-user-123",
Issuer: "https://test-issuer.com",
Audience: "test-client-id",
ExpiresAt: time.Now().Add(time.Hour),
IssuedAt: time.Now(),
Claims: map[string]interface{}{
"email": "testuser@example.com",
"name": "Test User",
"groups": []string{"developers"},
},
}
// Add multiple token variants for compatibility
m.AddTestToken("valid_token", defaultClaims)
m.AddTestToken("valid-oidc-token", defaultClaims) // For integration tests
m.AddTestToken("valid_test_token", defaultClaims) // For STS tests
// Add default test users
m.AddTestUser("test-user-123", &providers.ExternalIdentity{
UserID: "test-user-123",
Email: "testuser@example.com",
DisplayName: "Test User",
Groups: []string{"developers"},
Provider: m.name,
})
}

View File

@@ -0,0 +1,202 @@
//go:build test
package oidc
import (
"context"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
)
// MockOIDCProvider is a mock implementation for testing
type MockOIDCProvider struct {
*OIDCProvider
TestTokens map[string]*providers.TokenClaims
TestUsers map[string]*providers.ExternalIdentity
}
// NewMockOIDCProvider creates a mock OIDC provider for testing
func NewMockOIDCProvider(name string) *MockOIDCProvider {
return &MockOIDCProvider{
OIDCProvider: NewOIDCProvider(name),
TestTokens: make(map[string]*providers.TokenClaims),
TestUsers: make(map[string]*providers.ExternalIdentity),
}
}
// AddTestToken adds a test token with expected claims
func (m *MockOIDCProvider) AddTestToken(token string, claims *providers.TokenClaims) {
m.TestTokens[token] = claims
}
// AddTestUser adds a test user with expected identity
func (m *MockOIDCProvider) AddTestUser(userID string, identity *providers.ExternalIdentity) {
m.TestUsers[userID] = identity
}
// Authenticate overrides the parent Authenticate method to use mock data
func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if token == "" {
return nil, fmt.Errorf("token cannot be empty")
}
// Validate token using mock validation
claims, err := m.ValidateToken(ctx, token)
if err != nil {
return nil, err
}
// Map claims to external identity
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
return &providers.ExternalIdentity{
UserID: claims.Subject,
Email: email,
DisplayName: displayName,
Groups: groups,
Provider: m.name,
}, nil
}
// ValidateToken validates tokens using test data
func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if token == "" {
return nil, fmt.Errorf("token cannot be empty")
}
// Special test tokens
if token == "expired_token" {
return nil, fmt.Errorf("token has expired")
}
if token == "invalid_token" {
return nil, fmt.Errorf("invalid token")
}
// Try to parse as JWT token first
if len(token) > 20 && strings.Count(token, ".") >= 2 {
parsedToken, _, err := new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{})
if err == nil {
if jwtClaims, ok := parsedToken.Claims.(jwt.MapClaims); ok {
issuer, _ := jwtClaims["iss"].(string)
subject, _ := jwtClaims["sub"].(string)
audience, _ := jwtClaims["aud"].(string)
// Verify the issuer matches our configuration
if issuer == m.config.Issuer && subject != "" {
// Extract expiration and issued at times
var expiresAt, issuedAt time.Time
if exp, ok := jwtClaims["exp"].(float64); ok {
expiresAt = time.Unix(int64(exp), 0)
}
if iat, ok := jwtClaims["iat"].(float64); ok {
issuedAt = time.Unix(int64(iat), 0)
}
return &providers.TokenClaims{
Subject: subject,
Issuer: issuer,
Audience: audience,
ExpiresAt: expiresAt,
IssuedAt: issuedAt,
Claims: map[string]interface{}{
"email": subject + "@test-domain.com",
"name": "Test User " + subject,
},
}, nil
}
}
}
}
// Check test tokens
if claims, exists := m.TestTokens[token]; exists {
return claims, nil
}
// Default test token for basic testing
if token == "valid_test_token" {
return &providers.TokenClaims{
Subject: "test-user-id",
Issuer: m.config.Issuer,
Audience: m.config.ClientID,
ExpiresAt: time.Now().Add(time.Hour),
IssuedAt: time.Now(),
Claims: map[string]interface{}{
"email": "test@example.com",
"name": "Test User",
"groups": []string{"developers", "users"},
},
}, nil
}
return nil, fmt.Errorf("unknown test token: %s", token)
}
// GetUserInfo returns test user info
func (m *MockOIDCProvider) GetUserInfo(ctx context.Context, userID string) (*providers.ExternalIdentity, error) {
if !m.initialized {
return nil, fmt.Errorf("provider not initialized")
}
if userID == "" {
return nil, fmt.Errorf("user ID cannot be empty")
}
// Check test users
if identity, exists := m.TestUsers[userID]; exists {
return identity, nil
}
// Default test user
return &providers.ExternalIdentity{
UserID: userID,
Email: userID + "@example.com",
DisplayName: "Test User " + userID,
Provider: m.name,
}, nil
}
// SetupDefaultTestData configures common test data
func (m *MockOIDCProvider) SetupDefaultTestData() {
// Create default token claims
defaultClaims := &providers.TokenClaims{
Subject: "test-user-123",
Issuer: "https://test-issuer.com",
Audience: "test-client-id",
ExpiresAt: time.Now().Add(time.Hour),
IssuedAt: time.Now(),
Claims: map[string]interface{}{
"email": "testuser@example.com",
"name": "Test User",
"groups": []string{"developers"},
},
}
// Add multiple token variants for compatibility
m.AddTestToken("valid_token", defaultClaims)
m.AddTestToken("valid-oidc-token", defaultClaims) // For integration tests
m.AddTestToken("valid_test_token", defaultClaims) // For STS tests
// Add default test users
m.AddTestUser("test-user-123", &providers.ExternalIdentity{
UserID: "test-user-123",
Email: "testuser@example.com",
DisplayName: "Test User",
Groups: []string{"developers"},
Provider: m.name,
})
}

View File

@@ -0,0 +1,197 @@
package oidc
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
)
// fakeIDP wraps an httptest.Server and counts how many times each well-known
// endpoint is hit. Tests use it to assert discovery vs. fallback behaviour.
type fakeIDP struct {
server *httptest.Server
discoveryHits atomic.Int32
jwksHits atomic.Int32
customJWKSHits atomic.Int32
disableDiscovery bool
discoveryStatusCode int
discoveryIssuer string
omitDiscoveryIssuer bool // when true, the discovery doc omits the "issuer" field entirely
customJWKSPathSuffix string // optional suffix that fakeIDP serves at /custom/<suffix>
jwks JWKS
}
func newFakeIDP(t *testing.T) *fakeIDP {
t.Helper()
idp := &fakeIDP{
discoveryStatusCode: http.StatusOK,
jwks: JWKS{Keys: []JWK{{Kty: "RSA", Kid: "k1", Use: "sig", Alg: "RS256", N: "AQAB", E: "AQAB"}}},
}
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
idp.discoveryHits.Add(1)
if idp.disableDiscovery {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(idp.discoveryStatusCode)
issuer := idp.discoveryIssuer
if issuer == "" {
issuer = idp.server.URL
}
jwksURI := idp.server.URL + "/discovered/jwks"
if idp.customJWKSPathSuffix != "" {
jwksURI = idp.server.URL + "/custom/" + idp.customJWKSPathSuffix
}
body := map[string]string{"jwks_uri": jwksURI}
if !idp.omitDiscoveryIssuer {
body["issuer"] = issuer
}
_ = json.NewEncoder(w).Encode(body)
})
mux.HandleFunc("/discovered/jwks", func(w http.ResponseWriter, r *http.Request) {
idp.jwksHits.Add(1)
_ = json.NewEncoder(w).Encode(idp.jwks)
})
mux.HandleFunc("/.well-known/jwks.json", func(w http.ResponseWriter, r *http.Request) {
idp.jwksHits.Add(1)
_ = json.NewEncoder(w).Encode(idp.jwks)
})
mux.HandleFunc("/custom/", func(w http.ResponseWriter, r *http.Request) {
idp.customJWKSHits.Add(1)
_ = json.NewEncoder(w).Encode(idp.jwks)
})
idp.server = httptest.NewServer(mux)
t.Cleanup(idp.server.Close)
return idp
}
func newProviderForIDP(t *testing.T, idp *fakeIDP, jwksURIOverride string) *OIDCProvider {
t.Helper()
p := NewOIDCProvider("test")
cfg := &OIDCConfig{
Issuer: idp.server.URL,
ClientID: "test-client",
JWKSUri: jwksURIOverride,
}
if err := p.Initialize(cfg); err != nil {
t.Fatalf("Initialize: %v", err)
}
return p
}
func TestDiscoveryHappyPath(t *testing.T) {
idp := newFakeIDP(t)
p := newProviderForIDP(t, idp, "")
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS: %v", err)
}
if got := idp.discoveryHits.Load(); got != 1 {
t.Fatalf("expected 1 discovery hit, got %d", got)
}
if got := idp.jwksHits.Load(); got != 1 {
t.Fatalf("expected 1 JWKS hit at discovered uri, got %d", got)
}
// A second fetch reuses the cached jwks_uri without re-discovering.
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS second: %v", err)
}
if got := idp.discoveryHits.Load(); got != 1 {
t.Fatalf("discovery should be cached, got %d hits", got)
}
}
func TestDiscoveryFallback404(t *testing.T) {
idp := newFakeIDP(t)
idp.disableDiscovery = true
p := newProviderForIDP(t, idp, "")
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS: %v", err)
}
if got := idp.discoveryHits.Load(); got != 1 {
t.Fatalf("expected 1 discovery probe, got %d", got)
}
if got := idp.jwksHits.Load(); got != 1 {
t.Fatalf("expected 1 JWKS hit at fallback uri, got %d", got)
}
// Subsequent fetches retry discovery — discoveryFailed resets at the top
// of fetchJWKSLocked when no URI was cached, so a transient 5xx at
// startup doesn't lock the provider into the fallback path forever.
// Retry rate is bounded by the JWKS TTL (one retry per refresh cycle).
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS second: %v", err)
}
if got := idp.discoveryHits.Load(); got != 2 {
t.Fatalf("discovery probe should retry while no URI is cached, got %d hits", got)
}
}
func TestDiscoveryDisabledByExplicitJWKSUri(t *testing.T) {
idp := newFakeIDP(t)
override := idp.server.URL + "/custom/explicit"
idp.customJWKSPathSuffix = "explicit"
p := newProviderForIDP(t, idp, override)
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS: %v", err)
}
if got := idp.discoveryHits.Load(); got != 0 {
t.Fatalf("explicit JWKSUri should bypass discovery, got %d hits", got)
}
if got := idp.customJWKSHits.Load(); got != 1 {
t.Fatalf("expected 1 custom JWKS hit, got %d", got)
}
}
func TestDiscoveryRejectsIssuerMismatch(t *testing.T) {
idp := newFakeIDP(t)
idp.discoveryIssuer = "https://attacker.example/"
p := newProviderForIDP(t, idp, "")
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS should fall back to /.well-known/jwks.json, got error: %v", err)
}
// Discovery probe was tried once, rejected, then fell through to fallback path.
if got := idp.discoveryHits.Load(); got != 1 {
t.Fatalf("expected 1 discovery probe, got %d", got)
}
if got := idp.jwksHits.Load(); got != 1 {
t.Fatalf("expected 1 fallback JWKS hit, got %d", got)
}
}
// TestDiscoveryRejectsMissingIssuer: a discovery document that omits the
// issuer field entirely must be treated the same as one that supplies a
// mismatched issuer. Otherwise an attacker who can intercept the discovery
// response can strip the issuer field and the comparison silently passes,
// letting the document point fetchJWKS at any URL it pleases.
func TestDiscoveryRejectsMissingIssuer(t *testing.T) {
idp := newFakeIDP(t)
idp.omitDiscoveryIssuer = true
p := newProviderForIDP(t, idp, "")
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS should fall back to /.well-known/jwks.json on issuer-missing discovery: %v", err)
}
if got := idp.discoveryHits.Load(); got != 1 {
t.Fatalf("expected 1 discovery probe, got %d", got)
}
// The discovery document was rejected; the JWKS that ultimately served
// us must be the fallback one, not the discovered URI. The fakeIDP
// counts both hits under jwksHits since they share a counter; what
// matters is that customJWKSHits stayed zero.
if got := idp.customJWKSHits.Load(); got != 0 {
t.Fatalf("custom JWKS endpoint must not have been used, got %d hits", got)
}
if got := idp.jwksHits.Load(); got != 1 {
t.Fatalf("expected 1 fallback JWKS hit, got %d", got)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,662 @@
package oidc
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestOIDCProviderInitialization tests OIDC provider initialization
func TestOIDCProviderInitialization(t *testing.T) {
tests := []struct {
name string
config *OIDCConfig
wantErr bool
}{
{
name: "valid config",
config: &OIDCConfig{
Issuer: "https://accounts.google.com",
ClientID: "test-client-id",
JWKSUri: "https://www.googleapis.com/oauth2/v3/certs",
},
wantErr: false,
},
{
name: "missing issuer",
config: &OIDCConfig{
ClientID: "test-client-id",
},
wantErr: true,
},
{
name: "missing client id",
config: &OIDCConfig{
Issuer: "https://accounts.google.com",
},
wantErr: true,
},
{
name: "invalid issuer url",
config: &OIDCConfig{
Issuer: "not-a-url",
ClientID: "test-client-id",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
provider := NewOIDCProvider("test-provider")
err := provider.Initialize(tt.config)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, "test-provider", provider.Name())
}
})
}
}
// TestOIDCProviderJWTValidation tests JWT token validation
func TestOIDCProviderJWTValidation(t *testing.T) {
// Set up test server with JWKS endpoint
privateKey, publicKey := generateTestKeys(t)
jwks := map[string]interface{}{
"keys": []map[string]interface{}{
{
"kty": "RSA",
"kid": "test-key-id",
"use": "sig",
"alg": "RS256",
"n": encodePublicKey(t, publicKey),
"e": "AQAB",
},
},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid_configuration" {
config := map[string]interface{}{
"issuer": "http://" + r.Host,
"jwks_uri": "http://" + r.Host + "/jwks",
}
json.NewEncoder(w).Encode(config)
} else if r.URL.Path == "/jwks" {
json.NewEncoder(w).Encode(jwks)
}
}))
defer server.Close()
provider := NewOIDCProvider("test-oidc")
config := &OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
JWKSUri: server.URL + "/jwks",
}
err := provider.Initialize(config)
require.NoError(t, err)
t.Run("valid token", func(t *testing.T) {
// Create valid JWT token
token := createTestJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
"email": "user@example.com",
"name": "Test User",
})
claims, err := provider.ValidateToken(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, claims)
assert.Equal(t, "user123", claims.Subject)
assert.Equal(t, server.URL, claims.Issuer)
email, exists := claims.GetClaimString("email")
assert.True(t, exists)
assert.Equal(t, "user@example.com", email)
})
t.Run("valid token with array audience", func(t *testing.T) {
// Create valid JWT token with audience as an array (per RFC 7519)
token := createTestJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": []string{"test-client", "another-client"},
"sub": "user456",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
"email": "user2@example.com",
"name": "Test User 2",
})
claims, err := provider.ValidateToken(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, claims)
assert.Equal(t, "user456", claims.Subject)
assert.Equal(t, server.URL, claims.Issuer)
email, exists := claims.GetClaimString("email")
assert.True(t, exists)
assert.Equal(t, "user2@example.com", email)
})
t.Run("expired token", func(t *testing.T) {
// Create expired JWT token
token := createTestJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user123",
"exp": time.Now().Add(-time.Hour).Unix(), // Expired
"iat": time.Now().Add(-time.Hour * 2).Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
assert.Error(t, err)
assert.Contains(t, err.Error(), "expired")
})
t.Run("invalid signature", func(t *testing.T) {
// Create token with wrong key
wrongKey, _ := generateTestKeys(t)
token := createTestJWT(t, wrongKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
require.Error(t, err)
assert.ErrorIs(t, err, providers.ErrProviderInvalidToken)
})
}
func TestOIDCProviderJWTValidationECDSA(t *testing.T) {
privateKey, publicKey := generateTestECKeys(t)
x, y := encodeECPublicKey(t, publicKey)
jwks := map[string]interface{}{
"keys": []map[string]interface{}{
{
"kty": "EC",
"kid": "test-ec-key-id",
"use": "sig",
"alg": "ES256",
"crv": "P-256",
"x": x,
"y": y,
},
},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid_configuration" {
config := map[string]interface{}{
"issuer": "http://" + r.Host,
"jwks_uri": "http://" + r.Host + "/jwks",
}
json.NewEncoder(w).Encode(config)
} else if r.URL.Path == "/jwks" {
json.NewEncoder(w).Encode(jwks)
}
}))
defer server.Close()
provider := NewOIDCProvider("test-oidc-ecdsa")
config := &OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
JWKSUri: server.URL + "/jwks",
}
err := provider.Initialize(config)
require.NoError(t, err)
t.Run("valid token", func(t *testing.T) {
token := createTestECDSAJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user789",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
})
claims, err := provider.ValidateToken(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, claims)
assert.Equal(t, "user789", claims.Subject)
assert.Equal(t, server.URL, claims.Issuer)
})
t.Run("expired token", func(t *testing.T) {
token := createTestECDSAJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user789",
"exp": time.Now().Add(-time.Hour).Unix(),
"iat": time.Now().Add(-time.Hour * 2).Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
require.Error(t, err)
assert.ErrorIs(t, err, providers.ErrProviderTokenExpired)
})
t.Run("invalid signature", func(t *testing.T) {
wrongKey, _ := generateTestECKeys(t)
token := createTestECDSAJWT(t, wrongKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user789",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
require.Error(t, err)
assert.ErrorIs(t, err, providers.ErrProviderInvalidToken)
})
t.Run("invalid issuer", func(t *testing.T) {
token := createTestECDSAJWT(t, privateKey, jwt.MapClaims{
"iss": "http://wrong-issuer",
"aud": "test-client",
"sub": "user789",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
require.Error(t, err)
assert.ErrorIs(t, err, providers.ErrProviderInvalidIssuer)
})
t.Run("invalid audience", func(t *testing.T) {
token := createTestECDSAJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "wrong-client",
"sub": "user789",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
})
_, err := provider.ValidateToken(context.Background(), token)
require.Error(t, err)
assert.ErrorIs(t, err, providers.ErrProviderInvalidAudience)
})
}
// TestOIDCProviderAuthentication tests authentication flow
func TestOIDCProviderAuthentication(t *testing.T) {
// Set up test OIDC provider
privateKey, publicKey := generateTestKeys(t)
server := setupOIDCTestServer(t, publicKey)
defer server.Close()
provider := NewOIDCProvider("test-oidc")
config := &OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
JWKSUri: server.URL + "/jwks",
RoleMapping: &providers.RoleMapping{
Rules: []providers.MappingRule{
{
Claim: "email",
Value: "*@example.com",
Role: "arn:aws:iam::role/UserRole",
},
{
Claim: "groups",
Value: "admins",
Role: "arn:aws:iam::role/AdminRole",
},
},
DefaultRole: "arn:aws:iam::role/GuestRole",
},
}
err := provider.Initialize(config)
require.NoError(t, err)
t.Run("successful authentication", func(t *testing.T) {
token := createTestJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
"email": "user@example.com",
"name": "Test User",
"groups": []string{"users", "developers"},
})
identity, err := provider.Authenticate(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, identity)
assert.Equal(t, "user123", identity.UserID)
assert.Equal(t, "user@example.com", identity.Email)
assert.Equal(t, "Test User", identity.DisplayName)
assert.Equal(t, "test-oidc", identity.Provider)
assert.Contains(t, identity.Groups, "users")
assert.Contains(t, identity.Groups, "developers")
})
t.Run("successful authentication with additional attributes", func(t *testing.T) {
token := createTestJWT(t, privateKey, jwt.MapClaims{
"iss": server.URL,
"aud": "test-client",
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
"email": "user@example.com",
"name": "Test User",
"groups": []string{"users"},
"preferred_username": "myusername", // Extra claim
"department": "engineering", // Extra claim
"custom_number": 42, // Non-string claim
"custom_avg": 98.6, // Non-string claim
"custom_object": map[string]interface{}{"nested": "value"}, // Nested object claim
})
identity, err := provider.Authenticate(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, identity)
// Check standard fields
assert.Equal(t, "user123", identity.UserID)
// Check attributes
val, exists := identity.Attributes["preferred_username"]
assert.True(t, exists, "preferred_username should be in attributes")
assert.Equal(t, "myusername", val)
val, exists = identity.Attributes["department"]
assert.True(t, exists, "department should be in attributes")
assert.Equal(t, "engineering", val)
// Test non-string claims (should be JSON marshaled)
val, exists = identity.Attributes["custom_number"]
assert.True(t, exists, "custom_number should be in attributes")
assert.Equal(t, "42", val)
val, exists = identity.Attributes["custom_avg"]
assert.True(t, exists, "custom_avg should be in attributes")
assert.Contains(t, val, "98.6") // JSON number formatting might vary
val, exists = identity.Attributes["custom_object"]
assert.True(t, exists, "custom_object should be in attributes")
assert.Contains(t, val, "\"nested\":\"value\"")
// Verify structural JWT claims are excluded from attributes
excludedClaims := []string{"iss", "aud", "exp", "iat"}
for _, claim := range excludedClaims {
_, exists := identity.Attributes[claim]
assert.False(t, exists, "standard claim %s should not be in attributes", claim)
}
})
t.Run("authentication with invalid token", func(t *testing.T) {
_, err := provider.Authenticate(context.Background(), "invalid-token")
assert.Error(t, err)
})
}
// TestOIDCProviderUserInfo tests user info retrieval
func TestOIDCProviderUserInfo(t *testing.T) {
// Set up test server with UserInfo endpoint
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/userinfo" {
// Check for Authorization header
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error": "unauthorized"}`))
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer ")
// Return 401 for explicitly invalid tokens
if accessToken == "invalid-token" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error": "invalid_token"}`))
return
}
// Mock user info response
userInfo := map[string]interface{}{
"sub": "user123",
"email": "user@example.com",
"name": "Test User",
"groups": []string{"users", "developers"},
}
// Customize response based on token
if strings.Contains(accessToken, "admin") {
userInfo["groups"] = []string{"admins"}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userInfo)
}
}))
defer server.Close()
provider := NewOIDCProvider("test-oidc")
config := &OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
UserInfoUri: server.URL + "/userinfo",
}
err := provider.Initialize(config)
require.NoError(t, err)
t.Run("get user info with access token", func(t *testing.T) {
// Test using access token (real UserInfo endpoint call)
identity, err := provider.GetUserInfoWithToken(context.Background(), "valid-access-token")
require.NoError(t, err)
require.NotNil(t, identity)
assert.Equal(t, "user123", identity.UserID)
assert.Equal(t, "user@example.com", identity.Email)
assert.Equal(t, "Test User", identity.DisplayName)
assert.Contains(t, identity.Groups, "users")
assert.Contains(t, identity.Groups, "developers")
assert.Equal(t, "test-oidc", identity.Provider)
})
t.Run("get admin user info", func(t *testing.T) {
// Test admin token response
identity, err := provider.GetUserInfoWithToken(context.Background(), "admin-access-token")
require.NoError(t, err)
require.NotNil(t, identity)
assert.Equal(t, "user123", identity.UserID)
assert.Contains(t, identity.Groups, "admins")
})
t.Run("get user info without token", func(t *testing.T) {
// Test without access token (should fail)
_, err := provider.GetUserInfoWithToken(context.Background(), "")
assert.Error(t, err)
assert.Contains(t, err.Error(), "access token cannot be empty")
})
t.Run("get user info with invalid token", func(t *testing.T) {
// Test with invalid access token (should get 401)
_, err := provider.GetUserInfoWithToken(context.Background(), "invalid-token")
assert.Error(t, err)
assert.Contains(t, err.Error(), "UserInfo endpoint returned status 401")
})
t.Run("get user info with custom claims mapping", func(t *testing.T) {
// Create provider with custom claims mapping
customProvider := NewOIDCProvider("test-custom-oidc")
customConfig := &OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
UserInfoUri: server.URL + "/userinfo",
ClaimsMapping: map[string]string{
"customEmail": "email",
"customName": "name",
},
}
err := customProvider.Initialize(customConfig)
require.NoError(t, err)
identity, err := customProvider.GetUserInfoWithToken(context.Background(), "valid-access-token")
require.NoError(t, err)
require.NotNil(t, identity)
// Standard claims should still work
assert.Equal(t, "user123", identity.UserID)
assert.Equal(t, "user@example.com", identity.Email)
assert.Equal(t, "Test User", identity.DisplayName)
})
t.Run("get user info with empty id", func(t *testing.T) {
_, err := provider.GetUserInfo(context.Background(), "")
assert.Error(t, err)
})
}
// Helper functions for testing
func generateTestKeys(t *testing.T) (*rsa.PrivateKey, *rsa.PublicKey) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
return privateKey, &privateKey.PublicKey
}
func generateTestECKeys(t *testing.T) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
return privateKey, &privateKey.PublicKey
}
func createTestJWT(t *testing.T, privateKey *rsa.PrivateKey, claims jwt.MapClaims) string {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
token.Header["kid"] = "test-key-id"
tokenString, err := token.SignedString(privateKey)
require.NoError(t, err)
return tokenString
}
func createTestECDSAJWT(t *testing.T, privateKey *ecdsa.PrivateKey, claims jwt.MapClaims) string {
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["kid"] = "test-ec-key-id"
tokenString, err := token.SignedString(privateKey)
require.NoError(t, err)
return tokenString
}
func encodePublicKey(t *testing.T, publicKey *rsa.PublicKey) string {
// Properly encode the RSA modulus (N) as base64url
return base64.RawURLEncoding.EncodeToString(publicKey.N.Bytes())
}
func encodeECPublicKey(t *testing.T, publicKey *ecdsa.PublicKey) (string, string) {
// RFC 7518 §6.2.1.2 requires EC coordinates to be zero-padded to the full field size
curveParams := publicKey.Curve.Params()
size := (curveParams.BitSize + 7) / 8
xBytes := publicKey.X.Bytes()
yBytes := publicKey.Y.Bytes()
xPadded := make([]byte, size)
yPadded := make([]byte, size)
// Right-align the coordinate bytes and leave leading zeros for padding
copy(xPadded[size-len(xBytes):], xBytes)
copy(yPadded[size-len(yBytes):], yBytes)
return base64.RawURLEncoding.EncodeToString(xPadded),
base64.RawURLEncoding.EncodeToString(yPadded)
}
func setupOIDCTestServer(t *testing.T, publicKey *rsa.PublicKey) *httptest.Server {
jwks := map[string]interface{}{
"keys": []map[string]interface{}{
{
"kty": "RSA",
"kid": "test-key-id",
"use": "sig",
"alg": "RS256",
"n": encodePublicKey(t, publicKey),
"e": "AQAB",
},
},
}
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid_configuration":
config := map[string]interface{}{
"issuer": "http://" + r.Host,
"jwks_uri": "http://" + r.Host + "/jwks",
"userinfo_endpoint": "http://" + r.Host + "/userinfo",
}
json.NewEncoder(w).Encode(config)
case "/jwks":
json.NewEncoder(w).Encode(jwks)
case "/userinfo":
// Mock UserInfo endpoint
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error": "unauthorized"}`))
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer ")
// Return 401 for explicitly invalid tokens
if accessToken == "invalid-token" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error": "invalid_token"}`))
return
}
// Mock user info response based on access token
userInfo := map[string]interface{}{
"sub": "user123",
"email": "user@example.com",
"name": "Test User",
"groups": []string{"users", "developers"},
}
// Customize response based on token
if strings.Contains(accessToken, "admin") {
userInfo["groups"] = []string{"admins"}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userInfo)
default:
http.NotFound(w, r)
}
}))
}

View File

@@ -0,0 +1,57 @@
package oidc
import (
"reflect"
"testing"
)
func TestExtractClaimPoliciesString(t *testing.T) {
got := extractClaimPolicies(map[string]interface{}{"policy": "readonly"}, "policy")
if !reflect.DeepEqual(got, []string{"readonly"}) {
t.Fatalf("got=%v", got)
}
}
func TestExtractClaimPoliciesCommaSeparated(t *testing.T) {
got := extractClaimPolicies(map[string]interface{}{"policy": "readonly, billing , "}, "policy")
if !reflect.DeepEqual(got, []string{"readonly", "billing"}) {
t.Fatalf("got=%v", got)
}
}
func TestExtractClaimPoliciesArray(t *testing.T) {
got := extractClaimPolicies(map[string]interface{}{
"policy": []interface{}{"readonly", "billing", 42, ""}, // non-string + empty filtered
}, "policy")
if !reflect.DeepEqual(got, []string{"readonly", "billing"}) {
t.Fatalf("got=%v", got)
}
}
func TestExtractClaimPoliciesMissing(t *testing.T) {
if got := extractClaimPolicies(map[string]interface{}{}, "policy"); got != nil {
t.Fatalf("expected nil, got %v", got)
}
}
func TestExtractClaimPoliciesEmptyClaimName(t *testing.T) {
// Provider not in claim-mode -> never read the claim, even if present.
if got := extractClaimPolicies(map[string]interface{}{"policy": "readonly"}, ""); got != nil {
t.Fatalf("empty claim name should return nil, got %v", got)
}
}
func TestExtractClaimPoliciesUnsupportedShape(t *testing.T) {
// Numeric / object / bool values should be ignored, not panic.
cases := []interface{}{
42,
3.14,
map[string]interface{}{"x": "y"},
true,
}
for _, v := range cases {
if got := extractClaimPolicies(map[string]interface{}{"policy": v}, "policy"); got != nil {
t.Fatalf("value %v: expected nil, got %v", v, got)
}
}
}

View File

@@ -0,0 +1,83 @@
package oidc
import (
"reflect"
"testing"
)
func TestExtractPrincipalTagsObjectShape(t *testing.T) {
claims := map[string]interface{}{
PrincipalTagsClaim: map[string]interface{}{
"team": "infra",
"env": "prod",
"empty": "",
// non-string values are dropped
"count": 42,
},
}
got := extractPrincipalTags(claims)
want := map[string]string{"team": "infra", "env": "prod", "empty": ""}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got=%v want=%v", got, want)
}
}
func TestExtractPrincipalTagsArrayValueTakesFirst(t *testing.T) {
claims := map[string]interface{}{
PrincipalTagsClaim: map[string]interface{}{
"team": []interface{}{"infra", "ignored"},
},
}
got := extractPrincipalTags(claims)
if got["team"] != "infra" {
t.Fatalf("expected first array element, got %q", got["team"])
}
}
func TestExtractPrincipalTagsAbsent(t *testing.T) {
if got := extractPrincipalTags(map[string]interface{}{}); got != nil {
t.Fatalf("expected nil for missing claim, got %v", got)
}
}
func TestExtractPrincipalTagsWrongShape(t *testing.T) {
claims := map[string]interface{}{PrincipalTagsClaim: "not-an-object"}
if got := extractPrincipalTags(claims); got != nil {
t.Fatalf("expected nil for non-object claim, got %v", got)
}
}
func TestFilterPrincipalTagsAllowlist(t *testing.T) {
in := map[string]string{"team": "infra", "env": "prod", "secret": "shh"}
t.Run("empty allowlist denies all", func(t *testing.T) {
if got := filterPrincipalTags(in, nil); got != nil {
t.Fatalf("expected nil, got %v", got)
}
})
t.Run("partial allowlist", func(t *testing.T) {
got := filterPrincipalTags(in, []string{"team", "env"})
want := map[string]string{"team": "infra", "env": "prod"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got=%v want=%v", got, want)
}
})
t.Run("allowlist with no matches", func(t *testing.T) {
if got := filterPrincipalTags(in, []string{"unknown"}); got != nil {
t.Fatalf("expected nil, got %v", got)
}
})
t.Run("case-insensitive on key", func(t *testing.T) {
// AWS session tag keys are case-insensitive. An IDP whose claim
// uses different casing than the operator's allowlist string
// must still match.
got := filterPrincipalTags(map[string]string{"Team": "infra"}, []string{"TEAM"})
want := map[string]string{"Team": "infra"} // original casing preserved on output
if !reflect.DeepEqual(got, want) {
t.Fatalf("got=%v want=%v", got, want)
}
})
}

View File

@@ -0,0 +1,153 @@
package oidc
import (
"context"
"crypto/sha1"
"crypto/tls"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
// thumbprintFromTLS returns the SHA-1 hex of the first peer certificate the
// given TLS server presents. It mirrors the pinning algorithm used by the
// OIDC provider so the test is hashing the cert that will actually be
// verified at runtime.
func thumbprintFromTLS(t *testing.T, server *httptest.Server) string {
t.Helper()
if server.TLS == nil || len(server.Certificate().Raw) == 0 {
t.Fatal("server has no TLS certificate")
}
sum := sha1.Sum(server.Certificate().Raw)
return hex.EncodeToString(sum[:])
}
// newTLSIDP starts a TLS-only test IDP that always serves a static JWKS.
// httptest TLS servers use a self-signed certificate by default, which means
// callers who want a successful handshake must either trust that cert or
// use TLSInsecureSkipVerify.
func newTLSIDP(t *testing.T) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/jwks.json", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(JWKS{Keys: []JWK{{Kty: "RSA", Kid: "k1", Use: "sig", Alg: "RS256", N: "AQAB", E: "AQAB"}}})
})
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r) // force fallback path
})
server := httptest.NewTLSServer(mux)
t.Cleanup(server.Close)
return server
}
// pinnedProvider configures an OIDC provider that pins TLS to the given
// thumbprint allowlist and trusts only the test server's self-signed cert.
func pinnedProvider(t *testing.T, server *httptest.Server, thumbprints []string) *OIDCProvider {
t.Helper()
p := NewOIDCProvider("thumbprint-test")
cfg := &OIDCConfig{
Issuer: server.URL,
ClientID: "anything",
Thumbprints: thumbprints,
TLSInsecureSkipVerify: true, // we're doing the trust decision via thumbprint
}
if err := p.Initialize(cfg); err != nil {
t.Fatalf("Initialize: %v", err)
}
// Replace the inner transport's RootCAs with the server's cert so the chain
// builder also accepts it; this exercises the verified-chain path.
if transport, ok := p.httpClient.Transport.(*http.Transport); ok && transport.TLSClientConfig != nil {
transport.TLSClientConfig.InsecureSkipVerify = false
transport.TLSClientConfig.RootCAs = server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs
}
return p
}
func TestThumbprintMatchAccepted(t *testing.T) {
server := newTLSIDP(t)
tp := thumbprintFromTLS(t, server)
p := pinnedProvider(t, server, []string{tp})
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS with matching thumbprint should succeed: %v", err)
}
}
func TestThumbprintMismatchRejected(t *testing.T) {
server := newTLSIDP(t)
// Flip the last byte so the digest can't match anything legitimate.
bad := "0000000000000000000000000000000000000000"
p := pinnedProvider(t, server, []string{bad})
err := p.fetchJWKS(context.Background())
if err == nil {
t.Fatal("fetchJWKS with mismatched thumbprint should fail")
}
}
func TestThumbprintAllowlistAcceptsMixedCase(t *testing.T) {
server := newTLSIDP(t)
tp := thumbprintFromTLS(t, server)
// Mix uppercase + whitespace to ensure normalization is applied.
p := pinnedProvider(t, server, []string{" " + uppercase(tp) + " "})
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("normalized thumbprint should match: %v", err)
}
}
// uppercase returns s with letters uppercased — cheap helper avoiding a
// dependency on strings.ToUpper at the package level for clarity.
func uppercase(s string) string {
out := make([]byte, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
if c >= 'a' && c <= 'z' {
c -= 32
}
out[i] = c
}
return string(out)
}
// guard against a future refactor that drops VerifyConnection by checking
// that omitting Thumbprints leaves the connection unverified-by-pin.
func TestThumbprintEmptyAllowlistSkipsCheck(t *testing.T) {
server := newTLSIDP(t)
p := pinnedProvider(t, server, nil)
transport, ok := p.httpClient.Transport.(*http.Transport)
if !ok {
t.Fatal("expected *http.Transport")
}
if transport.TLSClientConfig.VerifyConnection != nil {
t.Fatal("VerifyConnection must be nil when no thumbprints are configured")
}
// And the full TLS handshake still succeeds normally.
if err := p.fetchJWKS(context.Background()); err != nil {
t.Fatalf("fetchJWKS with no thumbprints: %v", err)
}
}
// Ensure the underlying tls.Config still rejects truly invalid handshakes
// when InsecureSkipVerify is on but no thumbprint allowlist is configured —
// in that case we explicitly want to *trust* the connection (skip-verify),
// just as the existing test code did.
func TestThumbprintSkipVerifyHonoured(t *testing.T) {
server := newTLSIDP(t)
p := NewOIDCProvider("skip")
if err := p.Initialize(&OIDCConfig{
Issuer: server.URL,
ClientID: "x",
TLSInsecureSkipVerify: true,
}); err != nil {
t.Fatalf("Initialize: %v", err)
}
transport := p.httpClient.Transport.(*http.Transport)
if !transport.TLSClientConfig.InsecureSkipVerify {
t.Fatal("InsecureSkipVerify should be set")
}
if got := transport.TLSClientConfig.MinVersion; got != tls.VersionTLS12 {
t.Fatalf("MinVersion = %v want TLS12", got)
}
}