1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4#[cfg(feature = "oauth")]
5use openauth_oauth::oauth2::SocialOAuthProvider;
6
7use crate::cookies::get_cookies;
8use crate::crypto::password::{hash_password, verify_password};
9use crate::crypto::{build_secret_config, parse_secrets_env};
10use crate::db::RateLimitStorage as DbRateLimitStorage;
11use crate::db::{auth_schema, AuthSchemaOptions, DbAdapter, HookedAdapter};
12use crate::env::is_production;
13use crate::env::logger::{create_logger, LoggerOptions};
14use crate::error::OpenAuthError;
15use crate::options::RateLimitStore;
16use crate::options::{OpenAuthOptions, RateLimitStorageOption};
17use crate::rate_limit::{GovernorMemoryRateLimitStore, LegacyRateLimitStorageAdapter};
18
19use super::origins::resolve_trusted_origins;
20use super::plugins::initialize_plugins;
21use super::secrets::{resolve_legacy_secret, validate_secret, DEFAULT_SECRET};
22use super::{
23 AuthContext, AuthEnvironment, PasswordContext, PasswordPolicy, RateLimitContext,
24 SecretMaterial, SessionConfig,
25};
26
27pub fn create_auth_context(options: OpenAuthOptions) -> Result<AuthContext, OpenAuthError> {
28 create_auth_context_with_environment_and_adapter(options, AuthEnvironment::from_process(), None)
29}
30
31pub fn create_auth_context_with_adapter(
32 options: OpenAuthOptions,
33 adapter: Arc<dyn DbAdapter>,
34) -> Result<AuthContext, OpenAuthError> {
35 create_auth_context_with_environment_and_adapter(
36 options,
37 AuthEnvironment::from_process(),
38 Some(adapter),
39 )
40}
41
42pub fn create_auth_context_with_environment(
43 options: OpenAuthOptions,
44 environment: AuthEnvironment,
45) -> Result<AuthContext, OpenAuthError> {
46 create_auth_context_with_environment_and_adapter(options, environment, None)
47}
48
49pub fn create_auth_context_with_environment_and_adapter(
50 options: OpenAuthOptions,
51 environment: AuthEnvironment,
52 adapter: Option<Arc<dyn DbAdapter>>,
53) -> Result<AuthContext, OpenAuthError> {
54 let logger = create_logger(LoggerOptions::default());
55 let production = options.production || is_production();
56 let env_secrets = parse_secrets_env(environment.openauth_secrets.as_deref())?;
57 let secrets = if options.secrets.is_empty() {
58 env_secrets.unwrap_or_default()
59 } else {
60 options.secrets.clone()
61 };
62 let legacy_secret = resolve_legacy_secret(&options, &environment);
63
64 let (secret, secret_config) = if secrets.is_empty() {
65 let secret = legacy_secret.unwrap_or_else(|| DEFAULT_SECRET.to_owned());
66 validate_secret(&secret, production)?;
67 (secret.clone(), SecretMaterial::Single(secret))
68 } else {
69 let config = build_secret_config(&secrets, legacy_secret.as_deref().unwrap_or(""))?;
70 let current = config
71 .keys
72 .get(&config.current_version)
73 .cloned()
74 .ok_or_else(|| {
75 OpenAuthError::InvalidSecretConfig(format!(
76 "secret version {} not found in keys",
77 config.current_version
78 ))
79 })?;
80 (current, SecretMaterial::Rotating(config))
81 };
82
83 let base_path = options
84 .base_path
85 .clone()
86 .unwrap_or_else(|| "/api/auth".to_owned());
87 let base_url = options.base_url.clone().unwrap_or_default();
88 let trusted_origins = resolve_trusted_origins(&base_url, &options);
89 let auth_cookies = get_cookies(&options)?;
90 #[cfg(feature = "oauth")]
91 let social_providers = resolve_social_providers(&options)?;
92 let session_config = SessionConfig {
93 update_age: options.session.update_age.unwrap_or(24 * 60 * 60),
94 expires_in: options.session.expires_in.unwrap_or(60 * 60 * 24 * 7),
95 fresh_age: options.session.fresh_age.unwrap_or(60 * 60 * 24),
96 cookie_refresh_cache: options.session.cookie_cache.refresh_cache,
97 };
98 let password = PasswordContext {
99 config: PasswordPolicy {
100 min_password_length: options.password.min_password_length,
101 max_password_length: options.password.max_password_length,
102 },
103 hash: hash_password,
104 verify: verify_password,
105 };
106 validate_rate_limit_storage(&options)?;
107 let rate_limit = RateLimitContext {
108 enabled: options.rate_limit.enabled.unwrap_or(production),
109 window: options.rate_limit.window,
110 max: options.rate_limit.max,
111 storage: options.rate_limit.storage,
112 custom_rules: options.rate_limit.custom_rules.clone(),
113 dynamic_rules: options.rate_limit.dynamic_rules.clone(),
114 plugin_rules: Vec::new(),
115 custom_store: options.rate_limit.custom_store.clone().or_else(|| {
116 options.rate_limit.custom_storage.clone().map(|storage| {
117 Arc::new(LegacyRateLimitStorageAdapter::new(storage)) as Arc<dyn RateLimitStore>
118 })
119 }),
120 hybrid: options.rate_limit.hybrid.clone(),
121 memory_cleanup_interval: options.rate_limit.memory_cleanup_interval,
122 memory_store: Arc::new(GovernorMemoryRateLimitStore::with_cleanup_interval(
123 options.rate_limit.memory_cleanup_interval,
124 )),
125 };
126
127 let schema_options = schema_options_from_auth_options(&options);
128 let mut context = AuthContext {
129 app_name: "OpenAuth".to_owned(),
130 base_url,
131 base_path,
132 options: options.clone(),
133 auth_cookies,
134 session_config,
135 secret,
136 secret_config,
137 password,
138 rate_limit,
139 trusted_origins,
140 disabled_paths: options.disabled_paths,
141 plugins: options.plugins,
142 adapter,
143 secondary_storage: options.secondary_storage.clone(),
144 background_tasks: options.advanced.background_tasks.clone(),
145 #[cfg(feature = "oauth")]
146 social_providers,
147 db_schema: auth_schema(schema_options),
148 plugin_error_codes: BTreeMap::new(),
149 plugin_database_hooks: Vec::new(),
150 plugin_migrations: Vec::new(),
151 logger,
152 };
153 initialize_plugins(&mut context)?;
154 if !context.plugin_database_hooks.is_empty() {
155 if let Some(adapter) = context.adapter.clone() {
156 context.adapter = Some(Arc::new(HookedAdapter::new(
157 adapter,
158 context.plugin_database_hooks.clone(),
159 )));
160 }
161 }
162 Ok(context)
163}
164
165#[cfg(feature = "oauth")]
166fn resolve_social_providers(
167 options: &OpenAuthOptions,
168) -> Result<BTreeMap<String, Arc<dyn SocialOAuthProvider>>, OpenAuthError> {
169 let mut providers = BTreeMap::new();
170 for provider in &options.social_providers {
171 insert_social_provider(&mut providers, provider.clone())?;
172 }
173 Ok(providers)
174}
175
176#[cfg(feature = "oauth")]
177pub(super) fn insert_social_provider(
178 providers: &mut BTreeMap<String, Arc<dyn SocialOAuthProvider>>,
179 provider: Arc<dyn SocialOAuthProvider>,
180) -> Result<(), OpenAuthError> {
181 let id = provider.id().to_owned();
182 if id.trim().is_empty() {
183 return Err(OpenAuthError::InvalidConfig(
184 "social provider id cannot be empty".to_owned(),
185 ));
186 }
187 if providers.insert(id.clone(), provider).is_some() {
188 return Err(OpenAuthError::InvalidConfig(format!(
189 "duplicate social provider `{id}`"
190 )));
191 }
192 Ok(())
193}
194
195fn validate_rate_limit_storage(options: &OpenAuthOptions) -> Result<(), OpenAuthError> {
196 if options.rate_limit.custom_store.is_some() || options.rate_limit.custom_storage.is_some() {
197 return Ok(());
198 }
199 if matches!(
200 options.rate_limit.storage,
201 RateLimitStorageOption::Database | RateLimitStorageOption::SecondaryStorage
202 ) {
203 return Err(OpenAuthError::InvalidConfig(
204 "rate_limit.custom_store or rate_limit.custom_storage is required when using database or secondary-storage rate limiting without a concrete adapter".to_owned(),
205 ));
206 }
207 Ok(())
208}
209
210fn schema_options_from_auth_options(options: &OpenAuthOptions) -> AuthSchemaOptions {
211 AuthSchemaOptions {
212 has_secondary_storage: options.secondary_storage.is_some(),
213 store_session_in_database: options.session.store_session_in_database,
214 rate_limit_storage: match options.rate_limit.storage {
215 RateLimitStorageOption::Memory => DbRateLimitStorage::Memory,
216 RateLimitStorageOption::Database => DbRateLimitStorage::Database,
217 RateLimitStorageOption::SecondaryStorage => DbRateLimitStorage::SecondaryStorage,
218 },
219 ..AuthSchemaOptions::default()
220 }
221}