mirror of
https://github.com/lukaszraczylo/traefikoidc.git
synced 2026-10-14 04:07:46 +00:00
Release 0.7.5 (#70)
* Resolve issue with opaque tokens not being parsed correctly * Increase test coverage * Further improvements to test coverage and code quality * Add new providers. * fixup! Add new providers. * Cleanup. * fixup! Cleanup. * fixup! fixup! Cleanup. * fixup! fixup! fixup! Cleanup. * fixup! fixup! fixup! fixup! Cleanup. * Memory management optimisation 24 bytes per Put < 256-4096 bytes per buffer allocation avoided (10-170x difference) * Pooling cleanup.
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Auth0Provider encapsulates Auth0-specific OIDC logic.
|
||||
type Auth0Provider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewAuth0Provider creates a new instance of the Auth0Provider.
|
||||
func NewAuth0Provider() *Auth0Provider {
|
||||
return &Auth0Provider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *Auth0Provider) GetType() ProviderType {
|
||||
return ProviderTypeAuth0
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the Auth0 provider.
|
||||
func (p *Auth0Provider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: true,
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "id", // Auth0 typically uses ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures Auth0-specific authentication parameters.
|
||||
func (p *Auth0Provider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// Auth0 supports various response types and connection parameters
|
||||
baseParams.Set("response_type", "code")
|
||||
|
||||
// Ensure offline_access scope is present for refresh tokens
|
||||
hasOfflineAccess := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "offline_access" {
|
||||
hasOfflineAccess = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOfflineAccess {
|
||||
scopes = append(scopes, "offline_access")
|
||||
}
|
||||
|
||||
// Ensure openid scope is present
|
||||
hasOpenID := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "openid" {
|
||||
hasOpenID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOpenID {
|
||||
scopes = append(scopes, "openid")
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(scopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Auth0 requires specific tenant configuration and connection handling.
|
||||
func (p *Auth0Provider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAuth0Provider_NewAuth0Provider tests the constructor
|
||||
func TestAuth0Provider_NewAuth0Provider(t *testing.T) {
|
||||
provider := NewAuth0Provider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuth0Provider_GetType tests provider type
|
||||
func TestAuth0Provider_GetType(t *testing.T) {
|
||||
provider := NewAuth0Provider()
|
||||
|
||||
if provider.GetType() != ProviderTypeAuth0 {
|
||||
t.Errorf("Expected ProviderTypeAuth0, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuth0Provider_GetCapabilities tests Auth0-specific capabilities
|
||||
func TestAuth0Provider_GetCapabilities(t *testing.T) {
|
||||
provider := NewAuth0Provider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true for Auth0")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be true for Auth0")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for Auth0")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuth0Provider_BuildAuthParams tests Auth0-specific auth params
|
||||
func TestAuth0Provider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewAuth0Provider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Add offline_access and openid scopes",
|
||||
scopes: []string{"profile", "email"},
|
||||
expectedScopes: []string{"profile", "email", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keep existing offline_access and openid",
|
||||
scopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
},
|
||||
{
|
||||
name: "Add both scopes when none provided",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"offline_access", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that response_type is set
|
||||
if authParams.URLValues.Get("response_type") != "code" {
|
||||
t.Errorf("Expected response_type 'code', got '%s'", authParams.URLValues.Get("response_type"))
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d. Expected: %v, Got: %v",
|
||||
len(tt.expectedScopes), len(authParams.Scopes), tt.expectedScopes, authParams.Scopes)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuth0Provider_ValidateConfig tests config validation
|
||||
func TestAuth0Provider_ValidateConfig(t *testing.T) {
|
||||
provider := NewAuth0Provider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AWSCognitoProvider encapsulates AWS Cognito-specific OIDC logic.
|
||||
type AWSCognitoProvider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewAWSCognitoProvider creates a new instance of the AWSCognitoProvider.
|
||||
func NewAWSCognitoProvider() *AWSCognitoProvider {
|
||||
return &AWSCognitoProvider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *AWSCognitoProvider) GetType() ProviderType {
|
||||
return ProviderTypeAWSCognito
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the AWS Cognito provider.
|
||||
func (p *AWSCognitoProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: false, // Cognito doesn't use offline_access scope
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "id", // Cognito typically uses ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures AWS Cognito-specific authentication parameters.
|
||||
func (p *AWSCognitoProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// AWS Cognito supports standard OIDC parameters
|
||||
baseParams.Set("response_type", "code")
|
||||
|
||||
// Remove offline_access scope as Cognito doesn't use it (case-insensitive)
|
||||
var filteredScopes []string
|
||||
for _, scope := range scopes {
|
||||
if strings.ToLower(scope) != "offline_access" {
|
||||
filteredScopes = append(filteredScopes, scope)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure openid scope is present
|
||||
hasOpenID := false
|
||||
for _, scope := range filteredScopes {
|
||||
if scope == "openid" {
|
||||
hasOpenID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOpenID {
|
||||
filteredScopes = append(filteredScopes, "openid")
|
||||
}
|
||||
|
||||
// Default Cognito scopes if none specified
|
||||
if len(filteredScopes) == 1 && filteredScopes[0] == "openid" {
|
||||
filteredScopes = append(filteredScopes, "email", "profile")
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(filteredScopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AWS Cognito requires user pool and domain configuration.
|
||||
func (p *AWSCognitoProvider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAWSCognitoProvider_NewAWSCognitoProvider tests the constructor
|
||||
func TestAWSCognitoProvider_NewAWSCognitoProvider(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_GetType tests provider type
|
||||
func TestAWSCognitoProvider_GetType(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeAWSCognito {
|
||||
t.Errorf("Expected ProviderTypeAWSCognito, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_GetCapabilities tests AWS Cognito-specific capabilities
|
||||
func TestAWSCognitoProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true for AWS Cognito")
|
||||
}
|
||||
|
||||
if capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be false for AWS Cognito")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for AWS Cognito")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_BuildAuthParams tests AWS Cognito-specific auth params
|
||||
func TestAWSCognitoProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Remove offline_access scope and ensure openid",
|
||||
scopes: []string{"email", "profile", "offline_access"},
|
||||
expectedScopes: []string{"email", "profile", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keep existing openid, remove offline_access",
|
||||
scopes: []string{"openid", "email", "offline_access", "profile"},
|
||||
expectedScopes: []string{"openid", "email", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Add default scopes when only openid",
|
||||
scopes: []string{"openid"},
|
||||
expectedScopes: []string{"openid", "email", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Add openid and defaults when empty",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"openid", "email", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Cognito-specific scopes",
|
||||
scopes: []string{"aws.cognito.signin.user.admin", "phone"},
|
||||
expectedScopes: []string{"aws.cognito.signin.user.admin", "phone", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that response_type is set
|
||||
if authParams.URLValues.Get("response_type") != "code" {
|
||||
t.Errorf("Expected response_type 'code', got '%s'", authParams.URLValues.Get("response_type"))
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d. Expected: %v, Got: %v",
|
||||
len(tt.expectedScopes), len(authParams.Scopes), tt.expectedScopes, authParams.Scopes)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure offline_access is NOT present
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == "offline_access" {
|
||||
t.Error("offline_access scope should be filtered out for AWS Cognito")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_ValidateConfig tests config validation
|
||||
func TestAWSCognitoProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_InterfaceCompliance tests that AWS Cognito provider implements the OIDCProvider interface
|
||||
func TestAWSCognitoProvider_InterfaceCompliance(t *testing.T) {
|
||||
var _ OIDCProvider = NewAWSCognitoProvider()
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_BaseProviderInheritance tests that AWS Cognito provider inherits from BaseProvider correctly
|
||||
func TestAWSCognitoProvider_BaseProviderInheritance(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
|
||||
// Test that it has access to BaseProvider methods
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("Expected BaseProvider to be initialized")
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh (inherited from BaseProvider)
|
||||
err := provider.HandleTokenRefresh(&TokenResult{
|
||||
IDToken: "test-id-token",
|
||||
AccessToken: "test-access-token",
|
||||
RefreshToken: "test-refresh-token",
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("HandleTokenRefresh failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_OfflineAccessFiltering tests that offline_access scope is always filtered out
|
||||
func TestAWSCognitoProvider_OfflineAccessFiltering(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
}{
|
||||
{
|
||||
name: "Single offline_access",
|
||||
scopes: []string{"offline_access"},
|
||||
},
|
||||
{
|
||||
name: "Multiple offline_access occurrences",
|
||||
scopes: []string{"offline_access", "email", "offline_access", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Mixed case",
|
||||
scopes: []string{"OFFLINE_ACCESS", "email"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure offline_access is NOT present in any form
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == "offline_access" || actualScope == "OFFLINE_ACCESS" {
|
||||
t.Errorf("offline_access scope should be filtered out, but found: %s", actualScope)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_CognitoSpecificScopes tests AWS Cognito-specific scopes
|
||||
func TestAWSCognitoProvider_CognitoSpecificScopes(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
checkFor []string
|
||||
}{
|
||||
{
|
||||
name: "Cognito admin scope",
|
||||
scopes: []string{"aws.cognito.signin.user.admin"},
|
||||
checkFor: []string{"aws.cognito.signin.user.admin", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Phone scope",
|
||||
scopes: []string{"phone"},
|
||||
checkFor: []string{"phone", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Address scope",
|
||||
scopes: []string{"address"},
|
||||
checkFor: []string{"address", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Multiple Cognito scopes",
|
||||
scopes: []string{"aws.cognito.signin.user.admin", "phone", "address"},
|
||||
checkFor: []string{"aws.cognito.signin.user.admin", "phone", "address", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.checkFor {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAWSCognitoProvider_DefaultScopeHandling tests default scope behavior
|
||||
func TestAWSCognitoProvider_DefaultScopeHandling(t *testing.T) {
|
||||
provider := NewAWSCognitoProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
// Test with only openid scope - should add defaults
|
||||
authParams, err := provider.BuildAuthParams(baseParams, []string{"openid"})
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
expectedScopes := []string{"openid", "email", "profile"}
|
||||
if len(authParams.Scopes) != len(expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(expectedScopes), len(authParams.Scopes))
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected default scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func (p *AzureProvider) BuildAuthParams(baseParams url.Values, scopes []string)
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: scopes,
|
||||
Scopes: deduplicateScopes(scopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestAzureProvider_NewAzureProvider tests the constructor
|
||||
func TestAzureProvider_NewAzureProvider(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_GetType tests provider type
|
||||
func TestAzureProvider_GetType(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeAzure {
|
||||
t.Errorf("Expected ProviderTypeAzure, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_GetCapabilities tests Azure-specific capabilities
|
||||
func TestAzureProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be true for Azure")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for Azure")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "access" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'access', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_BuildAuthParams tests Azure-specific auth parameters
|
||||
func TestAzureProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
inputScopes []string
|
||||
expectedScopes []string
|
||||
shouldHaveResponseMode bool
|
||||
shouldAddOfflineAccess bool
|
||||
}{
|
||||
{
|
||||
name: "Basic scopes without offline_access",
|
||||
inputScopes: []string{"openid", "profile", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "email", "offline_access"},
|
||||
shouldHaveResponseMode: true,
|
||||
shouldAddOfflineAccess: true,
|
||||
},
|
||||
{
|
||||
name: "Scopes with offline_access already present",
|
||||
inputScopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
shouldHaveResponseMode: true,
|
||||
shouldAddOfflineAccess: false,
|
||||
},
|
||||
{
|
||||
name: "Only offline_access scope",
|
||||
inputScopes: []string{"offline_access"},
|
||||
expectedScopes: []string{"offline_access"},
|
||||
shouldHaveResponseMode: true,
|
||||
shouldAddOfflineAccess: false,
|
||||
},
|
||||
{
|
||||
name: "Empty scopes (should add offline_access)",
|
||||
inputScopes: []string{},
|
||||
expectedScopes: []string{"offline_access"},
|
||||
shouldHaveResponseMode: true,
|
||||
shouldAddOfflineAccess: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
|
||||
result, err := provider.BuildAuthParams(baseParams, tt.inputScopes)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Check Azure-specific parameters
|
||||
if tt.shouldHaveResponseMode {
|
||||
if result.URLValues.Get("response_mode") != "query" {
|
||||
t.Errorf("Expected response_mode 'query', got '%s'", result.URLValues.Get("response_mode"))
|
||||
}
|
||||
}
|
||||
|
||||
// Check scopes
|
||||
if len(result.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(tt.expectedScopes), len(result.Scopes))
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range result.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in result", expectedScope)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify offline_access is present
|
||||
hasOfflineAccess := false
|
||||
for _, scope := range result.Scopes {
|
||||
if scope == "offline_access" {
|
||||
hasOfflineAccess = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOfflineAccess {
|
||||
t.Error("Azure provider should always include offline_access scope")
|
||||
}
|
||||
|
||||
// Verify original base parameters are preserved
|
||||
if result.URLValues.Get("client_id") != "test-client" {
|
||||
t.Errorf("Expected client_id 'test-client', got '%s'", result.URLValues.Get("client_id"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_ValidateTokens tests Azure-specific token validation logic
|
||||
func TestAzureProvider_ValidateTokens(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
session *mockSession
|
||||
verifierError error
|
||||
cacheData map[string]interface{}
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "Unauthenticated with refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: false,
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Unauthenticated without refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: false,
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "JWT access token valid",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "valid.jwt.token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: nil,
|
||||
cacheData: map[string]interface{}{
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "JWT access token invalid, valid ID token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "invalid.jwt.token",
|
||||
idToken: "valid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: errors.New("invalid token"),
|
||||
cacheData: map[string]interface{}{
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Opaque access token with valid ID token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "opaque-token-no-dots",
|
||||
idToken: "valid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
cacheData: map[string]interface{}{
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Opaque access token without ID token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "opaque-token-no-dots",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No access token, valid ID token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "valid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: nil,
|
||||
cacheData: map[string]interface{}{
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No access token, invalid ID token, with refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "invalid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: errors.New("invalid token"),
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No tokens, with refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No tokens, no refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
verifier := &mockTokenVerifier{error: tt.verifierError}
|
||||
cache := &mockTokenCache{claims: make(map[string]map[string]interface{})}
|
||||
|
||||
// Set up cache data
|
||||
if tt.cacheData != nil {
|
||||
if tt.session.accessToken != "" && strings.Count(tt.session.accessToken, ".") == 2 {
|
||||
cache.claims[tt.session.accessToken] = tt.cacheData
|
||||
}
|
||||
if tt.session.idToken != "" {
|
||||
cache.claims[tt.session.idToken] = tt.cacheData
|
||||
}
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokens(tt.session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_ValidateConfig tests configuration validation
|
||||
func TestAzureProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_InterfaceCompliance tests that Azure provider implements OIDCProvider
|
||||
func TestAzureProvider_InterfaceCompliance(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
// Verify it implements the OIDCProvider interface
|
||||
var _ OIDCProvider = provider
|
||||
}
|
||||
|
||||
// TestAzureProvider_OfflineAccessHandling tests comprehensive offline_access handling
|
||||
func TestAzureProvider_OfflineAccessHandling(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
inputScopes []string
|
||||
expectedCount int // Expected number of offline_access scopes (should be 1)
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "No offline_access - should add one",
|
||||
inputScopes: []string{"openid", "profile", "email"},
|
||||
expectedCount: 1,
|
||||
description: "Should add offline_access when not present",
|
||||
},
|
||||
{
|
||||
name: "One offline_access - should preserve",
|
||||
inputScopes: []string{"openid", "offline_access", "profile"},
|
||||
expectedCount: 1,
|
||||
description: "Should preserve existing offline_access",
|
||||
},
|
||||
{
|
||||
name: "Multiple offline_access - should deduplicate",
|
||||
inputScopes: []string{"openid", "offline_access", "profile", "offline_access"},
|
||||
expectedCount: 1,
|
||||
description: "Should deduplicate multiple offline_access scopes",
|
||||
},
|
||||
{
|
||||
name: "Only offline_access",
|
||||
inputScopes: []string{"offline_access"},
|
||||
expectedCount: 1,
|
||||
description: "Should preserve when only offline_access is present",
|
||||
},
|
||||
{
|
||||
name: "Empty scopes - should add offline_access",
|
||||
inputScopes: []string{},
|
||||
expectedCount: 1,
|
||||
description: "Should add offline_access when no scopes provided",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseParams := make(url.Values)
|
||||
result, err := provider.BuildAuthParams(baseParams, tt.inputScopes)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Count offline_access occurrences in result
|
||||
offlineAccessCount := 0
|
||||
for _, scope := range result.Scopes {
|
||||
if scope == "offline_access" {
|
||||
offlineAccessCount++
|
||||
}
|
||||
}
|
||||
|
||||
if offlineAccessCount != tt.expectedCount {
|
||||
t.Errorf("Expected %d offline_access scopes in result, got %d", tt.expectedCount, offlineAccessCount)
|
||||
}
|
||||
|
||||
// Ensure at least one offline_access is always present
|
||||
if offlineAccessCount == 0 {
|
||||
t.Error("Azure provider should always have at least one offline_access scope")
|
||||
}
|
||||
|
||||
// Verify other scopes are preserved (except for the empty case)
|
||||
if len(tt.inputScopes) > 0 {
|
||||
for _, originalScope := range tt.inputScopes {
|
||||
found := false
|
||||
for _, resultScope := range result.Scopes {
|
||||
if resultScope == originalScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' to be preserved", originalScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_TokenValidationPriority tests access token vs ID token priority
|
||||
func TestAzureProvider_TokenValidationPriority(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
// Test that Azure prefers access tokens over ID tokens when both are JWT
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "valid.access.token",
|
||||
idToken: "valid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
}
|
||||
|
||||
verifier := &mockTokenVerifier{} // Valid tokens
|
||||
cache := &mockTokenCache{
|
||||
claims: map[string]map[string]interface{}{
|
||||
"valid.access.token": {
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
"valid.id.token": {
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if !result.Authenticated {
|
||||
t.Error("Should be authenticated with valid access token")
|
||||
}
|
||||
|
||||
if result.NeedsRefresh {
|
||||
t.Error("Should not need refresh with valid access token")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAzureProvider_AuthParamsPreservation tests that base parameters are not overwritten
|
||||
func TestAzureProvider_AuthParamsPreservation(t *testing.T) {
|
||||
provider := NewAzureProvider()
|
||||
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
baseParams.Set("redirect_uri", "https://example.com/callback")
|
||||
baseParams.Set("response_type", "code")
|
||||
baseParams.Set("state", "test-state")
|
||||
baseParams.Set("nonce", "test-nonce")
|
||||
|
||||
scopes := []string{"openid", "profile"}
|
||||
|
||||
result, err := provider.BuildAuthParams(baseParams, scopes)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Verify all original parameters are preserved
|
||||
expectedParams := map[string]string{
|
||||
"client_id": "test-client",
|
||||
"redirect_uri": "https://example.com/callback",
|
||||
"response_type": "code",
|
||||
"state": "test-state",
|
||||
"nonce": "test-nonce",
|
||||
"response_mode": "query", // Added by Azure provider
|
||||
}
|
||||
|
||||
for key, expectedValue := range expectedParams {
|
||||
actualValue := result.URLValues.Get(key)
|
||||
if actualValue != expectedValue {
|
||||
t.Errorf("Expected %s '%s', got '%s'", key, expectedValue, actualValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify scopes (should include offline_access)
|
||||
if len(result.Scopes) != 3 {
|
||||
t.Errorf("Expected 3 scopes (including offline_access), got %d", len(result.Scopes))
|
||||
}
|
||||
|
||||
expectedScopes := []string{"openid", "profile", "offline_access"}
|
||||
for _, expectedScope := range expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range result.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found", expectedScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkAzureProvider_BuildAuthParams(b *testing.B) {
|
||||
provider := NewAzureProvider()
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
scopes := []string{"openid", "profile", "email"}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.BuildAuthParams(baseParams, scopes)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAzureProvider_ValidateTokens(b *testing.B) {
|
||||
provider := NewAzureProvider()
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "valid.access.token",
|
||||
idToken: "valid.id.token",
|
||||
refreshToken: "refresh-token",
|
||||
}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{
|
||||
claims: map[string]map[string]interface{}{
|
||||
"valid.access.token": {
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ func (p *BaseProvider) BuildAuthParams(baseParams url.Values, scopes []string) (
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: scopes,
|
||||
Scopes: deduplicateScopes(scopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -127,6 +127,21 @@ func (p *BaseProvider) HandleTokenRefresh(tokenData *TokenResult) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// deduplicateScopes removes duplicate scopes from a slice while preserving order.
|
||||
func deduplicateScopes(scopes []string) []string {
|
||||
seen := make(map[string]bool)
|
||||
result := make([]string, 0, len(scopes))
|
||||
|
||||
for _, scope := range scopes {
|
||||
if !seen[scope] {
|
||||
seen[scope] = true
|
||||
result = append(result, scope)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// ValidateConfig checks provider-specific configuration requirements.
|
||||
// By default, it assumes the configuration is valid.
|
||||
func (p *BaseProvider) ValidateConfig() error {
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Mock implementations for testing
|
||||
type mockSession struct {
|
||||
authenticated bool
|
||||
idToken string
|
||||
accessToken string
|
||||
refreshToken string
|
||||
}
|
||||
|
||||
func (s *mockSession) GetIDToken() string { return s.idToken }
|
||||
func (s *mockSession) GetAccessToken() string { return s.accessToken }
|
||||
func (s *mockSession) GetRefreshToken() string { return s.refreshToken }
|
||||
func (s *mockSession) GetAuthenticated() bool { return s.authenticated }
|
||||
|
||||
type mockTokenVerifier struct {
|
||||
error error
|
||||
}
|
||||
|
||||
func (v *mockTokenVerifier) VerifyToken(token string) error {
|
||||
return v.error
|
||||
}
|
||||
|
||||
type mockTokenCache struct {
|
||||
claims map[string]map[string]interface{}
|
||||
}
|
||||
|
||||
func (c *mockTokenCache) Get(key string) (map[string]interface{}, bool) {
|
||||
claims, exists := c.claims[key]
|
||||
return claims, exists
|
||||
}
|
||||
|
||||
// TestBaseProvider_GetType tests the default provider type
|
||||
func TestBaseProvider_GetType(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeGeneric {
|
||||
t.Errorf("Expected ProviderTypeGeneric, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_GetCapabilities tests the default capabilities
|
||||
func TestBaseProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be true")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokens_Unauthenticated tests validation when not authenticated
|
||||
func TestBaseProvider_ValidateTokens_Unauthenticated(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{authenticated: false}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
refreshToken string
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "No refresh token",
|
||||
refreshToken: "",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Has refresh token",
|
||||
refreshToken: "refresh-token",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
session.refreshToken = tt.refreshToken
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokens_AuthenticatedNoAccessToken tests authenticated session without access token
|
||||
func TestBaseProvider_ValidateTokens_AuthenticatedNoAccessToken(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "", // No access token
|
||||
}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
refreshToken string
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "No access token, no refresh token",
|
||||
refreshToken: "",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No access token, has refresh token",
|
||||
refreshToken: "refresh-token",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
session.refreshToken = tt.refreshToken
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokens_AuthenticatedNoIDToken tests authenticated session without ID token
|
||||
func TestBaseProvider_ValidateTokens_AuthenticatedNoIDToken(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "access-token",
|
||||
idToken: "", // No ID token
|
||||
}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
refreshToken string
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "No ID token, no refresh token",
|
||||
refreshToken: "",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No ID token, has refresh token",
|
||||
refreshToken: "refresh-token",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
session.refreshToken = tt.refreshToken
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokens_TokenVerificationFailure tests token verification failures
|
||||
func TestBaseProvider_ValidateTokens_TokenVerificationFailure(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
accessToken: "access-token",
|
||||
idToken: "id-token",
|
||||
}
|
||||
cache := &mockTokenCache{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
verifierError error
|
||||
refreshToken string
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "Token expired, has refresh token",
|
||||
verifierError: errors.New("token has expired"),
|
||||
refreshToken: "refresh-token",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Token expired, no refresh token",
|
||||
verifierError: errors.New("token has expired"),
|
||||
refreshToken: "",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Other verification error, has refresh token",
|
||||
verifierError: errors.New("invalid signature"),
|
||||
refreshToken: "refresh-token",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Other verification error, no refresh token",
|
||||
verifierError: errors.New("invalid signature"),
|
||||
refreshToken: "",
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
verifier := &mockTokenVerifier{error: tt.verifierError}
|
||||
session.refreshToken = tt.refreshToken
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokenExpiry tests token expiry validation logic
|
||||
func TestBaseProvider_ValidateTokenExpiry(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{refreshToken: "refresh-token"}
|
||||
|
||||
now := time.Now()
|
||||
gracePeriod := 5 * time.Minute
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
claims map[string]interface{}
|
||||
cacheFound bool
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "Token not found in cache, has refresh token",
|
||||
claims: nil,
|
||||
cacheFound: false,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Claims without exp, has refresh token",
|
||||
claims: map[string]interface{}{"sub": "user123"},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Token expired (beyond grace period), has refresh token",
|
||||
claims: map[string]interface{}{
|
||||
"exp": float64(now.Add(-10 * time.Minute).Unix()),
|
||||
},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Token expires within grace period, has refresh token",
|
||||
claims: map[string]interface{}{
|
||||
"exp": float64(now.Add(2 * time.Minute).Unix()),
|
||||
},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Token valid (beyond grace period)",
|
||||
claims: map[string]interface{}{
|
||||
"exp": float64(now.Add(10 * time.Minute).Unix()),
|
||||
},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cache := &mockTokenCache{claims: make(map[string]map[string]interface{})}
|
||||
if tt.cacheFound {
|
||||
cache.claims["test-token"] = tt.claims
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokenExpiry(session, "test-token", cache, gracePeriod)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateTokenExpiry_NoRefreshToken tests expiry validation without refresh token
|
||||
func TestBaseProvider_ValidateTokenExpiry_NoRefreshToken(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{refreshToken: ""} // No refresh token
|
||||
|
||||
now := time.Now()
|
||||
gracePeriod := 5 * time.Minute
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
claims map[string]interface{}
|
||||
cacheFound bool
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "Token not found in cache, no refresh token",
|
||||
claims: nil,
|
||||
cacheFound: false,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Claims without exp, no refresh token",
|
||||
claims: map[string]interface{}{"sub": "user123"},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Token expires within grace period, no refresh token",
|
||||
claims: map[string]interface{}{
|
||||
"exp": float64(now.Add(2 * time.Minute).Unix()),
|
||||
},
|
||||
cacheFound: true,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cache := &mockTokenCache{claims: make(map[string]map[string]interface{})}
|
||||
if tt.cacheFound {
|
||||
cache.claims["test-token"] = tt.claims
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokenExpiry(session, "test-token", cache, gracePeriod)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_BuildAuthParams tests authorization parameter building
|
||||
func TestBaseProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "No existing offline_access scope",
|
||||
scopes: []string{"openid", "profile", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "email", "offline_access"},
|
||||
},
|
||||
{
|
||||
name: "Existing offline_access scope",
|
||||
scopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
},
|
||||
{
|
||||
name: "Empty scopes",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"offline_access"},
|
||||
},
|
||||
{
|
||||
name: "Only offline_access",
|
||||
scopes: []string{"offline_access"},
|
||||
expectedScopes: []string{"offline_access"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseParams := make(map[string][]string)
|
||||
baseParams["client_id"] = []string{"test-client"}
|
||||
|
||||
result, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(result.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(tt.expectedScopes), len(result.Scopes))
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range result.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in result", expectedScope)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify base parameters are preserved
|
||||
if result.URLValues.Get("client_id") != "test-client" {
|
||||
t.Errorf("Expected client_id 'test-client', got '%s'", result.URLValues.Get("client_id"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_HandleTokenRefresh tests token refresh handling
|
||||
func TestBaseProvider_HandleTokenRefresh(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
tokenData := &TokenResult{
|
||||
IDToken: "new-id-token",
|
||||
AccessToken: "new-access-token",
|
||||
RefreshToken: "new-refresh-token",
|
||||
}
|
||||
|
||||
// Base provider should do nothing and return no error
|
||||
err := provider.HandleTokenRefresh(tokenData)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseProvider_ValidateConfig tests configuration validation
|
||||
func TestBaseProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
|
||||
// Base provider should always return valid configuration
|
||||
err := provider.ValidateConfig()
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewBaseProvider tests the constructor
|
||||
func TestNewBaseProvider(t *testing.T) {
|
||||
provider := NewBaseProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
// Verify it implements the OIDCProvider interface
|
||||
var _ OIDCProvider = provider
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkBaseProvider_ValidateTokens(b *testing.B) {
|
||||
provider := NewBaseProvider()
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "test-token",
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{
|
||||
claims: map[string]map[string]interface{}{
|
||||
"test-token": {
|
||||
"exp": float64(time.Now().Add(10 * time.Minute).Unix()),
|
||||
"sub": "user123",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.ValidateTokens(session, verifier, cache, time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBaseProvider_BuildAuthParams(b *testing.B) {
|
||||
provider := NewBaseProvider()
|
||||
baseParams := make(map[string][]string)
|
||||
baseParams["client_id"] = []string{"test-client"}
|
||||
scopes := []string{"openid", "profile", "email"}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.BuildAuthParams(baseParams, scopes)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,12 @@ func NewProviderFactory() *ProviderFactory {
|
||||
registry.RegisterProvider(NewGenericProvider())
|
||||
registry.RegisterProvider(NewGoogleProvider())
|
||||
registry.RegisterProvider(NewAzureProvider())
|
||||
registry.RegisterProvider(NewGitHubProvider())
|
||||
registry.RegisterProvider(NewAuth0Provider())
|
||||
registry.RegisterProvider(NewOktaProvider())
|
||||
registry.RegisterProvider(NewKeycloakProvider())
|
||||
registry.RegisterProvider(NewAWSCognitoProvider())
|
||||
registry.RegisterProvider(NewGitLabProvider())
|
||||
|
||||
return &ProviderFactory{
|
||||
registry: registry,
|
||||
@@ -31,10 +37,16 @@ func (f *ProviderFactory) CreateProvider(issuerURL string) (OIDCProvider, error)
|
||||
return nil, fmt.Errorf("issuer URL cannot be empty")
|
||||
}
|
||||
|
||||
if _, err := url.Parse(issuerURL); err != nil {
|
||||
parsedURL, err := url.Parse(issuerURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid issuer URL format: %w", err)
|
||||
}
|
||||
|
||||
// Check if the URL has a valid scheme and host
|
||||
if parsedURL.Scheme == "" || parsedURL.Host == "" {
|
||||
return nil, fmt.Errorf("invalid issuer URL format: URL must have a valid scheme and host")
|
||||
}
|
||||
|
||||
provider := f.registry.DetectProvider(issuerURL)
|
||||
if provider == nil {
|
||||
return nil, fmt.Errorf("unable to detect provider for issuer URL: %s", issuerURL)
|
||||
@@ -59,6 +71,18 @@ func (f *ProviderFactory) CreateProviderByType(providerType ProviderType) (OIDCP
|
||||
provider = NewGoogleProvider()
|
||||
case ProviderTypeAzure:
|
||||
provider = NewAzureProvider()
|
||||
case ProviderTypeGitHub:
|
||||
provider = NewGitHubProvider()
|
||||
case ProviderTypeAuth0:
|
||||
provider = NewAuth0Provider()
|
||||
case ProviderTypeOkta:
|
||||
provider = NewOktaProvider()
|
||||
case ProviderTypeKeycloak:
|
||||
provider = NewKeycloakProvider()
|
||||
case ProviderTypeAWSCognito:
|
||||
provider = NewAWSCognitoProvider()
|
||||
case ProviderTypeGitLab:
|
||||
provider = NewGitLabProvider()
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported provider type: %d", providerType)
|
||||
}
|
||||
@@ -73,9 +97,15 @@ func (f *ProviderFactory) CreateProviderByType(providerType ProviderType) (OIDCP
|
||||
// GetSupportedProviders returns a list of all supported provider types and their detection patterns.
|
||||
func (f *ProviderFactory) GetSupportedProviders() map[ProviderType][]string {
|
||||
return map[ProviderType][]string{
|
||||
ProviderTypeGeneric: {"*"},
|
||||
ProviderTypeGoogle: {"accounts.google.com"},
|
||||
ProviderTypeAzure: {"login.microsoftonline.com", "sts.windows.net"},
|
||||
ProviderTypeGeneric: {"*"},
|
||||
ProviderTypeGoogle: {"accounts.google.com"},
|
||||
ProviderTypeAzure: {"login.microsoftonline.com", "sts.windows.net"},
|
||||
ProviderTypeGitHub: {"github.com"},
|
||||
ProviderTypeAuth0: {".auth0.com"},
|
||||
ProviderTypeOkta: {".okta.com", ".oktapreview.com", ".okta-emea.com"},
|
||||
ProviderTypeKeycloak: {"keycloak"},
|
||||
ProviderTypeAWSCognito: {"cognito-idp", ".amazonaws.com"},
|
||||
ProviderTypeGitLab: {"gitlab.com"},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +130,11 @@ func (f *ProviderFactory) IsProviderSupported(issuerURL string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if the URL has a valid scheme and host
|
||||
if normalizedURL.Scheme == "" || normalizedURL.Host == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
host := strings.ToLower(normalizedURL.Host)
|
||||
supportedProviders := f.GetSupportedProviders()
|
||||
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestProviderFactory_NewProviderFactory tests the factory constructor
|
||||
func TestProviderFactory_NewProviderFactory(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
if factory == nil {
|
||||
t.Fatal("Expected factory to be created, got nil")
|
||||
}
|
||||
|
||||
if factory.registry == nil {
|
||||
t.Error("Expected registry to be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_CreateProvider tests provider creation by issuer URL
|
||||
func TestProviderFactory_CreateProvider(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
expectedType ProviderType
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "Google provider",
|
||||
issuerURL: "https://accounts.google.com",
|
||||
expectedType: ProviderTypeGoogle,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Google provider with path",
|
||||
issuerURL: "https://accounts.google.com/oauth2",
|
||||
expectedType: ProviderTypeGoogle,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Azure provider - login.microsoftonline.com",
|
||||
issuerURL: "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
expectedType: ProviderTypeAzure,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Azure provider - sts.windows.net",
|
||||
issuerURL: "https://sts.windows.net/tenant-id",
|
||||
expectedType: ProviderTypeAzure,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "GitHub provider",
|
||||
issuerURL: "https://github.com/login/oauth",
|
||||
expectedType: ProviderTypeGitHub,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Auth0 provider",
|
||||
issuerURL: "https://tenant.auth0.com",
|
||||
expectedType: ProviderTypeAuth0,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Okta provider",
|
||||
issuerURL: "https://tenant.okta.com",
|
||||
expectedType: ProviderTypeOkta,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Okta preview provider",
|
||||
issuerURL: "https://tenant.oktapreview.com",
|
||||
expectedType: ProviderTypeOkta,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Keycloak provider",
|
||||
issuerURL: "https://auth.example.com/auth/realms/master",
|
||||
expectedType: ProviderTypeKeycloak,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "AWS Cognito provider",
|
||||
issuerURL: "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example",
|
||||
expectedType: ProviderTypeAWSCognito,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "GitLab provider",
|
||||
issuerURL: "https://gitlab.com/oauth",
|
||||
expectedType: ProviderTypeGitLab,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Generic provider",
|
||||
issuerURL: "https://auth.example.com",
|
||||
expectedType: ProviderTypeGeneric,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Empty issuer URL",
|
||||
issuerURL: "",
|
||||
wantErr: true,
|
||||
errMsg: "issuer URL cannot be empty",
|
||||
},
|
||||
{
|
||||
name: "Invalid URL format",
|
||||
issuerURL: "not-a-url",
|
||||
wantErr: true,
|
||||
errMsg: "invalid issuer URL format",
|
||||
},
|
||||
{
|
||||
name: "URL without scheme",
|
||||
issuerURL: "example.com",
|
||||
wantErr: true,
|
||||
errMsg: "invalid issuer URL format",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
provider, err := factory.CreateProvider(tt.issuerURL)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("Expected error but got none")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("Expected error containing '%s', got '%s'", tt.errMsg, err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.GetType() != tt.expectedType {
|
||||
t.Errorf("Expected provider type %v, got %v", tt.expectedType, provider.GetType())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_CreateProviderByType tests provider creation by type
|
||||
func TestProviderFactory_CreateProviderByType(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
providerType ProviderType
|
||||
expectedType ProviderType
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "Generic provider",
|
||||
providerType: ProviderTypeGeneric,
|
||||
expectedType: ProviderTypeGeneric,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Google provider",
|
||||
providerType: ProviderTypeGoogle,
|
||||
expectedType: ProviderTypeGoogle,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Azure provider",
|
||||
providerType: ProviderTypeAzure,
|
||||
expectedType: ProviderTypeAzure,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "GitHub provider",
|
||||
providerType: ProviderTypeGitHub,
|
||||
expectedType: ProviderTypeGitHub,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Auth0 provider",
|
||||
providerType: ProviderTypeAuth0,
|
||||
expectedType: ProviderTypeAuth0,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Okta provider",
|
||||
providerType: ProviderTypeOkta,
|
||||
expectedType: ProviderTypeOkta,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Keycloak provider",
|
||||
providerType: ProviderTypeKeycloak,
|
||||
expectedType: ProviderTypeKeycloak,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "AWS Cognito provider",
|
||||
providerType: ProviderTypeAWSCognito,
|
||||
expectedType: ProviderTypeAWSCognito,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "GitLab provider",
|
||||
providerType: ProviderTypeGitLab,
|
||||
expectedType: ProviderTypeGitLab,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid provider type",
|
||||
providerType: ProviderType(999),
|
||||
wantErr: true,
|
||||
errMsg: "unsupported provider type",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
provider, err := factory.CreateProviderByType(tt.providerType)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("Expected error but got none")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("Expected error containing '%s', got '%s'", tt.errMsg, err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.GetType() != tt.expectedType {
|
||||
t.Errorf("Expected provider type %v, got %v", tt.expectedType, provider.GetType())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_GetSupportedProviders tests listing supported providers
|
||||
func TestProviderFactory_GetSupportedProviders(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
supported := factory.GetSupportedProviders()
|
||||
|
||||
// Verify expected provider types are present
|
||||
expectedTypes := []ProviderType{
|
||||
ProviderTypeGeneric,
|
||||
ProviderTypeGoogle,
|
||||
ProviderTypeAzure,
|
||||
}
|
||||
|
||||
for _, expectedType := range expectedTypes {
|
||||
if _, exists := supported[expectedType]; !exists {
|
||||
t.Errorf("Expected provider type %v to be supported", expectedType)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify Google patterns
|
||||
googlePatterns := supported[ProviderTypeGoogle]
|
||||
if len(googlePatterns) != 1 || googlePatterns[0] != "accounts.google.com" {
|
||||
t.Errorf("Expected Google patterns ['accounts.google.com'], got %v", googlePatterns)
|
||||
}
|
||||
|
||||
// Verify Azure patterns
|
||||
azurePatterns := supported[ProviderTypeAzure]
|
||||
expectedAzurePatterns := []string{"login.microsoftonline.com", "sts.windows.net"}
|
||||
if len(azurePatterns) != len(expectedAzurePatterns) {
|
||||
t.Errorf("Expected %d Azure patterns, got %d", len(expectedAzurePatterns), len(azurePatterns))
|
||||
}
|
||||
|
||||
for _, expectedPattern := range expectedAzurePatterns {
|
||||
found := false
|
||||
for _, pattern := range azurePatterns {
|
||||
if pattern == expectedPattern {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected Azure pattern '%s' not found", expectedPattern)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify Generic patterns
|
||||
genericPatterns := supported[ProviderTypeGeneric]
|
||||
if len(genericPatterns) != 1 || genericPatterns[0] != "*" {
|
||||
t.Errorf("Expected Generic patterns ['*'], got %v", genericPatterns)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_DetectProviderType tests provider type detection
|
||||
func TestProviderFactory_DetectProviderType(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
expectedType ProviderType
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Google provider detection",
|
||||
issuerURL: "https://accounts.google.com",
|
||||
expectedType: ProviderTypeGoogle,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Azure provider detection",
|
||||
issuerURL: "https://login.microsoftonline.com/tenant/v2.0",
|
||||
expectedType: ProviderTypeAzure,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Generic provider detection",
|
||||
issuerURL: "https://auth.example.com",
|
||||
expectedType: ProviderTypeGeneric,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid URL",
|
||||
issuerURL: "not-a-url",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Empty URL",
|
||||
issuerURL: "",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
providerType, err := factory.DetectProviderType(tt.issuerURL)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("Expected error but got none")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if providerType != tt.expectedType {
|
||||
t.Errorf("Expected provider type %v, got %v", tt.expectedType, providerType)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_IsProviderSupported tests provider support checking
|
||||
func TestProviderFactory_IsProviderSupported(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "Google provider supported",
|
||||
issuerURL: "https://accounts.google.com",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Google provider with subdomain supported",
|
||||
issuerURL: "https://accounts.google.com/oauth2",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Azure login.microsoftonline.com supported",
|
||||
issuerURL: "https://login.microsoftonline.com/tenant/v2.0",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Azure sts.windows.net supported",
|
||||
issuerURL: "https://sts.windows.net/tenant",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Generic provider supported (wildcard)",
|
||||
issuerURL: "https://auth.example.com",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Any valid URL supported (wildcard)",
|
||||
issuerURL: "https://custom-auth.company.org",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "Empty URL not supported",
|
||||
issuerURL: "",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid URL format not supported",
|
||||
issuerURL: "not-a-url",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "URL without scheme not supported",
|
||||
issuerURL: "example.com",
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := factory.IsProviderSupported(tt.issuerURL)
|
||||
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderFactory_IntegrationTest tests the full flow
|
||||
func TestProviderFactory_IntegrationTest(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
// Test Google provider flow
|
||||
t.Run("Google Provider Flow", func(t *testing.T) {
|
||||
// Check if supported
|
||||
if !factory.IsProviderSupported("https://accounts.google.com") {
|
||||
t.Error("Google provider should be supported")
|
||||
}
|
||||
|
||||
// Detect type
|
||||
providerType, err := factory.DetectProviderType("https://accounts.google.com")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error detecting Google provider: %v", err)
|
||||
}
|
||||
if providerType != ProviderTypeGoogle {
|
||||
t.Errorf("Expected ProviderTypeGoogle, got %v", providerType)
|
||||
}
|
||||
|
||||
// Create provider by URL
|
||||
provider, err := factory.CreateProvider("https://accounts.google.com")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error creating Google provider: %v", err)
|
||||
}
|
||||
if provider.GetType() != ProviderTypeGoogle {
|
||||
t.Errorf("Expected ProviderTypeGoogle, got %v", provider.GetType())
|
||||
}
|
||||
|
||||
// Create provider by type
|
||||
provider2, err := factory.CreateProviderByType(ProviderTypeGoogle)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error creating Google provider by type: %v", err)
|
||||
}
|
||||
if provider2.GetType() != ProviderTypeGoogle {
|
||||
t.Errorf("Expected ProviderTypeGoogle, got %v", provider2.GetType())
|
||||
}
|
||||
})
|
||||
|
||||
// Test Azure provider flow
|
||||
t.Run("Azure Provider Flow", func(t *testing.T) {
|
||||
azureURL := "https://login.microsoftonline.com/tenant/v2.0"
|
||||
|
||||
// Check if supported
|
||||
if !factory.IsProviderSupported(azureURL) {
|
||||
t.Error("Azure provider should be supported")
|
||||
}
|
||||
|
||||
// Detect type
|
||||
providerType, err := factory.DetectProviderType(azureURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error detecting Azure provider: %v", err)
|
||||
}
|
||||
if providerType != ProviderTypeAzure {
|
||||
t.Errorf("Expected ProviderTypeAzure, got %v", providerType)
|
||||
}
|
||||
|
||||
// Create provider
|
||||
provider, err := factory.CreateProvider(azureURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error creating Azure provider: %v", err)
|
||||
}
|
||||
if provider.GetType() != ProviderTypeAzure {
|
||||
t.Errorf("Expected ProviderTypeAzure, got %v", provider.GetType())
|
||||
}
|
||||
})
|
||||
|
||||
// Test Generic provider flow
|
||||
t.Run("Generic Provider Flow", func(t *testing.T) {
|
||||
genericURL := "https://auth.custom-provider.com"
|
||||
|
||||
// Check if supported
|
||||
if !factory.IsProviderSupported(genericURL) {
|
||||
t.Error("Generic provider should be supported")
|
||||
}
|
||||
|
||||
// Detect type
|
||||
providerType, err := factory.DetectProviderType(genericURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error detecting generic provider: %v", err)
|
||||
}
|
||||
if providerType != ProviderTypeGeneric {
|
||||
t.Errorf("Expected ProviderTypeGeneric, got %v", providerType)
|
||||
}
|
||||
|
||||
// Create provider
|
||||
provider, err := factory.CreateProvider(genericURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error creating generic provider: %v", err)
|
||||
}
|
||||
if provider.GetType() != ProviderTypeGeneric {
|
||||
t.Errorf("Expected ProviderTypeGeneric, got %v", provider.GetType())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestProviderFactory_CaseInsensitiveHostMatching tests case insensitive host matching
|
||||
func TestProviderFactory_CaseInsensitiveHostMatching(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
expectedType ProviderType
|
||||
}{
|
||||
{
|
||||
name: "Google with uppercase",
|
||||
issuerURL: "https://ACCOUNTS.GOOGLE.COM",
|
||||
expectedType: ProviderTypeGoogle,
|
||||
},
|
||||
{
|
||||
name: "Google with mixed case",
|
||||
issuerURL: "https://Accounts.Google.Com",
|
||||
expectedType: ProviderTypeGoogle,
|
||||
},
|
||||
{
|
||||
name: "Azure with uppercase",
|
||||
issuerURL: "https://LOGIN.MICROSOFTONLINE.COM/tenant",
|
||||
expectedType: ProviderTypeAzure,
|
||||
},
|
||||
{
|
||||
name: "Azure STS with mixed case",
|
||||
issuerURL: "https://Sts.Windows.Net/tenant",
|
||||
expectedType: ProviderTypeAzure,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Should be supported
|
||||
if !factory.IsProviderSupported(tt.issuerURL) {
|
||||
t.Errorf("URL %s should be supported", tt.issuerURL)
|
||||
}
|
||||
|
||||
// Should detect correct type
|
||||
providerType, err := factory.DetectProviderType(tt.issuerURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
if providerType != tt.expectedType {
|
||||
t.Errorf("Expected %v, got %v", tt.expectedType, providerType)
|
||||
}
|
||||
|
||||
// Should create correct provider
|
||||
provider, err := factory.CreateProvider(tt.issuerURL)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
if provider.GetType() != tt.expectedType {
|
||||
t.Errorf("Expected %v, got %v", tt.expectedType, provider.GetType())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkProviderFactory_CreateProvider(b *testing.B) {
|
||||
factory := NewProviderFactory()
|
||||
issuerURL := "https://accounts.google.com"
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
factory.CreateProvider(issuerURL)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkProviderFactory_IsProviderSupported(b *testing.B) {
|
||||
factory := NewProviderFactory()
|
||||
issuerURL := "https://auth.example.com"
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
factory.IsProviderSupported(issuerURL)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkProviderFactory_DetectProviderType(b *testing.B) {
|
||||
factory := NewProviderFactory()
|
||||
issuerURL := "https://login.microsoftonline.com/tenant"
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
factory.DetectProviderType(issuerURL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGenericProvider_NewGenericProvider tests the constructor
|
||||
func TestGenericProvider_NewGenericProvider(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenericProvider_GetType tests provider type
|
||||
func TestGenericProvider_GetType(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeGeneric {
|
||||
t.Errorf("Expected ProviderTypeGeneric, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenericProvider_GetCapabilities tests that it inherits BaseProvider capabilities
|
||||
func TestGenericProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
// Should have the same capabilities as BaseProvider
|
||||
baseProvider := NewBaseProvider()
|
||||
baseCapabilities := baseProvider.GetCapabilities()
|
||||
|
||||
if capabilities.SupportsRefreshTokens != baseCapabilities.SupportsRefreshTokens {
|
||||
t.Errorf("Expected SupportsRefreshTokens %v, got %v",
|
||||
baseCapabilities.SupportsRefreshTokens, capabilities.SupportsRefreshTokens)
|
||||
}
|
||||
|
||||
if capabilities.RequiresOfflineAccessScope != baseCapabilities.RequiresOfflineAccessScope {
|
||||
t.Errorf("Expected RequiresOfflineAccessScope %v, got %v",
|
||||
baseCapabilities.RequiresOfflineAccessScope, capabilities.RequiresOfflineAccessScope)
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != baseCapabilities.PreferredTokenValidation {
|
||||
t.Errorf("Expected PreferredTokenValidation %v, got %v",
|
||||
baseCapabilities.PreferredTokenValidation, capabilities.PreferredTokenValidation)
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent != baseCapabilities.RequiresPromptConsent {
|
||||
t.Errorf("Expected RequiresPromptConsent %v, got %v",
|
||||
baseCapabilities.RequiresPromptConsent, capabilities.RequiresPromptConsent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenericProvider_InterfaceCompliance tests that Generic provider implements OIDCProvider
|
||||
func TestGenericProvider_InterfaceCompliance(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
// Verify it implements the OIDCProvider interface
|
||||
var _ OIDCProvider = provider
|
||||
}
|
||||
|
||||
// TestGenericProvider_InheritsBaseProviderBehavior tests inherited functionality
|
||||
func TestGenericProvider_InheritsBaseProviderBehavior(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
baseProvider := NewBaseProvider()
|
||||
|
||||
// Test BuildAuthParams behavior is the same
|
||||
scopes := []string{"openid", "profile", "email"}
|
||||
baseParams := make(map[string][]string)
|
||||
baseParams["client_id"] = []string{"test-client"}
|
||||
|
||||
genericResult, genericErr := provider.BuildAuthParams(baseParams, scopes)
|
||||
baseResult, baseErr := baseProvider.BuildAuthParams(baseParams, scopes)
|
||||
|
||||
if (genericErr == nil) != (baseErr == nil) {
|
||||
t.Errorf("BuildAuthParams error mismatch: generic=%v, base=%v", genericErr, baseErr)
|
||||
}
|
||||
|
||||
if genericErr == nil && baseErr == nil {
|
||||
// Compare scopes length (offline_access should be added)
|
||||
if len(genericResult.Scopes) != len(baseResult.Scopes) {
|
||||
t.Errorf("BuildAuthParams scope count mismatch: generic=%d, base=%d",
|
||||
len(genericResult.Scopes), len(baseResult.Scopes))
|
||||
}
|
||||
|
||||
// Verify offline_access is added in both cases
|
||||
genericHasOffline := false
|
||||
baseHasOffline := false
|
||||
|
||||
for _, scope := range genericResult.Scopes {
|
||||
if scope == "offline_access" {
|
||||
genericHasOffline = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for _, scope := range baseResult.Scopes {
|
||||
if scope == "offline_access" {
|
||||
baseHasOffline = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if genericHasOffline != baseHasOffline {
|
||||
t.Errorf("offline_access scope handling mismatch: generic=%v, base=%v",
|
||||
genericHasOffline, baseHasOffline)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ValidateConfig behavior is the same
|
||||
genericConfigErr := provider.ValidateConfig()
|
||||
baseConfigErr := baseProvider.ValidateConfig()
|
||||
|
||||
if (genericConfigErr == nil) != (baseConfigErr == nil) {
|
||||
t.Errorf("ValidateConfig error mismatch: generic=%v, base=%v", genericConfigErr, baseConfigErr)
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh behavior is the same
|
||||
tokenData := &TokenResult{IDToken: "test-token"}
|
||||
genericRefreshErr := provider.HandleTokenRefresh(tokenData)
|
||||
baseRefreshErr := baseProvider.HandleTokenRefresh(tokenData)
|
||||
|
||||
if (genericRefreshErr == nil) != (baseRefreshErr == nil) {
|
||||
t.Errorf("HandleTokenRefresh error mismatch: generic=%v, base=%v",
|
||||
genericRefreshErr, baseRefreshErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenericProvider_ValidateTokens tests token validation inheritance
|
||||
func TestGenericProvider_ValidateTokens(t *testing.T) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
session *mockSession
|
||||
verifierError error
|
||||
expectedResult ValidationResult
|
||||
}{
|
||||
{
|
||||
name: "Unauthenticated with refresh token",
|
||||
session: &mockSession{
|
||||
authenticated: false,
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Authenticated with valid tokens",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "valid-token",
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: nil,
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: true,
|
||||
NeedsRefresh: false,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Authenticated with invalid token, has refresh",
|
||||
session: &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "invalid-token",
|
||||
refreshToken: "refresh-token",
|
||||
},
|
||||
verifierError: &testError{"token expired"},
|
||||
expectedResult: ValidationResult{
|
||||
Authenticated: false,
|
||||
NeedsRefresh: true,
|
||||
IsExpired: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
verifier := &mockTokenVerifier{error: tt.verifierError}
|
||||
cache := &mockTokenCache{
|
||||
claims: map[string]map[string]interface{}{
|
||||
"valid-token": {
|
||||
"exp": float64(9999999999), // Far future
|
||||
"sub": "user123",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokens(tt.session, verifier, cache, 0)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if result.Authenticated != tt.expectedResult.Authenticated {
|
||||
t.Errorf("Expected Authenticated %v, got %v", tt.expectedResult.Authenticated, result.Authenticated)
|
||||
}
|
||||
|
||||
if result.NeedsRefresh != tt.expectedResult.NeedsRefresh {
|
||||
t.Errorf("Expected NeedsRefresh %v, got %v", tt.expectedResult.NeedsRefresh, result.NeedsRefresh)
|
||||
}
|
||||
|
||||
if result.IsExpired != tt.expectedResult.IsExpired {
|
||||
t.Errorf("Expected IsExpired %v, got %v", tt.expectedResult.IsExpired, result.IsExpired)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkGenericProvider_GetType(b *testing.B) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.GetType()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGenericProvider_GetCapabilities(b *testing.B) {
|
||||
provider := NewGenericProvider()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.GetCapabilities()
|
||||
}
|
||||
}
|
||||
|
||||
// Test error type for testing
|
||||
type testError struct {
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *testError) Error() string {
|
||||
return e.message
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// GitHubProvider encapsulates GitHub-specific OIDC logic.
|
||||
type GitHubProvider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewGitHubProvider creates a new instance of the GitHubProvider.
|
||||
func NewGitHubProvider() *GitHubProvider {
|
||||
return &GitHubProvider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *GitHubProvider) GetType() ProviderType {
|
||||
return ProviderTypeGitHub
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the GitHub provider.
|
||||
// WARNING: GitHub does NOT support OpenID Connect - it's OAuth 2.0 only.
|
||||
// This provider should only be used for OAuth flows, not OIDC authentication.
|
||||
func (p *GitHubProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: false, // GitHub OAuth apps don't support refresh tokens
|
||||
RequiresOfflineAccessScope: false, // GitHub doesn't use offline_access
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "access", // GitHub only provides access tokens, no ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures GitHub-specific authentication parameters.
|
||||
func (p *GitHubProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// GitHub doesn't use offline_access scope, so remove it if present
|
||||
var filteredScopes []string
|
||||
for _, scope := range scopes {
|
||||
if scope != "offline_access" {
|
||||
filteredScopes = append(filteredScopes, scope)
|
||||
}
|
||||
}
|
||||
|
||||
// If no scopes specified, use default GitHub scopes for OAuth
|
||||
// Note: GitHub doesn't support 'openid' scope as it's not an OIDC provider
|
||||
if len(filteredScopes) == 0 {
|
||||
filteredScopes = []string{"user:email", "read:user"}
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(filteredScopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GitHub requires specific configuration for proper operation.
|
||||
func (p *GitHubProvider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGitHubProvider_NewGitHubProvider tests the constructor
|
||||
func TestGitHubProvider_NewGitHubProvider(t *testing.T) {
|
||||
provider := NewGitHubProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubProvider_GetType tests provider type
|
||||
func TestGitHubProvider_GetType(t *testing.T) {
|
||||
provider := NewGitHubProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeGitHub {
|
||||
t.Errorf("Expected ProviderTypeGitHub, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubProvider_GetCapabilities tests GitHub-specific capabilities
|
||||
func TestGitHubProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewGitHubProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be false for GitHub")
|
||||
}
|
||||
|
||||
if capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be false for GitHub")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for GitHub")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "access" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'access', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubProvider_BuildAuthParams tests GitHub-specific auth params
|
||||
func TestGitHubProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewGitHubProvider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Remove offline_access scope",
|
||||
scopes: []string{"user:email", "offline_access", "read:user"},
|
||||
expectedScopes: []string{"user:email", "read:user"},
|
||||
},
|
||||
{
|
||||
name: "Default scopes when none provided",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"user:email", "read:user"},
|
||||
},
|
||||
{
|
||||
name: "Keep other scopes",
|
||||
scopes: []string{"user", "repo"},
|
||||
expectedScopes: []string{"user", "repo"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(tt.expectedScopes), len(authParams.Scopes))
|
||||
return
|
||||
}
|
||||
|
||||
for i, scope := range tt.expectedScopes {
|
||||
if authParams.Scopes[i] != scope {
|
||||
t.Errorf("Expected scope '%s', got '%s'", scope, authParams.Scopes[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubProvider_ValidateConfig tests config validation
|
||||
func TestGitHubProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewGitHubProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// GitLabProvider encapsulates GitLab-specific OIDC logic.
|
||||
type GitLabProvider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewGitLabProvider creates a new instance of the GitLabProvider.
|
||||
func NewGitLabProvider() *GitLabProvider {
|
||||
return &GitLabProvider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *GitLabProvider) GetType() ProviderType {
|
||||
return ProviderTypeGitLab
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the GitLab provider.
|
||||
func (p *GitLabProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: false, // GitLab doesn't use offline_access scope
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "id", // GitLab typically uses ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures GitLab-specific authentication parameters.
|
||||
func (p *GitLabProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// GitLab supports standard OAuth 2.0 parameters
|
||||
baseParams.Set("response_type", "code")
|
||||
|
||||
// Remove offline_access scope as GitLab doesn't use it
|
||||
var filteredScopes []string
|
||||
for _, scope := range scopes {
|
||||
if scope != "offline_access" {
|
||||
filteredScopes = append(filteredScopes, scope)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure openid scope is present for OIDC
|
||||
hasOpenID := false
|
||||
for _, scope := range filteredScopes {
|
||||
if scope == "openid" {
|
||||
hasOpenID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOpenID {
|
||||
filteredScopes = append(filteredScopes, "openid")
|
||||
}
|
||||
|
||||
// Default GitLab scopes if none specified
|
||||
if len(filteredScopes) == 1 && filteredScopes[0] == "openid" {
|
||||
filteredScopes = append(filteredScopes, "profile", "email")
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(filteredScopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GitLab requires application configuration and proper redirect URIs.
|
||||
func (p *GitLabProvider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGitLabProvider_NewGitLabProvider tests the constructor
|
||||
func TestGitLabProvider_NewGitLabProvider(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_GetType tests provider type
|
||||
func TestGitLabProvider_GetType(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeGitLab {
|
||||
t.Errorf("Expected ProviderTypeGitLab, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_GetCapabilities tests GitLab-specific capabilities
|
||||
func TestGitLabProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true for GitLab")
|
||||
}
|
||||
|
||||
if capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be false for GitLab")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for GitLab")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_BuildAuthParams tests GitLab-specific auth params
|
||||
func TestGitLabProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Remove offline_access scope and ensure openid",
|
||||
scopes: []string{"read_user", "read_api", "offline_access"},
|
||||
expectedScopes: []string{"read_user", "read_api", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keep existing openid, remove offline_access",
|
||||
scopes: []string{"openid", "read_user", "offline_access", "profile"},
|
||||
expectedScopes: []string{"openid", "read_user", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Add default scopes when only openid",
|
||||
scopes: []string{"openid"},
|
||||
expectedScopes: []string{"openid", "profile", "email"},
|
||||
},
|
||||
{
|
||||
name: "Add openid and defaults when empty",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"openid", "profile", "email"},
|
||||
},
|
||||
{
|
||||
name: "GitLab-specific scopes",
|
||||
scopes: []string{"read_user", "read_api", "read_repository"},
|
||||
expectedScopes: []string{"read_user", "read_api", "read_repository", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that response_type is set
|
||||
if authParams.URLValues.Get("response_type") != "code" {
|
||||
t.Errorf("Expected response_type 'code', got '%s'", authParams.URLValues.Get("response_type"))
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d. Expected: %v, Got: %v",
|
||||
len(tt.expectedScopes), len(authParams.Scopes), tt.expectedScopes, authParams.Scopes)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure offline_access is NOT present
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == "offline_access" {
|
||||
t.Error("offline_access scope should be filtered out for GitLab")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_ValidateConfig tests config validation
|
||||
func TestGitLabProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_InterfaceCompliance tests that GitLab provider implements the OIDCProvider interface
|
||||
func TestGitLabProvider_InterfaceCompliance(t *testing.T) {
|
||||
var _ OIDCProvider = NewGitLabProvider()
|
||||
}
|
||||
|
||||
// TestGitLabProvider_BaseProviderInheritance tests that GitLab provider inherits from BaseProvider correctly
|
||||
func TestGitLabProvider_BaseProviderInheritance(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
|
||||
// Test that it has access to BaseProvider methods
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("Expected BaseProvider to be initialized")
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh (inherited from BaseProvider)
|
||||
err := provider.HandleTokenRefresh(&TokenResult{
|
||||
IDToken: "test-id-token",
|
||||
AccessToken: "test-access-token",
|
||||
RefreshToken: "test-refresh-token",
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("HandleTokenRefresh failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_OfflineAccessFiltering tests that offline_access scope is always filtered out
|
||||
func TestGitLabProvider_OfflineAccessFiltering(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
}{
|
||||
{
|
||||
name: "Single offline_access",
|
||||
scopes: []string{"offline_access"},
|
||||
},
|
||||
{
|
||||
name: "Multiple offline_access occurrences",
|
||||
scopes: []string{"offline_access", "read_user", "offline_access", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Mixed with other scopes",
|
||||
scopes: []string{"read_api", "offline_access", "read_user"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure offline_access is NOT present
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == "offline_access" {
|
||||
t.Error("offline_access scope should be filtered out for GitLab")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_GitLabSpecificScopes tests GitLab-specific scopes
|
||||
func TestGitLabProvider_GitLabSpecificScopes(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
checkFor []string
|
||||
}{
|
||||
{
|
||||
name: "GitLab API scopes",
|
||||
scopes: []string{"read_api", "read_user"},
|
||||
checkFor: []string{"read_api", "read_user", "openid"},
|
||||
},
|
||||
{
|
||||
name: "GitLab repository scopes",
|
||||
scopes: []string{"read_repository", "write_repository"},
|
||||
checkFor: []string{"read_repository", "write_repository", "openid"},
|
||||
},
|
||||
{
|
||||
name: "GitLab admin scopes",
|
||||
scopes: []string{"api", "sudo"},
|
||||
checkFor: []string{"api", "sudo", "openid"},
|
||||
},
|
||||
{
|
||||
name: "GitLab registry scopes",
|
||||
scopes: []string{"read_registry", "write_registry"},
|
||||
checkFor: []string{"read_registry", "write_registry", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.checkFor {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_DefaultScopeHandling tests default scope behavior
|
||||
func TestGitLabProvider_DefaultScopeHandling(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
// Test with only openid scope - should add defaults
|
||||
authParams, err := provider.BuildAuthParams(baseParams, []string{"openid"})
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
expectedScopes := []string{"openid", "profile", "email"}
|
||||
if len(authParams.Scopes) != len(expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(expectedScopes), len(authParams.Scopes))
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected default scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProvider_ScopeDeduplication tests that duplicate scopes are handled correctly
|
||||
func TestGitLabProvider_ScopeDeduplication(t *testing.T) {
|
||||
provider := NewGitLabProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
// Test with duplicate scopes
|
||||
scopes := []string{"openid", "read_user", "openid", "profile", "read_user"}
|
||||
authParams, err := provider.BuildAuthParams(baseParams, scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Count occurrences of each scope
|
||||
scopeCounts := make(map[string]int)
|
||||
for _, scope := range authParams.Scopes {
|
||||
scopeCounts[scope]++
|
||||
}
|
||||
|
||||
// Check that no scope appears more than once
|
||||
for scope, count := range scopeCounts {
|
||||
if count > 1 {
|
||||
t.Errorf("Scope '%s' appears %d times, expected 1", scope, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,8 @@ func (p *GoogleProvider) GetType() ProviderType {
|
||||
// GetCapabilities returns the specific capabilities of the Google provider.
|
||||
func (p *GoogleProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: false,
|
||||
SupportsRefreshTokens: true, // Google DOES support refresh tokens
|
||||
RequiresOfflineAccessScope: false, // Google uses access_type=offline instead
|
||||
RequiresPromptConsent: true,
|
||||
PreferredTokenValidation: "id",
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func (p *GoogleProvider) BuildAuthParams(baseParams url.Values, scopes []string)
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: filteredScopes,
|
||||
Scopes: deduplicateScopes(filteredScopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGoogleProvider_NewGoogleProvider tests the constructor
|
||||
func TestGoogleProvider_NewGoogleProvider(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_GetType tests provider type
|
||||
func TestGoogleProvider_GetType(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeGoogle {
|
||||
t.Errorf("Expected ProviderTypeGoogle, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_GetCapabilities tests Google-specific capabilities
|
||||
func TestGoogleProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true")
|
||||
}
|
||||
|
||||
if capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be false for Google")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be true for Google")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_BuildAuthParams tests Google-specific auth parameters
|
||||
func TestGoogleProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
inputScopes []string
|
||||
expectedScopes []string
|
||||
shouldHaveAccessType bool
|
||||
shouldHavePrompt bool
|
||||
}{
|
||||
{
|
||||
name: "Basic scopes without offline_access",
|
||||
inputScopes: []string{"openid", "profile", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "email"},
|
||||
shouldHaveAccessType: true,
|
||||
shouldHavePrompt: true,
|
||||
},
|
||||
{
|
||||
name: "Scopes with offline_access (should be filtered out)",
|
||||
inputScopes: []string{"openid", "profile", "offline_access", "email"},
|
||||
expectedScopes: []string{"openid", "profile", "email"},
|
||||
shouldHaveAccessType: true,
|
||||
shouldHavePrompt: true,
|
||||
},
|
||||
{
|
||||
name: "Only offline_access scope (should be filtered out)",
|
||||
inputScopes: []string{"offline_access"},
|
||||
expectedScopes: []string{},
|
||||
shouldHaveAccessType: true,
|
||||
shouldHavePrompt: true,
|
||||
},
|
||||
{
|
||||
name: "Empty scopes",
|
||||
inputScopes: []string{},
|
||||
expectedScopes: []string{},
|
||||
shouldHaveAccessType: true,
|
||||
shouldHavePrompt: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
|
||||
result, err := provider.BuildAuthParams(baseParams, tt.inputScopes)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Check Google-specific parameters
|
||||
if tt.shouldHaveAccessType {
|
||||
if result.URLValues.Get("access_type") != "offline" {
|
||||
t.Errorf("Expected access_type 'offline', got '%s'", result.URLValues.Get("access_type"))
|
||||
}
|
||||
}
|
||||
|
||||
if tt.shouldHavePrompt {
|
||||
if result.URLValues.Get("prompt") != "consent" {
|
||||
t.Errorf("Expected prompt 'consent', got '%s'", result.URLValues.Get("prompt"))
|
||||
}
|
||||
}
|
||||
|
||||
// Check filtered scopes
|
||||
if len(result.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d", len(tt.expectedScopes), len(result.Scopes))
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range result.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in result", expectedScope)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure offline_access is not in the result scopes
|
||||
for _, scope := range result.Scopes {
|
||||
if scope == "offline_access" {
|
||||
t.Error("offline_access scope should be filtered out for Google")
|
||||
}
|
||||
}
|
||||
|
||||
// Verify original base parameters are preserved
|
||||
if result.URLValues.Get("client_id") != "test-client" {
|
||||
t.Errorf("Expected client_id 'test-client', got '%s'", result.URLValues.Get("client_id"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_ValidateConfig tests configuration validation
|
||||
func TestGoogleProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_InterfaceCompliance tests that Google provider implements OIDCProvider
|
||||
func TestGoogleProvider_InterfaceCompliance(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
// Verify it implements the OIDCProvider interface
|
||||
var _ OIDCProvider = provider
|
||||
}
|
||||
|
||||
// TestGoogleProvider_OfflineAccessFiltering tests comprehensive offline_access filtering
|
||||
func TestGoogleProvider_OfflineAccessFiltering(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
inputScopes []string
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "Multiple offline_access occurrences",
|
||||
inputScopes: []string{"openid", "offline_access", "profile", "offline_access", "email"},
|
||||
description: "Should remove all instances of offline_access",
|
||||
},
|
||||
{
|
||||
name: "Case sensitive filtering",
|
||||
inputScopes: []string{"openid", "OFFLINE_ACCESS", "profile", "offline_access"},
|
||||
description: "Should only remove exact case matches",
|
||||
},
|
||||
{
|
||||
name: "Similar but different scopes",
|
||||
inputScopes: []string{"openid", "offline_access_extended", "profile", "offline_access"},
|
||||
description: "Should only remove exact offline_access matches",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseParams := make(url.Values)
|
||||
result, err := provider.BuildAuthParams(baseParams, tt.inputScopes)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Count offline_access occurrences in result
|
||||
offlineAccessCount := 0
|
||||
for _, scope := range result.Scopes {
|
||||
if scope == "offline_access" {
|
||||
offlineAccessCount++
|
||||
}
|
||||
}
|
||||
|
||||
if offlineAccessCount != 0 {
|
||||
t.Errorf("Expected 0 offline_access scopes in result, got %d", offlineAccessCount)
|
||||
}
|
||||
|
||||
// Verify other scopes are preserved
|
||||
for _, originalScope := range tt.inputScopes {
|
||||
if originalScope == "offline_access" {
|
||||
continue // Skip the filtered scope
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, resultScope := range result.Scopes {
|
||||
if resultScope == originalScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' to be preserved", originalScope)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_BaseProviderInheritance tests inherited functionality from BaseProvider
|
||||
func TestGoogleProvider_BaseProviderInheritance(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
// Test ValidateTokens (inherited from BaseProvider)
|
||||
session := &mockSession{
|
||||
authenticated: true,
|
||||
idToken: "test-token",
|
||||
accessToken: "access-token", // Add access token for proper validation
|
||||
}
|
||||
verifier := &mockTokenVerifier{}
|
||||
cache := &mockTokenCache{
|
||||
claims: map[string]map[string]interface{}{
|
||||
"test-token": {
|
||||
"exp": float64(9999999999), // Far future
|
||||
"sub": "user123",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result, err := provider.ValidateTokens(session, verifier, cache, 0)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if !result.Authenticated {
|
||||
t.Error("Expected result to be authenticated")
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh (inherited from BaseProvider)
|
||||
tokenData := &TokenResult{IDToken: "new-token"}
|
||||
err = provider.HandleTokenRefresh(tokenData)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoogleProvider_AuthParamsPreservation tests that base parameters are not overwritten
|
||||
func TestGoogleProvider_AuthParamsPreservation(t *testing.T) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
baseParams.Set("redirect_uri", "https://example.com/callback")
|
||||
baseParams.Set("response_type", "code")
|
||||
baseParams.Set("state", "test-state")
|
||||
baseParams.Set("nonce", "test-nonce")
|
||||
|
||||
scopes := []string{"openid", "profile"}
|
||||
|
||||
result, err := provider.BuildAuthParams(baseParams, scopes)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Verify all original parameters are preserved
|
||||
expectedParams := map[string]string{
|
||||
"client_id": "test-client",
|
||||
"redirect_uri": "https://example.com/callback",
|
||||
"response_type": "code",
|
||||
"state": "test-state",
|
||||
"nonce": "test-nonce",
|
||||
"access_type": "offline", // Added by Google provider
|
||||
"prompt": "consent", // Added by Google provider
|
||||
}
|
||||
|
||||
for key, expectedValue := range expectedParams {
|
||||
actualValue := result.URLValues.Get(key)
|
||||
if actualValue != expectedValue {
|
||||
t.Errorf("Expected %s '%s', got '%s'", key, expectedValue, actualValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify scopes
|
||||
if len(result.Scopes) != 2 {
|
||||
t.Errorf("Expected 2 scopes, got %d", len(result.Scopes))
|
||||
}
|
||||
|
||||
expectedScopes := []string{"openid", "profile"}
|
||||
for _, expectedScope := range expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range result.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found", expectedScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkGoogleProvider_BuildAuthParams(b *testing.B) {
|
||||
provider := NewGoogleProvider()
|
||||
baseParams := make(url.Values)
|
||||
baseParams.Set("client_id", "test-client")
|
||||
scopes := []string{"openid", "profile", "email", "offline_access"}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.BuildAuthParams(baseParams, scopes)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGoogleProvider_GetCapabilities(b *testing.B) {
|
||||
provider := NewGoogleProvider()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider.GetCapabilities()
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,12 @@ const (
|
||||
ProviderTypeGeneric ProviderType = iota
|
||||
ProviderTypeGoogle
|
||||
ProviderTypeAzure
|
||||
ProviderTypeGitHub
|
||||
ProviderTypeAuth0
|
||||
ProviderTypeOkta
|
||||
ProviderTypeKeycloak
|
||||
ProviderTypeAWSCognito
|
||||
ProviderTypeGitLab
|
||||
)
|
||||
|
||||
// ProviderCapabilities defines the specific features and behaviors of an OIDC provider.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// KeycloakProvider encapsulates Keycloak-specific OIDC logic.
|
||||
type KeycloakProvider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewKeycloakProvider creates a new instance of the KeycloakProvider.
|
||||
func NewKeycloakProvider() *KeycloakProvider {
|
||||
return &KeycloakProvider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *KeycloakProvider) GetType() ProviderType {
|
||||
return ProviderTypeKeycloak
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the Keycloak provider.
|
||||
func (p *KeycloakProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: true,
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "id", // Keycloak typically uses ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures Keycloak-specific authentication parameters.
|
||||
func (p *KeycloakProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// Keycloak supports standard OIDC parameters
|
||||
baseParams.Set("response_type", "code")
|
||||
|
||||
// Ensure offline_access scope is present for refresh tokens
|
||||
hasOfflineAccess := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "offline_access" {
|
||||
hasOfflineAccess = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOfflineAccess {
|
||||
scopes = append(scopes, "offline_access")
|
||||
}
|
||||
|
||||
// Ensure openid scope is present
|
||||
hasOpenID := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "openid" {
|
||||
hasOpenID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOpenID {
|
||||
scopes = append(scopes, "openid")
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(scopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Keycloak requires realm and server configuration.
|
||||
func (p *KeycloakProvider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestKeycloakProvider_NewKeycloakProvider tests the constructor
|
||||
func TestKeycloakProvider_NewKeycloakProvider(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_GetType tests provider type
|
||||
func TestKeycloakProvider_GetType(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeKeycloak {
|
||||
t.Errorf("Expected ProviderTypeKeycloak, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_GetCapabilities tests Keycloak-specific capabilities
|
||||
func TestKeycloakProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true for Keycloak")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be true for Keycloak")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for Keycloak")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_BuildAuthParams tests Keycloak-specific auth params
|
||||
func TestKeycloakProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Add offline_access and openid scopes",
|
||||
scopes: []string{"roles", "groups"},
|
||||
expectedScopes: []string{"roles", "groups", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keep existing offline_access and openid",
|
||||
scopes: []string{"openid", "roles", "offline_access", "groups"},
|
||||
expectedScopes: []string{"openid", "roles", "offline_access", "groups"},
|
||||
},
|
||||
{
|
||||
name: "Add both scopes when none provided",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keycloak custom scopes",
|
||||
scopes: []string{"realm-roles", "account"},
|
||||
expectedScopes: []string{"realm-roles", "account", "offline_access", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that response_type is set
|
||||
if authParams.URLValues.Get("response_type") != "code" {
|
||||
t.Errorf("Expected response_type 'code', got '%s'", authParams.URLValues.Get("response_type"))
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d. Expected: %v, Got: %v",
|
||||
len(tt.expectedScopes), len(authParams.Scopes), tt.expectedScopes, authParams.Scopes)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_ValidateConfig tests config validation
|
||||
func TestKeycloakProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_InterfaceCompliance tests that Keycloak provider implements the OIDCProvider interface
|
||||
func TestKeycloakProvider_InterfaceCompliance(t *testing.T) {
|
||||
var _ OIDCProvider = NewKeycloakProvider()
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_BaseProviderInheritance tests that Keycloak provider inherits from BaseProvider correctly
|
||||
func TestKeycloakProvider_BaseProviderInheritance(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
|
||||
// Test that it has access to BaseProvider methods
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("Expected BaseProvider to be initialized")
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh (inherited from BaseProvider)
|
||||
err := provider.HandleTokenRefresh(&TokenResult{
|
||||
IDToken: "test-id-token",
|
||||
AccessToken: "test-access-token",
|
||||
RefreshToken: "test-refresh-token",
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("HandleTokenRefresh failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_RealmSpecificScopes tests Keycloak realm-specific scopes
|
||||
func TestKeycloakProvider_RealmSpecificScopes(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
checkFor []string
|
||||
}{
|
||||
{
|
||||
name: "Keycloak standard scopes",
|
||||
scopes: []string{"roles", "groups", "profile", "email"},
|
||||
checkFor: []string{"roles", "groups", "profile", "email", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keycloak realm roles",
|
||||
scopes: []string{"realm-roles", "client-roles"},
|
||||
checkFor: []string{"realm-roles", "client-roles", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keycloak account service",
|
||||
scopes: []string{"account"},
|
||||
checkFor: []string{"account", "offline_access", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.checkFor {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeycloakProvider_ScopeDeduplication tests that duplicate scopes are handled correctly
|
||||
func TestKeycloakProvider_ScopeDeduplication(t *testing.T) {
|
||||
provider := NewKeycloakProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
// Test with duplicate scopes
|
||||
scopes := []string{"openid", "profile", "offline_access", "roles", "openid", "profile"}
|
||||
authParams, err := provider.BuildAuthParams(baseParams, scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Count occurrences of each scope
|
||||
scopeCounts := make(map[string]int)
|
||||
for _, scope := range authParams.Scopes {
|
||||
scopeCounts[scope]++
|
||||
}
|
||||
|
||||
// Check that no scope appears more than once
|
||||
for scope, count := range scopeCounts {
|
||||
if count > 1 {
|
||||
t.Errorf("Scope '%s' appears %d times, expected 1", scope, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// OktaProvider encapsulates Okta-specific OIDC logic.
|
||||
type OktaProvider struct {
|
||||
*BaseProvider
|
||||
}
|
||||
|
||||
// NewOktaProvider creates a new instance of the OktaProvider.
|
||||
func NewOktaProvider() *OktaProvider {
|
||||
return &OktaProvider{
|
||||
BaseProvider: NewBaseProvider(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetType returns the provider's type.
|
||||
func (p *OktaProvider) GetType() ProviderType {
|
||||
return ProviderTypeOkta
|
||||
}
|
||||
|
||||
// GetCapabilities returns the specific capabilities of the Okta provider.
|
||||
func (p *OktaProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{
|
||||
SupportsRefreshTokens: true,
|
||||
RequiresOfflineAccessScope: true,
|
||||
RequiresPromptConsent: false,
|
||||
PreferredTokenValidation: "id", // Okta primarily uses ID tokens
|
||||
}
|
||||
}
|
||||
|
||||
// BuildAuthParams configures Okta-specific authentication parameters.
|
||||
func (p *OktaProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
// Okta supports various response types
|
||||
baseParams.Set("response_type", "code")
|
||||
|
||||
// Ensure offline_access scope is present for refresh tokens
|
||||
hasOfflineAccess := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "offline_access" {
|
||||
hasOfflineAccess = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOfflineAccess {
|
||||
scopes = append(scopes, "offline_access")
|
||||
}
|
||||
|
||||
// Ensure openid scope is present
|
||||
hasOpenID := false
|
||||
for _, scope := range scopes {
|
||||
if scope == "openid" {
|
||||
hasOpenID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasOpenID {
|
||||
scopes = append(scopes, "openid")
|
||||
}
|
||||
|
||||
return &AuthParams{
|
||||
URLValues: baseParams,
|
||||
Scopes: deduplicateScopes(scopes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Okta requires specific domain configuration and application setup.
|
||||
func (p *OktaProvider) ValidateConfig() error {
|
||||
return p.BaseProvider.ValidateConfig()
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestOktaProvider_NewOktaProvider tests the constructor
|
||||
func TestOktaProvider_NewOktaProvider(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
|
||||
if provider == nil {
|
||||
t.Fatal("Expected provider to be created, got nil")
|
||||
}
|
||||
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("BaseProvider should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_GetType tests provider type
|
||||
func TestOktaProvider_GetType(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
|
||||
if provider.GetType() != ProviderTypeOkta {
|
||||
t.Errorf("Expected ProviderTypeOkta, got %v", provider.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_GetCapabilities tests Okta-specific capabilities
|
||||
func TestOktaProvider_GetCapabilities(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
capabilities := provider.GetCapabilities()
|
||||
|
||||
if !capabilities.SupportsRefreshTokens {
|
||||
t.Error("Expected SupportsRefreshTokens to be true for Okta")
|
||||
}
|
||||
|
||||
if !capabilities.RequiresOfflineAccessScope {
|
||||
t.Error("Expected RequiresOfflineAccessScope to be true for Okta")
|
||||
}
|
||||
|
||||
if capabilities.RequiresPromptConsent {
|
||||
t.Error("Expected RequiresPromptConsent to be false for Okta")
|
||||
}
|
||||
|
||||
if capabilities.PreferredTokenValidation != "id" {
|
||||
t.Errorf("Expected PreferredTokenValidation 'id', got '%s'", capabilities.PreferredTokenValidation)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_BuildAuthParams tests Okta-specific auth params
|
||||
func TestOktaProvider_BuildAuthParams(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
baseParams := url.Values{}
|
||||
baseParams.Set("client_id", "test_client")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
expectedScopes []string
|
||||
}{
|
||||
{
|
||||
name: "Add offline_access and openid scopes",
|
||||
scopes: []string{"groups", "profile"},
|
||||
expectedScopes: []string{"groups", "profile", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Keep existing offline_access and openid",
|
||||
scopes: []string{"openid", "groups", "offline_access", "profile"},
|
||||
expectedScopes: []string{"openid", "groups", "offline_access", "profile"},
|
||||
},
|
||||
{
|
||||
name: "Add both scopes when none provided",
|
||||
scopes: []string{},
|
||||
expectedScopes: []string{"offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Add openid when only offline_access present",
|
||||
scopes: []string{"offline_access"},
|
||||
expectedScopes: []string{"offline_access", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that response_type is set
|
||||
if authParams.URLValues.Get("response_type") != "code" {
|
||||
t.Errorf("Expected response_type 'code', got '%s'", authParams.URLValues.Get("response_type"))
|
||||
}
|
||||
|
||||
if len(authParams.Scopes) != len(tt.expectedScopes) {
|
||||
t.Errorf("Expected %d scopes, got %d. Expected: %v, Got: %v",
|
||||
len(tt.expectedScopes), len(authParams.Scopes), tt.expectedScopes, authParams.Scopes)
|
||||
return
|
||||
}
|
||||
|
||||
// Check that all expected scopes are present
|
||||
for _, expectedScope := range tt.expectedScopes {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_ValidateConfig tests config validation
|
||||
func TestOktaProvider_ValidateConfig(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
|
||||
err := provider.ValidateConfig()
|
||||
if err != nil {
|
||||
t.Errorf("ValidateConfig failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_InterfaceCompliance tests that Okta provider implements the OIDCProvider interface
|
||||
func TestOktaProvider_InterfaceCompliance(t *testing.T) {
|
||||
var _ OIDCProvider = NewOktaProvider()
|
||||
}
|
||||
|
||||
// TestOktaProvider_BaseProviderInheritance tests that Okta provider inherits from BaseProvider correctly
|
||||
func TestOktaProvider_BaseProviderInheritance(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
|
||||
// Test that it has access to BaseProvider methods
|
||||
if provider.BaseProvider == nil {
|
||||
t.Error("Expected BaseProvider to be initialized")
|
||||
}
|
||||
|
||||
// Test HandleTokenRefresh (inherited from BaseProvider)
|
||||
err := provider.HandleTokenRefresh(&TokenResult{
|
||||
IDToken: "test-id-token",
|
||||
AccessToken: "test-access-token",
|
||||
RefreshToken: "test-refresh-token",
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("HandleTokenRefresh failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOktaProvider_ScopeHandling tests Okta-specific scope handling
|
||||
func TestOktaProvider_ScopeHandling(t *testing.T) {
|
||||
provider := NewOktaProvider()
|
||||
baseParams := url.Values{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
checkFor []string
|
||||
}{
|
||||
{
|
||||
name: "Groups scope handling",
|
||||
scopes: []string{"groups", "profile"},
|
||||
checkFor: []string{"groups", "profile", "offline_access", "openid"},
|
||||
},
|
||||
{
|
||||
name: "Custom Okta scopes",
|
||||
scopes: []string{"okta.users.read", "okta.groups.read"},
|
||||
checkFor: []string{"okta.users.read", "okta.groups.read", "offline_access", "openid"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
authParams, err := provider.BuildAuthParams(baseParams, tt.scopes)
|
||||
if err != nil {
|
||||
t.Errorf("BuildAuthParams failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, expectedScope := range tt.checkFor {
|
||||
found := false
|
||||
for _, actualScope := range authParams.Scopes {
|
||||
if actualScope == expectedScope {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected scope '%s' not found in %v", expectedScope, authParams.Scopes)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,14 @@ func (r *ProviderRegistry) detectProviderUnsafe(issuerURL string) OIDCProvider {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
host := normalizedURL.Host
|
||||
|
||||
// Check if the URL has a valid scheme and host
|
||||
if normalizedURL.Scheme == "" || normalizedURL.Host == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert host to lowercase for case-insensitive matching
|
||||
host := strings.ToLower(normalizedURL.Host)
|
||||
|
||||
for _, p := range r.providers {
|
||||
switch p.GetType() {
|
||||
@@ -127,6 +134,30 @@ func (r *ProviderRegistry) detectProviderUnsafe(issuerURL string) OIDCProvider {
|
||||
if strings.Contains(host, "login.microsoftonline.com") || strings.Contains(host, "sts.windows.net") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeGitHub:
|
||||
if strings.Contains(host, "github.com") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeAuth0:
|
||||
if strings.Contains(host, ".auth0.com") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeOkta:
|
||||
if strings.Contains(host, ".okta.com") || strings.Contains(host, ".oktapreview.com") || strings.Contains(host, ".okta-emea.com") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeKeycloak:
|
||||
if strings.Contains(host, "keycloak") || strings.Contains(normalizedURL.Path, "/auth/realms/") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeAWSCognito:
|
||||
if strings.Contains(host, "cognito-idp") && strings.Contains(host, ".amazonaws.com") {
|
||||
return p
|
||||
}
|
||||
case ProviderTypeGitLab:
|
||||
if strings.Contains(host, "gitlab.com") {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestProviderRegistry_NewProviderRegistry tests registry constructor
|
||||
func TestProviderRegistry_NewProviderRegistry(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
if registry == nil {
|
||||
t.Fatal("Expected registry to be created, got nil")
|
||||
}
|
||||
|
||||
if registry.providers == nil {
|
||||
t.Error("Providers slice should be initialized")
|
||||
}
|
||||
|
||||
if registry.cache == nil {
|
||||
t.Error("Cache map should be initialized")
|
||||
}
|
||||
|
||||
if registry.typeMap == nil {
|
||||
t.Error("TypeMap should be initialized")
|
||||
}
|
||||
|
||||
if registry.maxCacheSize != 1000 {
|
||||
t.Errorf("Expected maxCacheSize 1000, got %d", registry.maxCacheSize)
|
||||
}
|
||||
|
||||
if registry.cacheCount != 0 {
|
||||
t.Errorf("Expected initial cacheCount 0, got %d", registry.cacheCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_RegisterProvider tests provider registration
|
||||
func TestProviderRegistry_RegisterProvider(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
googleProvider := NewGoogleProvider()
|
||||
azureProvider := NewAzureProvider()
|
||||
|
||||
// Register providers
|
||||
registry.RegisterProvider(genericProvider)
|
||||
registry.RegisterProvider(googleProvider)
|
||||
registry.RegisterProvider(azureProvider)
|
||||
|
||||
// Verify providers are registered
|
||||
if len(registry.providers) != 3 {
|
||||
t.Errorf("Expected 3 providers, got %d", len(registry.providers))
|
||||
}
|
||||
|
||||
if len(registry.typeMap) != 3 {
|
||||
t.Errorf("Expected 3 type mappings, got %d", len(registry.typeMap))
|
||||
}
|
||||
|
||||
// Verify type mappings
|
||||
if registry.typeMap[ProviderTypeGeneric] != genericProvider {
|
||||
t.Error("Generic provider not mapped correctly")
|
||||
}
|
||||
|
||||
if registry.typeMap[ProviderTypeGoogle] != googleProvider {
|
||||
t.Error("Google provider not mapped correctly")
|
||||
}
|
||||
|
||||
if registry.typeMap[ProviderTypeAzure] != azureProvider {
|
||||
t.Error("Azure provider not mapped correctly")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_GetProviderByType tests provider retrieval by type
|
||||
func TestProviderRegistry_GetProviderByType(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
googleProvider := NewGoogleProvider()
|
||||
|
||||
registry.RegisterProvider(genericProvider)
|
||||
registry.RegisterProvider(googleProvider)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
providerType ProviderType
|
||||
expected OIDCProvider
|
||||
}{
|
||||
{
|
||||
name: "Get Generic provider",
|
||||
providerType: ProviderTypeGeneric,
|
||||
expected: genericProvider,
|
||||
},
|
||||
{
|
||||
name: "Get Google provider",
|
||||
providerType: ProviderTypeGoogle,
|
||||
expected: googleProvider,
|
||||
},
|
||||
{
|
||||
name: "Get unregistered provider",
|
||||
providerType: ProviderTypeAzure,
|
||||
expected: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := registry.GetProviderByType(tt.providerType)
|
||||
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_GetRegisteredProviders tests listing registered provider types
|
||||
func TestProviderRegistry_GetRegisteredProviders(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
// Initially empty
|
||||
types := registry.GetRegisteredProviders()
|
||||
if len(types) != 0 {
|
||||
t.Errorf("Expected 0 registered providers, got %d", len(types))
|
||||
}
|
||||
|
||||
// Register some providers
|
||||
registry.RegisterProvider(NewGenericProvider())
|
||||
registry.RegisterProvider(NewGoogleProvider())
|
||||
|
||||
types = registry.GetRegisteredProviders()
|
||||
if len(types) != 2 {
|
||||
t.Errorf("Expected 2 registered providers, got %d", len(types))
|
||||
}
|
||||
|
||||
// Verify types are correct
|
||||
expectedTypes := map[ProviderType]bool{
|
||||
ProviderTypeGeneric: false,
|
||||
ProviderTypeGoogle: false,
|
||||
}
|
||||
|
||||
for _, providerType := range types {
|
||||
if _, exists := expectedTypes[providerType]; exists {
|
||||
expectedTypes[providerType] = true
|
||||
} else {
|
||||
t.Errorf("Unexpected provider type: %v", providerType)
|
||||
}
|
||||
}
|
||||
|
||||
for providerType, found := range expectedTypes {
|
||||
if !found {
|
||||
t.Errorf("Provider type %v not found in results", providerType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_DetectProvider tests provider detection
|
||||
func TestProviderRegistry_DetectProvider(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
// Register providers
|
||||
genericProvider := NewGenericProvider()
|
||||
googleProvider := NewGoogleProvider()
|
||||
azureProvider := NewAzureProvider()
|
||||
githubProvider := NewGitHubProvider()
|
||||
auth0Provider := NewAuth0Provider()
|
||||
oktaProvider := NewOktaProvider()
|
||||
keycloakProvider := NewKeycloakProvider()
|
||||
cognitoProvider := NewAWSCognitoProvider()
|
||||
gitlabProvider := NewGitLabProvider()
|
||||
|
||||
registry.RegisterProvider(genericProvider)
|
||||
registry.RegisterProvider(googleProvider)
|
||||
registry.RegisterProvider(azureProvider)
|
||||
registry.RegisterProvider(githubProvider)
|
||||
registry.RegisterProvider(auth0Provider)
|
||||
registry.RegisterProvider(oktaProvider)
|
||||
registry.RegisterProvider(keycloakProvider)
|
||||
registry.RegisterProvider(cognitoProvider)
|
||||
registry.RegisterProvider(gitlabProvider)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
expected OIDCProvider
|
||||
}{
|
||||
{
|
||||
name: "Google provider detection",
|
||||
issuerURL: "https://accounts.google.com",
|
||||
expected: googleProvider,
|
||||
},
|
||||
{
|
||||
name: "Google provider with path",
|
||||
issuerURL: "https://accounts.google.com/oauth2",
|
||||
expected: googleProvider,
|
||||
},
|
||||
{
|
||||
name: "Azure provider detection - login.microsoftonline.com",
|
||||
issuerURL: "https://login.microsoftonline.com/tenant/v2.0",
|
||||
expected: azureProvider,
|
||||
},
|
||||
{
|
||||
name: "Azure provider detection - sts.windows.net",
|
||||
issuerURL: "https://sts.windows.net/tenant",
|
||||
expected: azureProvider,
|
||||
},
|
||||
{
|
||||
name: "GitHub provider detection",
|
||||
issuerURL: "https://github.com/login/oauth",
|
||||
expected: githubProvider,
|
||||
},
|
||||
{
|
||||
name: "Auth0 provider detection",
|
||||
issuerURL: "https://tenant.auth0.com",
|
||||
expected: auth0Provider,
|
||||
},
|
||||
{
|
||||
name: "Okta provider detection",
|
||||
issuerURL: "https://tenant.okta.com",
|
||||
expected: oktaProvider,
|
||||
},
|
||||
{
|
||||
name: "Okta preview provider detection",
|
||||
issuerURL: "https://tenant.oktapreview.com",
|
||||
expected: oktaProvider,
|
||||
},
|
||||
{
|
||||
name: "Keycloak provider detection",
|
||||
issuerURL: "https://auth.example.com/auth/realms/master",
|
||||
expected: keycloakProvider,
|
||||
},
|
||||
{
|
||||
name: "AWS Cognito provider detection",
|
||||
issuerURL: "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example",
|
||||
expected: cognitoProvider,
|
||||
},
|
||||
{
|
||||
name: "GitLab provider detection",
|
||||
issuerURL: "https://gitlab.com/oauth",
|
||||
expected: gitlabProvider,
|
||||
},
|
||||
{
|
||||
name: "Generic provider fallback",
|
||||
issuerURL: "https://auth.example.com",
|
||||
expected: genericProvider,
|
||||
},
|
||||
{
|
||||
name: "Invalid URL",
|
||||
issuerURL: "not-a-url",
|
||||
expected: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := registry.DetectProvider(tt.issuerURL)
|
||||
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_DetectProvider_Caching tests cache behavior
|
||||
func TestProviderRegistry_DetectProvider_Caching(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
issuerURL := "https://auth.example.com"
|
||||
|
||||
// First call should detect and cache
|
||||
result1 := registry.DetectProvider(issuerURL)
|
||||
if result1 != genericProvider {
|
||||
t.Errorf("Expected generic provider, got %v", result1)
|
||||
}
|
||||
|
||||
// Verify it's cached
|
||||
registry.mu.RLock()
|
||||
cachedResult, found := registry.cache[issuerURL]
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if !found {
|
||||
t.Error("Expected result to be cached")
|
||||
}
|
||||
|
||||
if cachedResult != genericProvider {
|
||||
t.Errorf("Expected cached generic provider, got %v", cachedResult)
|
||||
}
|
||||
|
||||
// Second call should return cached result
|
||||
result2 := registry.DetectProvider(issuerURL)
|
||||
if result2 != genericProvider {
|
||||
t.Errorf("Expected cached generic provider, got %v", result2)
|
||||
}
|
||||
|
||||
// Should be same instance (from cache)
|
||||
if result1 != result2 {
|
||||
t.Error("Expected same instance from cache")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_ClearCache tests cache clearing
|
||||
func TestProviderRegistry_ClearCache(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
// Populate cache
|
||||
registry.DetectProvider("https://auth1.example.com")
|
||||
registry.DetectProvider("https://auth2.example.com")
|
||||
|
||||
// Verify cache has entries
|
||||
registry.mu.RLock()
|
||||
cacheSize := len(registry.cache)
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if cacheSize != 2 {
|
||||
t.Errorf("Expected 2 cache entries, got %d", cacheSize)
|
||||
}
|
||||
|
||||
// Clear cache
|
||||
registry.ClearCache()
|
||||
|
||||
// Verify cache is empty
|
||||
registry.mu.RLock()
|
||||
cacheSize = len(registry.cache)
|
||||
cacheCount := registry.cacheCount
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if cacheSize != 0 {
|
||||
t.Errorf("Expected 0 cache entries after clear, got %d", cacheSize)
|
||||
}
|
||||
|
||||
if cacheCount != 0 {
|
||||
t.Errorf("Expected 0 cache count after clear, got %d", cacheCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_CacheEviction tests cache size limits and eviction
|
||||
func TestProviderRegistry_CacheEviction(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
registry.maxCacheSize = 2 // Set small cache size for testing
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
// Fill cache to capacity
|
||||
registry.DetectProvider("https://auth1.example.com")
|
||||
registry.DetectProvider("https://auth2.example.com")
|
||||
|
||||
// Verify cache is at capacity
|
||||
registry.mu.RLock()
|
||||
cacheSize := len(registry.cache)
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if cacheSize != 2 {
|
||||
t.Errorf("Expected 2 cache entries, got %d", cacheSize)
|
||||
}
|
||||
|
||||
// Add one more entry (should trigger eviction)
|
||||
registry.DetectProvider("https://auth3.example.com")
|
||||
|
||||
// Cache size should still be at max
|
||||
registry.mu.RLock()
|
||||
cacheSize = len(registry.cache)
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if cacheSize != 2 {
|
||||
t.Errorf("Expected 2 cache entries after eviction, got %d", cacheSize)
|
||||
}
|
||||
|
||||
// Verify the new entry is cached
|
||||
registry.mu.RLock()
|
||||
_, found := registry.cache["https://auth3.example.com"]
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if !found {
|
||||
t.Error("Expected new entry to be cached")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_ConcurrentAccess tests thread safety
|
||||
func TestProviderRegistry_ConcurrentAccess(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
googleProvider := NewGoogleProvider()
|
||||
azureProvider := NewAzureProvider()
|
||||
|
||||
registry.RegisterProvider(genericProvider)
|
||||
registry.RegisterProvider(googleProvider)
|
||||
registry.RegisterProvider(azureProvider)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
goroutines := 10
|
||||
iterations := 100
|
||||
|
||||
// Test concurrent detection
|
||||
for i := 0; i < goroutines; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < iterations; j++ {
|
||||
issuerURL := "https://accounts.google.com"
|
||||
if id%2 == 0 {
|
||||
issuerURL = "https://login.microsoftonline.com/tenant"
|
||||
} else if id%3 == 0 {
|
||||
issuerURL = "https://auth.example.com"
|
||||
}
|
||||
|
||||
result := registry.DetectProvider(issuerURL)
|
||||
if result == nil {
|
||||
t.Errorf("Expected provider for URL %s", issuerURL)
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Test concurrent registration
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 10; i++ {
|
||||
newProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(newProvider)
|
||||
}
|
||||
}()
|
||||
|
||||
// Test concurrent cache clearing
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 10; i++ {
|
||||
registry.ClearCache()
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Verify final state is consistent
|
||||
types := registry.GetRegisteredProviders()
|
||||
if len(types) < 3 { // Should have at least the original 3
|
||||
t.Errorf("Expected at least 3 provider types, got %d", len(types))
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderRegistry_DoubleCheckedLocking tests the double-checked locking pattern
|
||||
func TestProviderRegistry_DoubleCheckedLocking(t *testing.T) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
goroutines := 100
|
||||
issuerURL := "https://auth.example.com"
|
||||
|
||||
// Multiple goroutines trying to detect the same provider simultaneously
|
||||
for i := 0; i < goroutines; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
result := registry.DetectProvider(issuerURL)
|
||||
if result != genericProvider {
|
||||
t.Errorf("Expected generic provider, got %v", result)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Verify only one cache entry was created
|
||||
registry.mu.RLock()
|
||||
cacheSize := len(registry.cache)
|
||||
registry.mu.RUnlock()
|
||||
|
||||
if cacheSize != 1 {
|
||||
t.Errorf("Expected 1 cache entry, got %d", cacheSize)
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark tests
|
||||
func BenchmarkProviderRegistry_DetectProvider_Cached(b *testing.B) {
|
||||
registry := NewProviderRegistry()
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
issuerURL := "https://auth.example.com"
|
||||
// Warm up cache
|
||||
registry.DetectProvider(issuerURL)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
registry.DetectProvider(issuerURL)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkProviderRegistry_DetectProvider_Uncached(b *testing.B) {
|
||||
registry := NewProviderRegistry()
|
||||
genericProvider := NewGenericProvider()
|
||||
registry.RegisterProvider(genericProvider)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
registry.ClearCache() // Clear cache for each iteration
|
||||
registry.DetectProvider("https://auth.example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkProviderRegistry_RegisterProvider(b *testing.B) {
|
||||
registry := NewProviderRegistry()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
provider := NewGenericProvider()
|
||||
registry.RegisterProvider(provider)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestNewConfigValidator tests the creation of a ConfigValidator
|
||||
func TestNewConfigValidator(t *testing.T) {
|
||||
validator := NewConfigValidator()
|
||||
if validator == nil {
|
||||
t.Error("expected non-nil validator")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateIssuerURL tests the ValidateIssuerURL function
|
||||
func TestValidateIssuerURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid https URL",
|
||||
issuerURL: "https://accounts.google.com",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid http URL",
|
||||
issuerURL: "http://localhost:8080",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid URL with path",
|
||||
issuerURL: "https://login.microsoftonline.com/tenant-id/v2.0",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty URL",
|
||||
issuerURL: "",
|
||||
wantErr: true,
|
||||
errMsg: "issuer URL cannot be empty",
|
||||
},
|
||||
{
|
||||
name: "URL without scheme",
|
||||
issuerURL: "accounts.google.com",
|
||||
wantErr: true,
|
||||
errMsg: "issuer URL must include scheme",
|
||||
},
|
||||
{
|
||||
name: "URL with invalid scheme",
|
||||
issuerURL: "ftp://example.com",
|
||||
wantErr: true,
|
||||
errMsg: "issuer URL scheme must be http or https",
|
||||
},
|
||||
{
|
||||
name: "URL without host",
|
||||
issuerURL: "https://",
|
||||
wantErr: true,
|
||||
errMsg: "issuer URL must include host",
|
||||
},
|
||||
{
|
||||
name: "malformed URL",
|
||||
issuerURL: "ht!tp://[invalid",
|
||||
wantErr: true,
|
||||
errMsg: "invalid issuer URL format",
|
||||
},
|
||||
{
|
||||
name: "URL with port",
|
||||
issuerURL: "https://auth.example.com:443/oauth",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "URL with query parameters",
|
||||
issuerURL: "https://auth.example.com?tenant=123",
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
validator := NewConfigValidator()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateIssuerURL(tt.issuerURL)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateClientID tests the ValidateClientID function
|
||||
func TestValidateClientID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
clientID string
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid client ID",
|
||||
clientID: "my-application-client",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid UUID client ID",
|
||||
clientID: "123e4567-e89b-12d3-a456-426614174000",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty client ID",
|
||||
clientID: "",
|
||||
wantErr: true,
|
||||
errMsg: "client ID cannot be empty",
|
||||
},
|
||||
{
|
||||
name: "too short client ID",
|
||||
clientID: "ab",
|
||||
wantErr: true,
|
||||
errMsg: "client ID appears to be too short",
|
||||
},
|
||||
{
|
||||
name: "minimum length client ID",
|
||||
clientID: "abc",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "client ID with special characters",
|
||||
clientID: "client-id_123.app",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "long client ID",
|
||||
clientID: strings.Repeat("a", 255),
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
validator := NewConfigValidator()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateClientID(tt.clientID)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateScopes tests the ValidateScopes function
|
||||
func TestValidateScopes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid scopes with openid",
|
||||
scopes: []string{"openid", "email", "profile"},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "only openid scope",
|
||||
scopes: []string{"openid"},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "openid with whitespace",
|
||||
scopes: []string{" openid ", "email"},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty scopes",
|
||||
scopes: []string{},
|
||||
wantErr: true,
|
||||
errMsg: "at least one scope must be provided",
|
||||
},
|
||||
{
|
||||
name: "nil scopes",
|
||||
scopes: nil,
|
||||
wantErr: true,
|
||||
errMsg: "at least one scope must be provided",
|
||||
},
|
||||
{
|
||||
name: "missing openid scope",
|
||||
scopes: []string{"email", "profile"},
|
||||
wantErr: true,
|
||||
errMsg: "'openid' scope is required",
|
||||
},
|
||||
{
|
||||
name: "duplicate openid scope",
|
||||
scopes: []string{"openid", "openid", "email"},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "custom scopes with openid",
|
||||
scopes: []string{"openid", "api:read", "api:write"},
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
validator := NewConfigValidator()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateScopes(tt.scopes)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateRedirectURL tests the ValidateRedirectURL function
|
||||
func TestValidateRedirectURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
redirectURL string
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid https redirect URL",
|
||||
redirectURL: "https://example.com/callback",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "valid http redirect URL",
|
||||
redirectURL: "http://localhost:3000/auth/callback",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty redirect URL",
|
||||
redirectURL: "",
|
||||
wantErr: true,
|
||||
errMsg: "redirect URL cannot be empty",
|
||||
},
|
||||
{
|
||||
name: "redirect URL without scheme",
|
||||
redirectURL: "example.com/callback",
|
||||
wantErr: true,
|
||||
errMsg: "redirect URL must include scheme",
|
||||
},
|
||||
{
|
||||
name: "malformed redirect URL",
|
||||
redirectURL: "ht!tp://[invalid",
|
||||
wantErr: true,
|
||||
errMsg: "invalid redirect URL format",
|
||||
},
|
||||
{
|
||||
name: "redirect URL with query parameters",
|
||||
redirectURL: "https://example.com/callback?state=abc",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "redirect URL with fragment",
|
||||
redirectURL: "https://example.com/callback#section",
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
validator := NewConfigValidator()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateRedirectURL(tt.redirectURL)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateProviderSpecificConfig tests provider-specific configuration validation
|
||||
func TestValidateProviderSpecificConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
provider OIDCProvider
|
||||
config map[string]interface{}
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid Google config",
|
||||
provider: NewGoogleProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://accounts.google.com",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid Google config - wrong issuer",
|
||||
provider: NewGoogleProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://example.com",
|
||||
},
|
||||
wantErr: true,
|
||||
errMsg: "google provider requires issuer URL to contain accounts.google.com",
|
||||
},
|
||||
{
|
||||
name: "valid Azure config with tenant ID",
|
||||
provider: NewAzureProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://login.microsoftonline.com/12345678-1234-1234-1234-123456789012/v2.0",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid Azure config - wrong domain",
|
||||
provider: NewAzureProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://example.com/tenant",
|
||||
},
|
||||
wantErr: true,
|
||||
errMsg: "azure provider requires issuer URL to contain login.microsoftonline.com",
|
||||
},
|
||||
{
|
||||
name: "Azure config with sts.windows.net",
|
||||
provider: NewAzureProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://sts.windows.net/12345678-1234-1234-1234-123456789012",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "Azure config without tenant ID",
|
||||
provider: NewAzureProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://login.microsoftonline.com/common",
|
||||
},
|
||||
wantErr: true,
|
||||
errMsg: "azure issuer URL should include tenant ID",
|
||||
},
|
||||
{
|
||||
name: "valid generic provider config",
|
||||
provider: NewGenericProvider(),
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://auth.example.com",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty config for generic provider",
|
||||
provider: NewGenericProvider(),
|
||||
config: map[string]interface{}{},
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
validator := NewConfigValidator()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateProviderSpecificConfig(tt.provider, tt.config)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateProviderSpecificConfig_UnknownProvider tests handling of unknown provider types
|
||||
func TestValidateProviderSpecificConfig_UnknownProvider(t *testing.T) {
|
||||
validator := NewConfigValidator()
|
||||
|
||||
// Create a mock provider with invalid type
|
||||
mockProvider := &mockUnknownProvider{}
|
||||
|
||||
err := validator.ValidateProviderSpecificConfig(mockProvider, map[string]interface{}{})
|
||||
if err == nil {
|
||||
t.Error("expected error for unknown provider type")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown provider type") {
|
||||
t.Errorf("expected 'unknown provider type' error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// mockUnknownProvider is a test provider with an invalid type
|
||||
type mockUnknownProvider struct{}
|
||||
|
||||
func (m *mockUnknownProvider) GetType() ProviderType {
|
||||
return ProviderType(999) // Invalid type
|
||||
}
|
||||
|
||||
func (m *mockUnknownProvider) GetCapabilities() ProviderCapabilities {
|
||||
return ProviderCapabilities{}
|
||||
}
|
||||
|
||||
func (m *mockUnknownProvider) ValidateTokens(session Session, verifier TokenVerifier, tokenCache TokenCache, refreshGracePeriod time.Duration) (*ValidationResult, error) {
|
||||
return &ValidationResult{}, nil
|
||||
}
|
||||
|
||||
func (m *mockUnknownProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
|
||||
return &AuthParams{}, nil
|
||||
}
|
||||
|
||||
func (m *mockUnknownProvider) HandleTokenRefresh(tokenData *TokenResult) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockUnknownProvider) ValidateConfig() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestValidateGoogleConfig_EdgeCases tests edge cases for Google config validation
|
||||
func TestValidateGoogleConfig_EdgeCases(t *testing.T) {
|
||||
validator := NewConfigValidator()
|
||||
googleProvider := NewGoogleProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
config map[string]interface{}
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "config without issuer_url",
|
||||
config: map[string]interface{}{},
|
||||
wantErr: false, // Should pass as issuer_url is not present
|
||||
},
|
||||
{
|
||||
name: "config with non-string issuer_url",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": 123,
|
||||
},
|
||||
wantErr: false, // Should pass as type assertion fails
|
||||
},
|
||||
{
|
||||
name: "config with accounts.google.com in path",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://example.com/accounts.google.com",
|
||||
},
|
||||
wantErr: false, // Should pass as it contains the required string
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateProviderSpecificConfig(googleProvider, tt.config)
|
||||
|
||||
if tt.wantErr && err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if !tt.wantErr && err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateAzureConfig_EdgeCases tests edge cases for Azure config validation
|
||||
func TestValidateAzureConfig_EdgeCases(t *testing.T) {
|
||||
validator := NewConfigValidator()
|
||||
azureProvider := NewAzureProvider()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
config map[string]interface{}
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid tenant ID format",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://login.microsoftonline.com/a1b2c3d4-e5f6-7890-abcd-ef1234567890/v2.0",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "tenant ID in different position",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://login.microsoftonline.com/v2.0/a1b2c3d4-e5f6-7890-abcd-ef1234567890/oauth",
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "malformed URL for parsing",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": "https://login.microsoftonline.com/[invalid",
|
||||
},
|
||||
wantErr: true,
|
||||
errMsg: "azure issuer URL should include tenant ID",
|
||||
},
|
||||
{
|
||||
name: "config without issuer_url",
|
||||
config: map[string]interface{}{},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "config with non-string issuer_url",
|
||||
config: map[string]interface{}{
|
||||
"issuer_url": []string{"https://login.microsoftonline.com"},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validator.ValidateProviderSpecificConfig(azureProvider, tt.config)
|
||||
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error, got nil")
|
||||
} else if tt.errMsg != "" && !strings.Contains(err.Error(), tt.errMsg) {
|
||||
t.Errorf("expected error containing %q, got %q", tt.errMsg, err.Error())
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ProviderWarning represents a warning about provider limitations or requirements.
|
||||
type ProviderWarning struct {
|
||||
ProviderType ProviderType
|
||||
Level string // "info", "warning", "error"
|
||||
Message string
|
||||
}
|
||||
|
||||
// GetProviderWarnings returns warnings about provider-specific limitations.
|
||||
func GetProviderWarnings(providerType ProviderType) []ProviderWarning {
|
||||
var warnings []ProviderWarning
|
||||
|
||||
switch providerType {
|
||||
case ProviderTypeGitHub:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeGitHub,
|
||||
Level: "warning",
|
||||
Message: "GitHub uses OAuth 2.0, not OpenID Connect. ID tokens are not available. Use access tokens for API calls only.",
|
||||
})
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeGitHub,
|
||||
Level: "info",
|
||||
Message: "GitHub OAuth apps do not support refresh tokens. Users will need to re-authenticate when tokens expire.",
|
||||
})
|
||||
|
||||
case ProviderTypeAuth0:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeAuth0,
|
||||
Level: "info",
|
||||
Message: "Auth0 requires 'offline_access' scope for refresh tokens. This will be automatically added.",
|
||||
})
|
||||
|
||||
case ProviderTypeOkta:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeOkta,
|
||||
Level: "info",
|
||||
Message: "Okta requires proper application configuration in your Okta admin console for OIDC to work.",
|
||||
})
|
||||
|
||||
case ProviderTypeKeycloak:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeKeycloak,
|
||||
Level: "info",
|
||||
Message: "Keycloak detection is based on URL path '/auth/realms/'. Ensure your issuer URL follows this pattern.",
|
||||
})
|
||||
|
||||
case ProviderTypeAWSCognito:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeAWSCognito,
|
||||
Level: "info",
|
||||
Message: "AWS Cognito uses regional endpoints. Ensure your issuer URL includes the correct region (e.g., cognito-idp.us-east-1.amazonaws.com).",
|
||||
})
|
||||
|
||||
case ProviderTypeGitLab:
|
||||
warnings = append(warnings, ProviderWarning{
|
||||
ProviderType: ProviderTypeGitLab,
|
||||
Level: "info",
|
||||
Message: "GitLab supports OIDC but requires application registration in GitLab admin settings.",
|
||||
})
|
||||
}
|
||||
|
||||
return warnings
|
||||
}
|
||||
|
||||
// ValidateProviderCompatibility checks if a provider is suitable for OIDC authentication.
|
||||
func ValidateProviderCompatibility(providerType ProviderType, requiresOIDC bool) error {
|
||||
switch providerType {
|
||||
case ProviderTypeGitHub:
|
||||
if requiresOIDC {
|
||||
return fmt.Errorf("GitHub does not support OpenID Connect. It only supports OAuth 2.0. Consider using a different provider for OIDC authentication")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// GetProviderRecommendations returns setup recommendations for each provider.
|
||||
func GetProviderRecommendations(providerType ProviderType) []string {
|
||||
switch providerType {
|
||||
case ProviderTypeGitHub:
|
||||
return []string{
|
||||
"Register an OAuth App in GitHub Settings > Developer settings > OAuth Apps",
|
||||
"Use scopes: 'user:email', 'read:user' for basic profile access",
|
||||
"GitHub tokens expire, plan for re-authentication flow",
|
||||
}
|
||||
|
||||
case ProviderTypeAuth0:
|
||||
return []string{
|
||||
"Create an Application in Auth0 Dashboard",
|
||||
"Set Application Type to 'Regular Web Application'",
|
||||
"Configure Allowed Callback URLs with your redirect URI",
|
||||
"Enable 'offline_access' scope for refresh tokens",
|
||||
}
|
||||
|
||||
case ProviderTypeOkta:
|
||||
return []string{
|
||||
"Create an App Integration in Okta Admin Console",
|
||||
"Choose 'OIDC - OpenID Connect' as sign-in method",
|
||||
"Select 'Web Application' as application type",
|
||||
"Configure redirect URIs and assign users/groups",
|
||||
}
|
||||
|
||||
case ProviderTypeKeycloak:
|
||||
return []string{
|
||||
"Create a Client in your Keycloak realm",
|
||||
"Set Client Protocol to 'openid-connect'",
|
||||
"Configure Valid Redirect URIs",
|
||||
"Ensure issuer URL format: https://your-keycloak/auth/realms/your-realm",
|
||||
}
|
||||
|
||||
case ProviderTypeAWSCognito:
|
||||
return []string{
|
||||
"Create a User Pool in AWS Cognito",
|
||||
"Create an App Client with 'Authorization code grant' enabled",
|
||||
"Configure App Client settings and callback URLs",
|
||||
"Use issuer URL format: https://cognito-idp.{region}.amazonaws.com/{userPoolId}",
|
||||
}
|
||||
|
||||
case ProviderTypeGitLab:
|
||||
return []string{
|
||||
"Create an Application in GitLab (Admin Area > Applications)",
|
||||
"Select 'openid', 'profile', 'email' scopes",
|
||||
"Configure Redirect URI",
|
||||
"Use issuer URL: https://gitlab.com (for GitLab.com)",
|
||||
}
|
||||
|
||||
default:
|
||||
return []string{}
|
||||
}
|
||||
}
|
||||
|
||||
// FormatProviderWarnings formats warnings for display.
|
||||
func FormatProviderWarnings(warnings []ProviderWarning) string {
|
||||
if len(warnings) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
for _, warning := range warnings {
|
||||
result.WriteString(fmt.Sprintf("[%s] %s\n", strings.ToUpper(warning.Level), warning.Message))
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGetProviderWarnings tests that warnings are provided for providers with limitations
|
||||
func TestGetProviderWarnings(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
providerType ProviderType
|
||||
expectCount int
|
||||
checkContent string
|
||||
}{
|
||||
{
|
||||
name: "GitHub has OAuth 2.0 warning",
|
||||
providerType: ProviderTypeGitHub,
|
||||
expectCount: 2,
|
||||
checkContent: "OAuth 2.0",
|
||||
},
|
||||
{
|
||||
name: "Auth0 has offline_access info",
|
||||
providerType: ProviderTypeAuth0,
|
||||
expectCount: 1,
|
||||
checkContent: "offline_access",
|
||||
},
|
||||
{
|
||||
name: "Okta has configuration info",
|
||||
providerType: ProviderTypeOkta,
|
||||
expectCount: 1,
|
||||
checkContent: "admin console",
|
||||
},
|
||||
{
|
||||
name: "AWS Cognito has regional endpoint info",
|
||||
providerType: ProviderTypeAWSCognito,
|
||||
expectCount: 1,
|
||||
checkContent: "regional endpoints",
|
||||
},
|
||||
{
|
||||
name: "Generic provider has no warnings",
|
||||
providerType: ProviderTypeGeneric,
|
||||
expectCount: 0,
|
||||
checkContent: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
warnings := GetProviderWarnings(tt.providerType)
|
||||
|
||||
if len(warnings) != tt.expectCount {
|
||||
t.Errorf("Expected %d warnings, got %d", tt.expectCount, len(warnings))
|
||||
}
|
||||
|
||||
if tt.checkContent != "" {
|
||||
found := false
|
||||
for _, warning := range warnings {
|
||||
if strings.Contains(strings.ToLower(warning.Message), strings.ToLower(tt.checkContent)) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected warning content '%s' not found", tt.checkContent)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateProviderCompatibility tests OIDC compatibility validation
|
||||
func TestValidateProviderCompatibility(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
providerType ProviderType
|
||||
requiresOIDC bool
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "GitHub with OIDC requirement should error",
|
||||
providerType: ProviderTypeGitHub,
|
||||
requiresOIDC: true,
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
name: "GitHub without OIDC requirement should pass",
|
||||
providerType: ProviderTypeGitHub,
|
||||
requiresOIDC: false,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "Auth0 with OIDC requirement should pass",
|
||||
providerType: ProviderTypeAuth0,
|
||||
requiresOIDC: true,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "Google with OIDC requirement should pass",
|
||||
providerType: ProviderTypeGoogle,
|
||||
requiresOIDC: true,
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ValidateProviderCompatibility(tt.providerType, tt.requiresOIDC)
|
||||
|
||||
if tt.expectError && err == nil {
|
||||
t.Error("Expected error but got none")
|
||||
}
|
||||
|
||||
if !tt.expectError && err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetProviderRecommendations tests that recommendations are provided
|
||||
func TestGetProviderRecommendations(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
providerType ProviderType
|
||||
expectMin int
|
||||
}{
|
||||
{
|
||||
name: "GitHub recommendations",
|
||||
providerType: ProviderTypeGitHub,
|
||||
expectMin: 3,
|
||||
},
|
||||
{
|
||||
name: "Auth0 recommendations",
|
||||
providerType: ProviderTypeAuth0,
|
||||
expectMin: 3,
|
||||
},
|
||||
{
|
||||
name: "AWS Cognito recommendations",
|
||||
providerType: ProviderTypeAWSCognito,
|
||||
expectMin: 3,
|
||||
},
|
||||
{
|
||||
name: "Generic provider no recommendations",
|
||||
providerType: ProviderTypeGeneric,
|
||||
expectMin: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
recommendations := GetProviderRecommendations(tt.providerType)
|
||||
|
||||
if len(recommendations) < tt.expectMin {
|
||||
t.Errorf("Expected at least %d recommendations, got %d", tt.expectMin, len(recommendations))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormatProviderWarnings tests warning formatting
|
||||
func TestFormatProviderWarnings(t *testing.T) {
|
||||
warnings := []ProviderWarning{
|
||||
{
|
||||
ProviderType: ProviderTypeGitHub,
|
||||
Level: "warning",
|
||||
Message: "Test warning message",
|
||||
},
|
||||
{
|
||||
ProviderType: ProviderTypeGitHub,
|
||||
Level: "info",
|
||||
Message: "Test info message",
|
||||
},
|
||||
}
|
||||
|
||||
formatted := FormatProviderWarnings(warnings)
|
||||
|
||||
if !strings.Contains(formatted, "[WARNING]") {
|
||||
t.Error("Expected formatted output to contain [WARNING]")
|
||||
}
|
||||
|
||||
if !strings.Contains(formatted, "[INFO]") {
|
||||
t.Error("Expected formatted output to contain [INFO]")
|
||||
}
|
||||
|
||||
if !strings.Contains(formatted, "Test warning message") {
|
||||
t.Error("Expected formatted output to contain warning message")
|
||||
}
|
||||
|
||||
// Test empty warnings
|
||||
emptyFormatted := FormatProviderWarnings([]ProviderWarning{})
|
||||
if emptyFormatted != "" {
|
||||
t.Error("Expected empty string for no warnings")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user