diff --git a/openapi/config.go b/openapi/config.go index e97dd4da..ca82495c 100644 --- a/openapi/config.go +++ b/openapi/config.go @@ -2,6 +2,9 @@ package openapi import ( "errors" + "path/filepath" + "strings" + "time" jsoniter "github.com/json-iterator/go" "github.com/yaoapp/gou/store" @@ -28,27 +31,308 @@ func (config *Config) Validate() error { // MarshalJSON JSON Marshaler func (config *Config) MarshalJSON() ([]byte, error) { - return jsoniter.Marshal(config) + // Convert config to temporary structure with string duration fields + tempConfig := TempConfig{ + BaseURL: config.BaseURL, + Store: config.Store, + Cache: config.Cache, + Providers: config.Providers, + } + + if config.OAuth != nil { + tempConfig.OAuth = &TempOAuth{ + IssuerURL: config.OAuth.IssuerURL, + Features: config.OAuth.Features, + Signing: TempSigningConfig{ + SigningCertPath: convertAbsoluteToRelativePath(config.OAuth.Signing.SigningCertPath, config.root), + SigningKeyPath: convertAbsoluteToRelativePath(config.OAuth.Signing.SigningKeyPath, config.root), + SigningKeyPassword: config.OAuth.Signing.SigningKeyPassword, + SigningAlgorithm: config.OAuth.Signing.SigningAlgorithm, + VerificationCerts: config.OAuth.Signing.VerificationCerts, + MTLSClientCACertPath: convertAbsoluteToRelativePath(config.OAuth.Signing.MTLSClientCACertPath, config.root), + MTLSEnabled: config.OAuth.Signing.MTLSEnabled, + CertRotationEnabled: config.OAuth.Signing.CertRotationEnabled, + CertRotationInterval: formatDuration(config.OAuth.Signing.CertRotationInterval), + }, + Token: TempTokenConfig{ + AccessTokenLifetime: formatDuration(config.OAuth.Token.AccessTokenLifetime), + AccessTokenFormat: config.OAuth.Token.AccessTokenFormat, + AccessTokenSigningAlg: config.OAuth.Token.AccessTokenSigningAlg, + RefreshTokenLifetime: formatDuration(config.OAuth.Token.RefreshTokenLifetime), + RefreshTokenRotation: config.OAuth.Token.RefreshTokenRotation, + RefreshTokenFormat: config.OAuth.Token.RefreshTokenFormat, + AuthorizationCodeLifetime: formatDuration(config.OAuth.Token.AuthorizationCodeLifetime), + AuthorizationCodeLength: config.OAuth.Token.AuthorizationCodeLength, + DeviceCodeLifetime: formatDuration(config.OAuth.Token.DeviceCodeLifetime), + DeviceCodeLength: config.OAuth.Token.DeviceCodeLength, + UserCodeLength: config.OAuth.Token.UserCodeLength, + DeviceCodeInterval: formatDuration(config.OAuth.Token.DeviceCodeInterval), + TokenBindingEnabled: config.OAuth.Token.TokenBindingEnabled, + SupportedBindingTypes: config.OAuth.Token.SupportedBindingTypes, + DefaultAudience: config.OAuth.Token.DefaultAudience, + AudienceValidationMode: config.OAuth.Token.AudienceValidationMode, + }, + Security: TempSecurityConfig{ + PKCERequired: config.OAuth.Security.PKCERequired, + PKCECodeChallengeMethod: config.OAuth.Security.PKCECodeChallengeMethod, + PKCECodeVerifierLength: config.OAuth.Security.PKCECodeVerifierLength, + StateParameterRequired: config.OAuth.Security.StateParameterRequired, + StateParameterLifetime: formatDuration(config.OAuth.Security.StateParameterLifetime), + StateParameterLength: config.OAuth.Security.StateParameterLength, + RateLimitEnabled: config.OAuth.Security.RateLimitEnabled, + RateLimitRequests: config.OAuth.Security.RateLimitRequests, + RateLimitWindow: formatDuration(config.OAuth.Security.RateLimitWindow), + RateLimitByClientID: config.OAuth.Security.RateLimitByClientID, + BruteForceProtectionEnabled: config.OAuth.Security.BruteForceProtectionEnabled, + MaxFailedAttempts: config.OAuth.Security.MaxFailedAttempts, + LockoutDuration: formatDuration(config.OAuth.Security.LockoutDuration), + EncryptionKey: config.OAuth.Security.EncryptionKey, + EncryptionAlgorithm: config.OAuth.Security.EncryptionAlgorithm, + IPWhitelist: config.OAuth.Security.IPWhitelist, + IPBlacklist: config.OAuth.Security.IPBlacklist, + RequireHTTPS: config.OAuth.Security.RequireHTTPS, + DisableUnsecureEndpoints: config.OAuth.Security.DisableUnsecureEndpoints, + }, + Client: TempClientConfig{ + DefaultClientType: config.OAuth.Client.DefaultClientType, + DefaultTokenEndpointAuthMethod: config.OAuth.Client.DefaultTokenEndpointAuthMethod, + DefaultGrantTypes: config.OAuth.Client.DefaultGrantTypes, + DefaultResponseTypes: config.OAuth.Client.DefaultResponseTypes, + DefaultScopes: config.OAuth.Client.DefaultScopes, + ClientIDLength: config.OAuth.Client.ClientIDLength, + ClientSecretLength: config.OAuth.Client.ClientSecretLength, + ClientSecretLifetime: formatDuration(config.OAuth.Client.ClientSecretLifetime), + DynamicRegistrationEnabled: config.OAuth.Client.DynamicRegistrationEnabled, + AllowedRedirectURISchemes: config.OAuth.Client.AllowedRedirectURISchemes, + AllowedRedirectURIHosts: config.OAuth.Client.AllowedRedirectURIHosts, + ClientCertificateRequired: config.OAuth.Client.ClientCertificateRequired, + ClientCertificateValidation: config.OAuth.Client.ClientCertificateValidation, + }, + } + } + + return jsoniter.Marshal(tempConfig) } // UnmarshalJSON JSON Unmarshaler func (config *Config) UnmarshalJSON(data []byte) error { - return jsoniter.Unmarshal(data, config) + var tempConfig TempConfig + err := jsoniter.Unmarshal(data, &tempConfig) + if err != nil { + return err + } + + // Convert temporary config to final config + config.BaseURL = tempConfig.BaseURL + config.Store = tempConfig.Store + config.Cache = tempConfig.Cache + config.Providers = tempConfig.Providers + + if tempConfig.OAuth != nil { + config.OAuth = &OAuth{ + IssuerURL: tempConfig.OAuth.IssuerURL, + Features: tempConfig.OAuth.Features, + } + + // Convert signing config with duration parsing + config.OAuth.Signing = types.SigningConfig{ + SigningCertPath: tempConfig.OAuth.Signing.SigningCertPath, + SigningKeyPath: tempConfig.OAuth.Signing.SigningKeyPath, + SigningKeyPassword: tempConfig.OAuth.Signing.SigningKeyPassword, + SigningAlgorithm: tempConfig.OAuth.Signing.SigningAlgorithm, + VerificationCerts: tempConfig.OAuth.Signing.VerificationCerts, + MTLSClientCACertPath: tempConfig.OAuth.Signing.MTLSClientCACertPath, + MTLSEnabled: tempConfig.OAuth.Signing.MTLSEnabled, + CertRotationEnabled: tempConfig.OAuth.Signing.CertRotationEnabled, + } + if tempConfig.OAuth.Signing.CertRotationInterval != "" { + if duration, err := parseDuration(tempConfig.OAuth.Signing.CertRotationInterval); err == nil { + config.OAuth.Signing.CertRotationInterval = duration + } + } + + // Convert token config with duration parsing + config.OAuth.Token = types.TokenConfig{ + AccessTokenFormat: tempConfig.OAuth.Token.AccessTokenFormat, + AccessTokenSigningAlg: tempConfig.OAuth.Token.AccessTokenSigningAlg, + RefreshTokenRotation: tempConfig.OAuth.Token.RefreshTokenRotation, + RefreshTokenFormat: tempConfig.OAuth.Token.RefreshTokenFormat, + AuthorizationCodeLength: tempConfig.OAuth.Token.AuthorizationCodeLength, + DeviceCodeLength: tempConfig.OAuth.Token.DeviceCodeLength, + UserCodeLength: tempConfig.OAuth.Token.UserCodeLength, + TokenBindingEnabled: tempConfig.OAuth.Token.TokenBindingEnabled, + SupportedBindingTypes: tempConfig.OAuth.Token.SupportedBindingTypes, + DefaultAudience: tempConfig.OAuth.Token.DefaultAudience, + AudienceValidationMode: tempConfig.OAuth.Token.AudienceValidationMode, + } + if tempConfig.OAuth.Token.AccessTokenLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Token.AccessTokenLifetime); err == nil { + config.OAuth.Token.AccessTokenLifetime = duration + } + } + if tempConfig.OAuth.Token.RefreshTokenLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Token.RefreshTokenLifetime); err == nil { + config.OAuth.Token.RefreshTokenLifetime = duration + } + } + if tempConfig.OAuth.Token.AuthorizationCodeLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Token.AuthorizationCodeLifetime); err == nil { + config.OAuth.Token.AuthorizationCodeLifetime = duration + } + } + if tempConfig.OAuth.Token.DeviceCodeLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Token.DeviceCodeLifetime); err == nil { + config.OAuth.Token.DeviceCodeLifetime = duration + } + } + if tempConfig.OAuth.Token.DeviceCodeInterval != "" { + if duration, err := parseDuration(tempConfig.OAuth.Token.DeviceCodeInterval); err == nil { + config.OAuth.Token.DeviceCodeInterval = duration + } + } + + // Convert security config with duration parsing + config.OAuth.Security = types.SecurityConfig{ + PKCERequired: tempConfig.OAuth.Security.PKCERequired, + PKCECodeChallengeMethod: tempConfig.OAuth.Security.PKCECodeChallengeMethod, + PKCECodeVerifierLength: tempConfig.OAuth.Security.PKCECodeVerifierLength, + StateParameterRequired: tempConfig.OAuth.Security.StateParameterRequired, + StateParameterLength: tempConfig.OAuth.Security.StateParameterLength, + RateLimitEnabled: tempConfig.OAuth.Security.RateLimitEnabled, + RateLimitRequests: tempConfig.OAuth.Security.RateLimitRequests, + RateLimitByClientID: tempConfig.OAuth.Security.RateLimitByClientID, + BruteForceProtectionEnabled: tempConfig.OAuth.Security.BruteForceProtectionEnabled, + MaxFailedAttempts: tempConfig.OAuth.Security.MaxFailedAttempts, + EncryptionKey: tempConfig.OAuth.Security.EncryptionKey, + EncryptionAlgorithm: tempConfig.OAuth.Security.EncryptionAlgorithm, + IPWhitelist: tempConfig.OAuth.Security.IPWhitelist, + IPBlacklist: tempConfig.OAuth.Security.IPBlacklist, + RequireHTTPS: tempConfig.OAuth.Security.RequireHTTPS, + DisableUnsecureEndpoints: tempConfig.OAuth.Security.DisableUnsecureEndpoints, + } + if tempConfig.OAuth.Security.StateParameterLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Security.StateParameterLifetime); err == nil { + config.OAuth.Security.StateParameterLifetime = duration + } + } + if tempConfig.OAuth.Security.RateLimitWindow != "" { + if duration, err := parseDuration(tempConfig.OAuth.Security.RateLimitWindow); err == nil { + config.OAuth.Security.RateLimitWindow = duration + } + } + if tempConfig.OAuth.Security.LockoutDuration != "" { + if duration, err := parseDuration(tempConfig.OAuth.Security.LockoutDuration); err == nil { + config.OAuth.Security.LockoutDuration = duration + } + } + + // Convert client config with duration parsing + config.OAuth.Client = types.ClientConfig{ + DefaultClientType: tempConfig.OAuth.Client.DefaultClientType, + DefaultTokenEndpointAuthMethod: tempConfig.OAuth.Client.DefaultTokenEndpointAuthMethod, + DefaultGrantTypes: tempConfig.OAuth.Client.DefaultGrantTypes, + DefaultResponseTypes: tempConfig.OAuth.Client.DefaultResponseTypes, + DefaultScopes: tempConfig.OAuth.Client.DefaultScopes, + ClientIDLength: tempConfig.OAuth.Client.ClientIDLength, + ClientSecretLength: tempConfig.OAuth.Client.ClientSecretLength, + DynamicRegistrationEnabled: tempConfig.OAuth.Client.DynamicRegistrationEnabled, + AllowedRedirectURISchemes: tempConfig.OAuth.Client.AllowedRedirectURISchemes, + AllowedRedirectURIHosts: tempConfig.OAuth.Client.AllowedRedirectURIHosts, + ClientCertificateRequired: tempConfig.OAuth.Client.ClientCertificateRequired, + ClientCertificateValidation: tempConfig.OAuth.Client.ClientCertificateValidation, + } + if tempConfig.OAuth.Client.ClientSecretLifetime != "" { + if duration, err := parseDuration(tempConfig.OAuth.Client.ClientSecretLifetime); err == nil { + config.OAuth.Client.ClientSecretLifetime = duration + } + } + } + + // Set defaults if needed + if config.Cache == "" { + config.Cache = "__yao.oauth.cache" + } + + if config.Store == "" { + config.Store = "__yao.oauth.store" + } + + return nil +} + +// parseDuration parses a time duration string (e.g., "24h", "1h", "10m") into time.Duration +func parseDuration(durationStr string) (time.Duration, error) { + if durationStr == "" || durationStr == "0" || durationStr == "0s" { + return 0, nil + } + return time.ParseDuration(durationStr) +} + +// formatDuration converts time.Duration to human-readable string format +func formatDuration(duration time.Duration) string { + if duration == 0 { + return "0s" + } + return duration.String() +} + +// convertRelativeToAbsolutePath converts relative certificate path to absolute path +func convertRelativeToAbsolutePath(relativePath, rootPath string) string { + if relativePath == "" { + return "" + } + // If already absolute path, return as is + if filepath.IsAbs(relativePath) { + return relativePath + } + // Convert relative path to absolute: Root + "openapi" + "certs" + relativePath + return filepath.Join(rootPath, "openapi", "certs", relativePath) +} + +// convertAbsoluteToRelativePath converts absolute certificate path to relative path +func convertAbsoluteToRelativePath(absolutePath, rootPath string) string { + if absolutePath == "" { + return "" + } + // If not absolute path, return as is + if !filepath.IsAbs(absolutePath) { + return absolutePath + } + + // Remove Root + "openapi" + "certs" prefix + certBasePath := filepath.Join(rootPath, "openapi", "certs") + if strings.HasPrefix(absolutePath, certBasePath) { + relativePath := strings.TrimPrefix(absolutePath, certBasePath) + // Remove leading separator + relativePath = strings.TrimPrefix(relativePath, string(filepath.Separator)) + return relativePath + } + + // If path doesn't match expected pattern, return as is + return absolutePath } // OAuthConfig converts the configuration to an OAuth configuration -func (config *Config) OAuthConfig(appConfig *config.Config) (*oauth.Config, error) { +func (config *Config) OAuthConfig(appConfig config.Config) (*oauth.Config, error) { var oauthConfig oauth.Config var prefix string = share.App.GetPrefix() var providers *Providers = config.GetProviders() - cacheStore, err := store.Get(string(providers.Cache)) + // Store the root path for later use in MarshalJSON + config.root = appConfig.Root + + cacheStore, err := store.Get(config.Cache) if err != nil { return nil, err } - dataStore, err := store.Get(string(providers.Client)) + dataStore, err := store.Get(config.Store) + if err != nil { + return nil, err + } + + clientStore, err := store.Get(string(providers.Client)) if err != nil { return nil, err } @@ -64,7 +348,7 @@ func (config *Config) OAuthConfig(appConfig *config.Config) (*oauth.Config, erro // Create the Client provider clientProvider, err := client.NewDefaultClient(&client.DefaultClientOptions{ Prefix: prefix, - Store: dataStore, + Store: clientStore, Cache: cacheStore, }) @@ -77,6 +361,12 @@ func (config *Config) OAuthConfig(appConfig *config.Config) (*oauth.Config, erro config.OAuth = config.GetDefaultOAuthConfig() } + // Convert certificate paths from relative to absolute + signingConfig := config.OAuth.Signing + signingConfig.SigningCertPath = convertRelativeToAbsolutePath(signingConfig.SigningCertPath, appConfig.Root) + signingConfig.SigningKeyPath = convertRelativeToAbsolutePath(signingConfig.SigningKeyPath, appConfig.Root) + signingConfig.MTLSClientCACertPath = convertRelativeToAbsolutePath(signingConfig.MTLSClientCACertPath, appConfig.Root) + // Create the OAuth configuration oauthConfig = oauth.Config{ UserProvider: userProvider, @@ -84,7 +374,7 @@ func (config *Config) OAuthConfig(appConfig *config.Config) (*oauth.Config, erro Cache: cacheStore, Store: dataStore, IssuerURL: config.BaseURL, - Signing: config.OAuth.Signing, + Signing: signingConfig, // Use the converted signing config Token: config.OAuth.Token, Security: config.OAuth.Security, Client: config.OAuth.Client, @@ -110,7 +400,6 @@ func (config *Config) GetProviders() *Providers { if config.Providers == nil { config.Providers = &Providers{ User: "__yao.user", - Cache: "__yao.oauth.cache", Client: "__yao.oauth.client", } @@ -121,10 +410,6 @@ func (config *Config) GetProviders() *Providers { config.Providers.User = "__yao.user" } - if config.Providers.Cache == "" { - config.Providers.Cache = "__yao.oauth.cache" - } - if config.Providers.Client == "" { config.Providers.Client = "__yao.oauth.client" } diff --git a/openapi/config_test.go b/openapi/config_test.go index 764d6c82..f2ff62cf 100644 --- a/openapi/config_test.go +++ b/openapi/config_test.go @@ -1 +1,352 @@ package openapi + +import ( + "testing" + "time" + + jsoniter "github.com/json-iterator/go" + "github.com/stretchr/testify/assert" + "github.com/yaoapp/yao/openapi/oauth/types" +) + +func TestConfigUnmarshalJSON_TimeParsingCorrect(t *testing.T) { + jsonData := `{ + "baseurl": "/v1", + "store": "__yao.oauth.store", + "cache": "__yao.oauth.cache", + "oauth": { + "issuer_url": "https://localhost:5099", + "signing": { + "cert_rotation_interval": "24h" + }, + "token": { + "access_token_lifetime": "1h", + "refresh_token_lifetime": "24h", + "authorization_code_lifetime": "10m", + "device_code_lifetime": "15m", + "device_code_interval": "5s" + }, + "security": { + "state_parameter_lifetime": "10m", + "rate_limit_window": "1m", + "lockout_duration": "15m" + }, + "client": { + "client_secret_lifetime": "0s" + } + } + }` + + var config Config + err := jsoniter.Unmarshal([]byte(jsonData), &config) + assert.NoError(t, err, "JSON unmarshaling should succeed") + + // Test that duration strings are correctly parsed + assert.Equal(t, 24*time.Hour, config.OAuth.Signing.CertRotationInterval) + assert.Equal(t, time.Hour, config.OAuth.Token.AccessTokenLifetime) + assert.Equal(t, 24*time.Hour, config.OAuth.Token.RefreshTokenLifetime) + assert.Equal(t, 10*time.Minute, config.OAuth.Token.AuthorizationCodeLifetime) + assert.Equal(t, 15*time.Minute, config.OAuth.Token.DeviceCodeLifetime) + assert.Equal(t, 5*time.Second, config.OAuth.Token.DeviceCodeInterval) + assert.Equal(t, 10*time.Minute, config.OAuth.Security.StateParameterLifetime) + assert.Equal(t, time.Minute, config.OAuth.Security.RateLimitWindow) + assert.Equal(t, 15*time.Minute, config.OAuth.Security.LockoutDuration) + assert.Equal(t, time.Duration(0), config.OAuth.Client.ClientSecretLifetime) + + // Test other fields are correctly parsed + assert.Equal(t, "/v1", config.BaseURL) + assert.Equal(t, "__yao.oauth.store", config.Store) + assert.Equal(t, "__yao.oauth.cache", config.Cache) + assert.Equal(t, "https://localhost:5099", config.OAuth.IssuerURL) +} + +func TestParseDuration(t *testing.T) { + tests := []struct { + input string + expected time.Duration + hasError bool + }{ + {"24h", 24 * time.Hour, false}, + {"1h", time.Hour, false}, + {"10m", 10 * time.Minute, false}, + {"5s", 5 * time.Second, false}, + {"0s", 0, false}, + {"0", 0, false}, + {"", 0, false}, + {"invalid", 0, true}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + result, err := parseDuration(tt.input) + if tt.hasError { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.Equal(t, tt.expected, result) + } + }) + } +} + +func TestFormatDuration(t *testing.T) { + tests := []struct { + input time.Duration + expected string + }{ + {24 * time.Hour, "24h0m0s"}, + {time.Hour, "1h0m0s"}, + {10 * time.Minute, "10m0s"}, + {5 * time.Second, "5s"}, + {0, "0s"}, + } + + for _, tt := range tests { + t.Run(tt.expected, func(t *testing.T) { + result := formatDuration(tt.input) + assert.Equal(t, tt.expected, result) + }) + } +} + +func TestConfigMarshalUnmarshalRoundTrip(t *testing.T) { + // Create a config with duration fields + originalConfig := &Config{ + BaseURL: "/v1", + Store: "__yao.oauth.store", + Cache: "__yao.oauth.cache", + OAuth: &OAuth{ + IssuerURL: "https://localhost:5099", + Signing: types.SigningConfig{ + SigningCertPath: "/path/to/cert.pem", + SigningKeyPath: "/path/to/key.pem", + CertRotationInterval: 24 * time.Hour, + }, + Token: types.TokenConfig{ + AccessTokenLifetime: time.Hour, + RefreshTokenLifetime: 24 * time.Hour, + AuthorizationCodeLifetime: 10 * time.Minute, + DeviceCodeLifetime: 15 * time.Minute, + DeviceCodeInterval: 5 * time.Second, + }, + Security: types.SecurityConfig{ + StateParameterLifetime: 10 * time.Minute, + RateLimitWindow: time.Minute, + LockoutDuration: 15 * time.Minute, + }, + Client: types.ClientConfig{ + ClientSecretLifetime: 0, // No expiration + }, + }, + } + + // Marshal to JSON + jsonData, err := jsoniter.Marshal(originalConfig) + assert.NoError(t, err, "Marshal should succeed") + + // Unmarshal back to config + var unmarshaledConfig Config + err = jsoniter.Unmarshal(jsonData, &unmarshaledConfig) + assert.NoError(t, err, "Unmarshal should succeed") + + // Compare the original and unmarshaled configs + assert.Equal(t, originalConfig.BaseURL, unmarshaledConfig.BaseURL) + assert.Equal(t, originalConfig.Store, unmarshaledConfig.Store) + assert.Equal(t, originalConfig.Cache, unmarshaledConfig.Cache) + assert.Equal(t, originalConfig.OAuth.IssuerURL, unmarshaledConfig.OAuth.IssuerURL) + + // Compare duration fields + assert.Equal(t, originalConfig.OAuth.Signing.CertRotationInterval, unmarshaledConfig.OAuth.Signing.CertRotationInterval) + assert.Equal(t, originalConfig.OAuth.Token.AccessTokenLifetime, unmarshaledConfig.OAuth.Token.AccessTokenLifetime) + assert.Equal(t, originalConfig.OAuth.Token.RefreshTokenLifetime, unmarshaledConfig.OAuth.Token.RefreshTokenLifetime) + assert.Equal(t, originalConfig.OAuth.Token.AuthorizationCodeLifetime, unmarshaledConfig.OAuth.Token.AuthorizationCodeLifetime) + assert.Equal(t, originalConfig.OAuth.Token.DeviceCodeLifetime, unmarshaledConfig.OAuth.Token.DeviceCodeLifetime) + assert.Equal(t, originalConfig.OAuth.Token.DeviceCodeInterval, unmarshaledConfig.OAuth.Token.DeviceCodeInterval) + assert.Equal(t, originalConfig.OAuth.Security.StateParameterLifetime, unmarshaledConfig.OAuth.Security.StateParameterLifetime) + assert.Equal(t, originalConfig.OAuth.Security.RateLimitWindow, unmarshaledConfig.OAuth.Security.RateLimitWindow) + assert.Equal(t, originalConfig.OAuth.Security.LockoutDuration, unmarshaledConfig.OAuth.Security.LockoutDuration) + assert.Equal(t, originalConfig.OAuth.Client.ClientSecretLifetime, unmarshaledConfig.OAuth.Client.ClientSecretLifetime) + + // Verify that the JSON contains human-readable duration strings + jsonString := string(jsonData) + assert.Contains(t, jsonString, `"cert_rotation_interval":"24h0m0s"`) + assert.Contains(t, jsonString, `"access_token_lifetime":"1h0m0s"`) + assert.Contains(t, jsonString, `"authorization_code_lifetime":"10m0s"`) + assert.Contains(t, jsonString, `"device_code_interval":"5s"`) + assert.Contains(t, jsonString, `"client_secret_lifetime":"0s"`) +} + +// TestConfigJSONOutputDemo demonstrates the human-readable JSON output format +func TestConfigJSONOutputDemo(t *testing.T) { + config := &Config{ + BaseURL: "/v1", + Store: "__yao.oauth.store", + Cache: "__yao.oauth.cache", + OAuth: &OAuth{ + IssuerURL: "https://localhost:5099", + Signing: types.SigningConfig{ + SigningCertPath: "openapi/certs/signing-cert.pem", + SigningKeyPath: "openapi/certs/signing-key.pem", + CertRotationInterval: 24 * time.Hour, + }, + Token: types.TokenConfig{ + AccessTokenLifetime: time.Hour, + RefreshTokenLifetime: 24 * time.Hour, + AuthorizationCodeLifetime: 10 * time.Minute, + DeviceCodeLifetime: 15 * time.Minute, + DeviceCodeInterval: 5 * time.Second, + AccessTokenFormat: "jwt", + RefreshTokenFormat: "opaque", + }, + }, + } + + jsonData, err := jsoniter.MarshalIndent(config, "", " ") + assert.NoError(t, err) + + t.Logf("Human-readable JSON output:\n%s", string(jsonData)) + + // Verify key duration fields are formatted as strings + jsonString := string(jsonData) + assert.Contains(t, jsonString, `"cert_rotation_interval":"24h0m0s"`) + assert.Contains(t, jsonString, `"access_token_lifetime":"1h0m0s"`) + assert.Contains(t, jsonString, `"device_code_interval":"5s"`) +} + +func TestConvertRelativeToAbsolutePath(t *testing.T) { + tests := []struct { + name string + relativePath string + rootPath string + expected string + }{ + { + name: "basic relative path", + relativePath: "signing-cert.pem", + rootPath: "/app", + expected: "/app/openapi/certs/signing-cert.pem", + }, + { + name: "relative path with subdirectory", + relativePath: "ssl/signing-cert.pem", + rootPath: "/app", + expected: "/app/openapi/certs/ssl/signing-cert.pem", + }, + { + name: "empty relative path", + relativePath: "", + rootPath: "/app", + expected: "", + }, + { + name: "already absolute path", + relativePath: "/absolute/path/cert.pem", + rootPath: "/app", + expected: "/absolute/path/cert.pem", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := convertRelativeToAbsolutePath(tt.relativePath, tt.rootPath) + assert.Equal(t, tt.expected, result) + }) + } +} + +func TestConvertAbsoluteToRelativePath(t *testing.T) { + tests := []struct { + name string + absolutePath string + rootPath string + expected string + }{ + { + name: "basic absolute path", + absolutePath: "/app/openapi/certs/signing-cert.pem", + rootPath: "/app", + expected: "signing-cert.pem", + }, + { + name: "absolute path with subdirectory", + absolutePath: "/app/openapi/certs/ssl/signing-cert.pem", + rootPath: "/app", + expected: "ssl/signing-cert.pem", + }, + { + name: "empty absolute path", + absolutePath: "", + rootPath: "/app", + expected: "", + }, + { + name: "already relative path", + absolutePath: "relative/path/cert.pem", + rootPath: "/app", + expected: "relative/path/cert.pem", + }, + { + name: "path not matching pattern", + absolutePath: "/other/path/cert.pem", + rootPath: "/app", + expected: "/other/path/cert.pem", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := convertAbsoluteToRelativePath(tt.absolutePath, tt.rootPath) + assert.Equal(t, tt.expected, result) + }) + } +} + +func TestCertificatePathConversion(t *testing.T) { + t.Run("complete path conversion cycle", func(t *testing.T) { + rootPath := "/app" + originalRelativePath := "ssl/signing-cert.pem" + + // Convert relative to absolute + absolutePath := convertRelativeToAbsolutePath(originalRelativePath, rootPath) + expected := "/app/openapi/certs/ssl/signing-cert.pem" + assert.Equal(t, expected, absolutePath) + + // Convert absolute back to relative + convertedRelativePath := convertAbsoluteToRelativePath(absolutePath, rootPath) + assert.Equal(t, originalRelativePath, convertedRelativePath) + }) + + t.Run("path conversion with different scenarios", func(t *testing.T) { + testCases := []struct { + name string + relative string + root string + absolute string + }{ + { + name: "simple certificate", + relative: "cert.pem", + root: "/app", + absolute: "/app/openapi/certs/cert.pem", + }, + { + name: "nested directory", + relative: "ssl/prod/cert.pem", + root: "/production", + absolute: "/production/openapi/certs/ssl/prod/cert.pem", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Test conversion to absolute + absolute := convertRelativeToAbsolutePath(tc.relative, tc.root) + assert.Equal(t, tc.absolute, absolute) + + // Test conversion back to relative + relative := convertAbsoluteToRelativePath(tc.absolute, tc.root) + assert.Equal(t, tc.relative, relative) + }) + } + }) +} diff --git a/openapi/openapi.go b/openapi/openapi.go index 520d95b8..c1e8649c 100644 --- a/openapi/openapi.go +++ b/openapi/openapi.go @@ -19,7 +19,7 @@ type OpenAPI struct { } // Load loads the OpenAPI server from the configuration -func Load(appConfig *config.Config) (*OpenAPI, error) { +func Load(appConfig config.Config) (*OpenAPI, error) { var configPath string = filepath.Join("openapi", "openapi.yao") var configRaw, err = application.App.Read(configPath) diff --git a/openapi/openapi_test.go b/openapi/openapi_test.go index 61701177..f40bb863 100644 --- a/openapi/openapi_test.go +++ b/openapi/openapi_test.go @@ -2,7 +2,19 @@ package openapi import ( "testing" + + "github.com/stretchr/testify/assert" + "github.com/yaoapp/yao/config" + "github.com/yaoapp/yao/test" ) func TestLoad(t *testing.T) { + test.Prepare(t, config.Conf) + defer test.Clean() + + _, err := Load(config.Conf) + if err != nil { + t.Fatal(err) + } + assert.NotNil(t, Server) } diff --git a/openapi/types.go b/openapi/types.go index 13d35b14..b77542d2 100644 --- a/openapi/types.go +++ b/openapi/types.go @@ -8,8 +8,11 @@ import ( // Config is the configuration for the OpenAPI server type Config struct { BaseURL string `json:"baseurl" yaml:"baseurl"` + Store string `json:"store,omitempty" yaml:"store,omitempty"` + Cache string `json:"cache,omitempty" yaml:"cache,omitempty"` Providers *Providers `json:"providers,omitempty" yaml:"providers,omitempty"` OAuth *OAuth `json:"oauth,omitempty" yaml:"oauth,omitempty"` + root string `json:"-" yaml:"-"` // Application root path, not serialized to JSON } // Provider is the provider for the OpenAPI server, and in the future will be refactored into a struct @@ -18,7 +21,6 @@ type Provider string // Providers is the providers for the OpenAPI server type Providers struct { User Provider `json:"user,omitempty" yaml:"user,omitempty"` - Cache Provider `json:"cache,omitempty" yaml:"cache,omitempty"` Client Provider `json:"client,omitempty" yaml:"client,omitempty"` } @@ -31,3 +33,99 @@ type OAuth struct { Client types.ClientConfig `json:"client,omitempty" yaml:"client,omitempty"` Features oauth.FeatureFlags `json:"features,omitempty" yaml:"features,omitempty"` } + +// Temporary config structures for JSON unmarshaling (string duration fields) +// These are used to parse human-readable duration strings from config files +// and convert them to Go time.Duration types for internal use + +// TempSigningConfig represents signing configuration with string duration fields +type TempSigningConfig struct { + SigningCertPath string `json:"signing_cert_path"` + SigningKeyPath string `json:"signing_key_path"` + SigningKeyPassword string `json:"signing_key_password,omitempty"` + SigningAlgorithm string `json:"signing_algorithm"` + VerificationCerts []string `json:"verification_certs,omitempty"` + MTLSClientCACertPath string `json:"mtls_client_ca_cert_path,omitempty"` + MTLSEnabled bool `json:"mtls_enabled"` + CertRotationEnabled bool `json:"cert_rotation_enabled"` + CertRotationInterval string `json:"cert_rotation_interval"` +} + +// TempTokenConfig represents token configuration with string duration fields +type TempTokenConfig struct { + AccessTokenLifetime string `json:"access_token_lifetime"` + AccessTokenFormat string `json:"access_token_format"` + AccessTokenSigningAlg string `json:"access_token_signing_alg"` + RefreshTokenLifetime string `json:"refresh_token_lifetime"` + RefreshTokenRotation bool `json:"refresh_token_rotation"` + RefreshTokenFormat string `json:"refresh_token_format"` + AuthorizationCodeLifetime string `json:"authorization_code_lifetime"` + AuthorizationCodeLength int `json:"authorization_code_length"` + DeviceCodeLifetime string `json:"device_code_lifetime"` + DeviceCodeLength int `json:"device_code_length"` + UserCodeLength int `json:"user_code_length"` + DeviceCodeInterval string `json:"device_code_interval"` + TokenBindingEnabled bool `json:"token_binding_enabled"` + SupportedBindingTypes []string `json:"supported_binding_types"` + DefaultAudience []string `json:"default_audience"` + AudienceValidationMode string `json:"audience_validation_mode"` +} + +// TempSecurityConfig represents security configuration with string duration fields +type TempSecurityConfig struct { + PKCERequired bool `json:"pkce_required"` + PKCECodeChallengeMethod []string `json:"pkce_code_challenge_method"` + PKCECodeVerifierLength int `json:"pkce_code_verifier_length"` + StateParameterRequired bool `json:"state_parameter_required"` + StateParameterLifetime string `json:"state_parameter_lifetime"` + StateParameterLength int `json:"state_parameter_length"` + RateLimitEnabled bool `json:"rate_limit_enabled"` + RateLimitRequests int `json:"rate_limit_requests"` + RateLimitWindow string `json:"rate_limit_window"` + RateLimitByClientID bool `json:"rate_limit_by_client_id"` + BruteForceProtectionEnabled bool `json:"brute_force_protection_enabled"` + MaxFailedAttempts int `json:"max_failed_attempts"` + LockoutDuration string `json:"lockout_duration"` + EncryptionKey string `json:"encryption_key"` + EncryptionAlgorithm string `json:"encryption_algorithm"` + IPWhitelist []string `json:"ip_whitelist,omitempty"` + IPBlacklist []string `json:"ip_blacklist,omitempty"` + RequireHTTPS bool `json:"require_https"` + DisableUnsecureEndpoints bool `json:"disable_unsecure_endpoints"` +} + +// TempClientConfig represents client configuration with string duration fields +type TempClientConfig struct { + DefaultClientType string `json:"default_client_type"` + DefaultTokenEndpointAuthMethod string `json:"default_token_endpoint_auth_method"` + DefaultGrantTypes []string `json:"default_grant_types"` + DefaultResponseTypes []string `json:"default_response_types"` + DefaultScopes []string `json:"default_scopes"` + ClientIDLength int `json:"client_id_length"` + ClientSecretLength int `json:"client_secret_length"` + ClientSecretLifetime string `json:"client_secret_lifetime"` + DynamicRegistrationEnabled bool `json:"dynamic_registration_enabled"` + AllowedRedirectURISchemes []string `json:"allowed_redirect_uri_schemes"` + AllowedRedirectURIHosts []string `json:"allowed_redirect_uri_hosts"` + ClientCertificateRequired bool `json:"client_certificate_required"` + ClientCertificateValidation string `json:"client_certificate_validation"` +} + +// TempOAuth represents OAuth configuration with string duration fields +type TempOAuth struct { + IssuerURL string `json:"issuer_url,omitempty"` + Signing TempSigningConfig `json:"signing,omitempty"` + Token TempTokenConfig `json:"token,omitempty"` + Security TempSecurityConfig `json:"security,omitempty"` + Client TempClientConfig `json:"client,omitempty"` + Features oauth.FeatureFlags `json:"features,omitempty"` +} + +// TempConfig represents the full config structure with string duration fields +type TempConfig struct { + BaseURL string `json:"baseurl"` + Store string `json:"store,omitempty"` + Cache string `json:"cache,omitempty"` + Providers *Providers `json:"providers,omitempty"` + OAuth *TempOAuth `json:"oauth,omitempty"` +}