Skip to main content

auth_framework/
builders.rs

1//! Builder patterns and ergonomic helpers for the Auth Framework
2//!
3//! This module provides fluent builder APIs and helper functions to make
4//! common authentication setup tasks easier and more discoverable.
5//!
6//! # Quick Start Builders
7//!
8//! For the most common setups, use the quick start builders:
9//!
10//! ```rust,no_run
11//! # #[tokio::main]
12//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
13//! use auth_framework::prelude::*;
14//!
15//! // Simple JWT auth with environment variables
16//! let auth = AuthFramework::quick_start()
17//!     .jwt_auth_from_env()
18//!     .build().await?;
19//!
20//! // Web app with database
21//! let auth = AuthFramework::quick_start()
22//!     .jwt_auth("your-secret-key")
23//!     .with_postgres("postgresql://...")
24//!     .with_axum()
25//!     .build().await?;
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! # Preset Configurations
31//!
32//! Use presets for common security and performance configurations:
33//!
34//! ```rust,no_run
35//! # #[tokio::main]
36//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
37//! use auth_framework::prelude::*;
38//!
39//! let auth = AuthFramework::builder()
40//!     .security_preset(SecurityPreset::HighSecurity)
41//!     .performance_preset(PerformancePreset::LowLatency)
42//!     .build().await?;
43//! # Ok(())
44//! # }
45//! ```
46//!
47//! # Use Case Templates
48//!
49//! Get started quickly with templates for common use cases:
50//!
51//! ```rust,no_run
52//! # #[tokio::main]
53//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
54//! use auth_framework::prelude::*;
55//!
56//! // Configure for web application
57//! let auth = AuthFramework::for_use_case(UseCasePreset::WebApp)
58//!     .customize(|config| {
59//!         config.token_lifetime = hours(24);
60//!         config
61//!     })
62//!     .build().await?;
63//! # Ok(())
64//! # }
65//! ```
66
67use crate::{
68    AuthConfig, AuthError, AuthFramework,
69    config::{RateLimitConfig, SecurityConfig, StorageConfig},
70    prelude::{PerformancePreset, UseCasePreset, days, hours, minutes},
71    security::SecurityPreset,
72};
73use std::time::Duration;
74
75/// Main builder for AuthFramework with fluent API
76#[derive(Debug)]
77pub struct AuthBuilder {
78    config: AuthConfig,
79    security_preset: Option<SecurityPreset>,
80    performance_preset: Option<PerformancePreset>,
81    use_case_preset: Option<UseCasePreset>,
82}
83
84/// Quick start builder for common authentication setups
85#[derive(Debug)]
86pub struct QuickStartBuilder {
87    auth_method: Option<QuickStartAuth>,
88    storage: Option<QuickStartStorage>,
89    framework: Option<QuickStartFramework>,
90    security_level: SecurityPreset,
91}
92
93/// Authentication method configuration for quick start
94#[derive(Debug)]
95pub enum QuickStartAuth {
96    Jwt {
97        secret: String,
98    },
99    JwtFromEnv,
100    OAuth2 {
101        client_id: String,
102        client_secret: String,
103    },
104    Combined {
105        jwt_secret: String,
106        oauth_client_id: String,
107        oauth_client_secret: String,
108    },
109}
110
111/// Storage configuration for quick start
112#[derive(Debug)]
113pub enum QuickStartStorage {
114    Memory,
115    Postgres(String),
116    PostgresFromEnv,
117    Redis(String),
118    RedisFromEnv,
119}
120
121/// Web framework integration for quick start
122#[derive(Debug)]
123pub enum QuickStartFramework {
124    Axum,
125    ActixWeb,
126    Warp,
127}
128
129impl AuthFramework {
130    /// Create a new builder for the authentication framework
131    pub fn builder() -> AuthBuilder {
132        AuthBuilder::new()
133    }
134
135    /// Quick start builder for common setups
136    pub fn quick_start() -> QuickStartBuilder {
137        QuickStartBuilder::new()
138    }
139
140    /// Create a builder for a specific use case
141    pub fn for_use_case(use_case: UseCasePreset) -> AuthBuilder {
142        AuthBuilder::new().use_case_preset(use_case)
143    }
144
145    /// Create an authentication framework with preset configuration
146    pub fn preset(preset: SecurityPreset) -> AuthBuilder {
147        AuthBuilder::new().security_preset(preset)
148    }
149}
150
151impl AuthBuilder {
152    /// Create a new builder with default configuration
153    pub fn new() -> Self {
154        Self {
155            config: AuthConfig::default(),
156            security_preset: None,
157            performance_preset: None,
158            use_case_preset: None,
159        }
160    }
161
162    /// Apply a security preset
163    pub fn security_preset(mut self, preset: SecurityPreset) -> Self {
164        self.security_preset = Some(preset);
165        self
166    }
167
168    /// Apply a performance preset
169    pub fn performance_preset(mut self, preset: PerformancePreset) -> Self {
170        self.performance_preset = Some(preset);
171        self
172    }
173
174    /// Apply a use case preset
175    pub fn use_case_preset(mut self, preset: UseCasePreset) -> Self {
176        self.use_case_preset = Some(preset);
177        self
178    }
179
180    /// Configure JWT authentication
181    pub fn with_jwt(self) -> JwtBuilder {
182        JwtBuilder::new(self)
183    }
184
185    /// Configure OAuth2 authentication
186    pub fn with_oauth2(self) -> OAuth2Builder {
187        OAuth2Builder::new(self)
188    }
189
190    /// Configure storage backend
191    pub fn with_storage(self) -> StorageBuilder {
192        StorageBuilder::new(self)
193    }
194
195    /// Configure rate limiting
196    pub fn with_rate_limiting(self) -> RateLimitBuilder {
197        RateLimitBuilder::new(self)
198    }
199
200    /// Configure security settings
201    pub fn with_security(self) -> SecurityBuilder {
202        SecurityBuilder::new(self)
203    }
204
205    /// Configure audit logging
206    pub fn with_audit(self) -> AuditBuilder {
207        AuditBuilder::new(self)
208    }
209
210    /// Customize configuration with a closure
211    pub fn customize<F>(mut self, f: F) -> Self
212    where
213        F: FnOnce(&mut AuthConfig) -> &mut AuthConfig,
214    {
215        f(&mut self.config);
216        self
217    }
218
219    /// Build the authentication framework
220    pub async fn build(mut self) -> Result<AuthFramework, AuthError> {
221        // Apply presets before building
222        if let Some(preset) = self.security_preset.take() {
223            self.config.security = self.apply_security_preset(preset);
224        }
225
226        if let Some(preset) = self.performance_preset.take() {
227            self.apply_performance_preset(preset);
228        }
229
230        if let Some(preset) = self.use_case_preset.take() {
231            self.apply_use_case_preset(preset);
232        }
233
234        // Validate configuration
235        self.config.validate()?;
236
237        // Create and initialize framework
238        let mut framework = AuthFramework::new(self.config);
239        framework.initialize().await?;
240
241        Ok(framework)
242    }
243
244    fn apply_security_preset(&self, preset: SecurityPreset) -> SecurityConfig {
245        match preset {
246            SecurityPreset::Development => SecurityConfig::development(),
247            SecurityPreset::Balanced => SecurityConfig::default(),
248            SecurityPreset::HighSecurity | SecurityPreset::Paranoid => SecurityConfig::secure(),
249        }
250    }
251
252    fn apply_performance_preset(&mut self, preset: PerformancePreset) {
253        match preset {
254            PerformancePreset::HighThroughput => {
255                // Optimize for throughput
256                self.config.rate_limiting.max_requests = 1000;
257                self.config.rate_limiting.window = Duration::from_secs(60);
258            }
259            PerformancePreset::LowLatency => {
260                // Optimize for latency
261                self.config.token_lifetime = hours(1);
262                self.config.rate_limiting.max_requests = 100;
263                self.config.rate_limiting.window = Duration::from_secs(60);
264            }
265            PerformancePreset::LowMemory => {
266                // Optimize for memory usage
267                self.config.token_lifetime = minutes(15);
268                self.config.refresh_token_lifetime = hours(2);
269            }
270            PerformancePreset::Balanced => {
271                // Keep defaults
272            }
273        }
274    }
275
276    fn apply_use_case_preset(&mut self, preset: UseCasePreset) {
277        match preset {
278            UseCasePreset::WebApp => {
279                self.config.token_lifetime = hours(24);
280                self.config.refresh_token_lifetime = days(7);
281                self.config.security.secure_cookies = true;
282                self.config.security.csrf_protection = true;
283            }
284            UseCasePreset::ApiService => {
285                self.config.token_lifetime = hours(1);
286                self.config.refresh_token_lifetime = hours(24);
287                self.config.rate_limiting.enabled = true;
288                self.config.rate_limiting.max_requests = 1000;
289            }
290            UseCasePreset::Microservices => {
291                self.config.token_lifetime = minutes(15);
292                self.config.refresh_token_lifetime = hours(1);
293                self.config.audit.enabled = true;
294            }
295            UseCasePreset::MobileBackend => {
296                self.config.token_lifetime = hours(1);
297                self.config.refresh_token_lifetime = days(30);
298                self.config.security.secure_cookies = false; // Mobile doesn't use cookies
299            }
300            UseCasePreset::Enterprise => {
301                self.config.enable_multi_factor = true;
302                self.config.security = SecurityConfig::secure();
303                self.config.audit.enabled = true;
304                self.config.audit.log_success = true;
305                self.config.audit.log_failures = true;
306            }
307        }
308    }
309}
310
311impl QuickStartBuilder {
312    fn new() -> Self {
313        Self {
314            auth_method: None,
315            storage: None,
316            framework: None,
317            security_level: SecurityPreset::Balanced,
318        }
319    }
320
321    /// Configure JWT authentication with a secret key
322    pub fn jwt_auth(mut self, secret: impl Into<String>) -> Self {
323        self.auth_method = Some(QuickStartAuth::Jwt {
324            secret: secret.into(),
325        });
326        self
327    }
328
329    /// Configure JWT authentication from JWT_SECRET environment variable
330    pub fn jwt_auth_from_env(mut self) -> Self {
331        self.auth_method = Some(QuickStartAuth::JwtFromEnv);
332        self
333    }
334
335    /// Configure OAuth2 authentication
336    pub fn oauth2_auth(
337        mut self,
338        client_id: impl Into<String>,
339        client_secret: impl Into<String>,
340    ) -> Self {
341        self.auth_method = Some(QuickStartAuth::OAuth2 {
342            client_id: client_id.into(),
343            client_secret: client_secret.into(),
344        });
345        self
346    }
347
348    /// Configure both JWT and OAuth2 authentication
349    pub fn combined_auth(
350        mut self,
351        jwt_secret: impl Into<String>,
352        oauth_client_id: impl Into<String>,
353        oauth_client_secret: impl Into<String>,
354    ) -> Self {
355        self.auth_method = Some(QuickStartAuth::Combined {
356            jwt_secret: jwt_secret.into(),
357            oauth_client_id: oauth_client_id.into(),
358            oauth_client_secret: oauth_client_secret.into(),
359        });
360        self
361    }
362
363    /// Use PostgreSQL storage with connection string
364    pub fn with_postgres(mut self, connection_string: impl Into<String>) -> Self {
365        self.storage = Some(QuickStartStorage::Postgres(connection_string.into()));
366        self
367    }
368
369    /// Use PostgreSQL storage from DATABASE_URL environment variable
370    pub fn with_postgres_from_env(mut self) -> Self {
371        self.storage = Some(QuickStartStorage::PostgresFromEnv);
372        self
373    }
374
375    /// Use Redis storage with connection string
376    pub fn with_redis(mut self, connection_string: impl Into<String>) -> Self {
377        self.storage = Some(QuickStartStorage::Redis(connection_string.into()));
378        self
379    }
380
381    /// Use Redis storage from REDIS_URL environment variable
382    pub fn with_redis_from_env(mut self) -> Self {
383        self.storage = Some(QuickStartStorage::RedisFromEnv);
384        self
385    }
386
387    /// Use in-memory storage (development only)
388    pub fn with_memory_storage(mut self) -> Self {
389        self.storage = Some(QuickStartStorage::Memory);
390        self
391    }
392
393    /// Configure for Axum web framework
394    pub fn with_axum(mut self) -> Self {
395        self.framework = Some(QuickStartFramework::Axum);
396        self
397    }
398
399    /// Configure for Actix Web framework
400    pub fn with_actix(mut self) -> Self {
401        self.framework = Some(QuickStartFramework::ActixWeb);
402        self
403    }
404
405    /// Configure for Warp web framework
406    pub fn with_warp(mut self) -> Self {
407        self.framework = Some(QuickStartFramework::Warp);
408        self
409    }
410
411    /// Set security level
412    pub fn security_level(mut self, level: SecurityPreset) -> Self {
413        self.security_level = level;
414        self
415    }
416
417    /// Build the authentication framework
418    pub async fn build(self) -> Result<AuthFramework, AuthError> {
419        let mut builder = AuthBuilder::new().security_preset(self.security_level);
420
421        // Configure authentication method
422        match self.auth_method {
423            Some(QuickStartAuth::Jwt { secret }) => {
424                builder = builder.with_jwt().secret(secret).done();
425            }
426            Some(QuickStartAuth::JwtFromEnv) => {
427                let secret = std::env::var("JWT_SECRET").map_err(|_| {
428                    AuthError::config("JWT_SECRET environment variable is required")
429                })?;
430                builder = builder.with_jwt().secret(secret).done();
431            }
432            Some(QuickStartAuth::OAuth2 {
433                client_id,
434                client_secret,
435            }) => {
436                builder = builder
437                    .with_oauth2()
438                    .client_id(client_id)
439                    .client_secret(client_secret)
440                    .done();
441            }
442            Some(QuickStartAuth::Combined {
443                jwt_secret,
444                oauth_client_id,
445                oauth_client_secret,
446            }) => {
447                builder = builder
448                    .with_jwt()
449                    .secret(jwt_secret)
450                    .done()
451                    .with_oauth2()
452                    .client_id(oauth_client_id)
453                    .client_secret(oauth_client_secret)
454                    .done();
455            }
456            None => {
457                return Err(AuthError::config("Authentication method is required"));
458            }
459        }
460
461        // Configure storage
462        match self.storage {
463            Some(QuickStartStorage::Memory) => {
464                builder = builder.with_storage().memory().done();
465            }
466            Some(QuickStartStorage::Postgres(conn_str)) => {
467                builder = builder.with_storage().postgres(conn_str).done();
468            }
469            Some(QuickStartStorage::PostgresFromEnv) => {
470                let conn_str = std::env::var("DATABASE_URL").map_err(|_| {
471                    AuthError::config("DATABASE_URL environment variable is required")
472                })?;
473                builder = builder.with_storage().postgres(conn_str).done();
474            }
475            Some(QuickStartStorage::Redis(_conn_str)) => {
476                // Redis storage not yet implemented, fallback to memory
477                builder = builder.with_storage().memory().done();
478            }
479            Some(QuickStartStorage::RedisFromEnv) => {
480                // Redis storage not yet implemented, fallback to memory
481                builder = builder.with_storage().memory().done();
482            }
483            None => {
484                // Default to memory storage for quick start
485                builder = builder.with_storage().memory().done();
486            }
487        }
488
489        builder.build().await
490    }
491}
492
493/// JWT configuration builder
494pub struct JwtBuilder {
495    parent: AuthBuilder,
496    secret: Option<String>,
497    issuer: Option<String>,
498    audience: Option<String>,
499    token_lifetime: Option<Duration>,
500}
501
502impl JwtBuilder {
503    fn new(parent: AuthBuilder) -> Self {
504        Self {
505            parent,
506            secret: None,
507            issuer: None,
508            audience: None,
509            token_lifetime: None,
510        }
511    }
512
513    /// Set JWT secret key
514    pub fn secret(mut self, secret: impl Into<String>) -> Self {
515        self.secret = Some(secret.into());
516        self
517    }
518
519    /// Load JWT secret from environment variable
520    pub fn secret_from_env(mut self, env_var: &str) -> Self {
521        if let Ok(secret) = std::env::var(env_var) {
522            self.secret = Some(secret);
523        }
524        self
525    }
526
527    /// Set JWT issuer
528    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
529        self.issuer = Some(issuer.into());
530        self
531    }
532
533    /// Set JWT audience
534    pub fn audience(mut self, audience: impl Into<String>) -> Self {
535        self.audience = Some(audience.into());
536        self
537    }
538
539    /// Set token lifetime
540    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
541        self.token_lifetime = Some(lifetime);
542        self
543    }
544
545    /// Complete JWT configuration and return to main builder
546    pub fn done(mut self) -> AuthBuilder {
547        if let Some(secret) = self.secret {
548            self.parent.config.secret = Some(secret);
549        }
550        if let Some(issuer) = self.issuer {
551            self.parent.config.issuer = issuer;
552        }
553        if let Some(audience) = self.audience {
554            self.parent.config.audience = audience;
555        }
556        if let Some(lifetime) = self.token_lifetime {
557            self.parent.config.token_lifetime = lifetime;
558        }
559        self.parent
560    }
561}
562
563/// OAuth2 configuration builder
564pub struct OAuth2Builder {
565    parent: AuthBuilder,
566    client_id: Option<String>,
567    client_secret: Option<String>,
568    redirect_uri: Option<String>,
569}
570
571impl OAuth2Builder {
572    fn new(parent: AuthBuilder) -> Self {
573        Self {
574            parent,
575            client_id: None,
576            client_secret: None,
577            redirect_uri: None,
578        }
579    }
580
581    /// Set OAuth2 client ID
582    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
583        self.client_id = Some(client_id.into());
584        self
585    }
586
587    /// Set OAuth2 client secret
588    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
589        self.client_secret = Some(client_secret.into());
590        self
591    }
592
593    /// Set redirect URI
594    pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
595        self.redirect_uri = Some(redirect_uri.into());
596        self
597    }
598
599    /// Configure Google OAuth2
600    pub fn google_client_id(self, client_id: impl Into<String>) -> Self {
601        self.client_id(client_id)
602    }
603
604    /// Configure GitHub OAuth2
605    pub fn github_client_id(self, client_id: impl Into<String>) -> Self {
606        self.client_id(client_id)
607    }
608
609    /// Complete OAuth2 configuration and return to main builder
610    pub fn done(self) -> AuthBuilder {
611        // OAuth2 configuration would be stored in method_configs
612        // This is a simplified version
613        self.parent
614    }
615}
616
617/// Storage configuration builder
618pub struct StorageBuilder {
619    parent: AuthBuilder,
620}
621
622impl StorageBuilder {
623    fn new(parent: AuthBuilder) -> Self {
624        Self { parent }
625    }
626
627    /// Configure in-memory storage
628    pub fn memory(mut self) -> Self {
629        self.parent.config.storage = StorageConfig::Memory;
630        self
631    }
632
633    /// Configure PostgreSQL storage
634    #[cfg(feature = "postgres-storage")]
635    pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
636        self.parent.config.storage = StorageConfig::Postgres {
637            connection_string: connection_string.into(),
638            table_prefix: "auth_".to_string(),
639        };
640        self
641    }
642
643    /// Configure PostgreSQL storage from environment
644    #[cfg(feature = "postgres-storage")]
645    pub fn postgres_from_env(mut self) -> Self {
646        if let Ok(conn_str) = std::env::var("DATABASE_URL") {
647            self = self.postgres(conn_str);
648        }
649        self
650    }
651
652    /// Configure Redis storage
653    #[cfg(feature = "redis-storage")]
654    pub fn redis(mut self, url: impl Into<String>) -> Self {
655        self.parent.config.storage = StorageConfig::Redis {
656            url: url.into(),
657            key_prefix: "auth:".to_string(),
658        };
659        self
660    }
661
662    /// Configure Redis storage from environment
663    #[cfg(feature = "redis-storage")]
664    pub fn redis_from_env(mut self) -> Self {
665        if let Ok(url) = std::env::var("REDIS_URL") {
666            self = self.redis(url);
667        }
668        self
669    }
670
671    /// Set connection pool size
672    pub fn connection_pool_size(self, _size: u32) -> Self {
673        // This would be implemented when storage supports connection pooling
674        self
675    }
676
677    /// Complete storage configuration and return to main builder
678    pub fn done(self) -> AuthBuilder {
679        self.parent
680    }
681}
682
683/// Rate limiting configuration builder
684pub struct RateLimitBuilder {
685    parent: AuthBuilder,
686}
687
688impl RateLimitBuilder {
689    fn new(parent: AuthBuilder) -> Self {
690        Self { parent }
691    }
692
693    /// Configure rate limiting per IP
694    pub fn per_ip(mut self, (requests, window): (u32, Duration)) -> Self {
695        self.parent.config.rate_limiting = RateLimitConfig {
696            enabled: true,
697            max_requests: requests,
698            window,
699            burst: requests / 10,
700        };
701        self
702    }
703
704    /// Disable rate limiting
705    pub fn disabled(mut self) -> Self {
706        self.parent.config.rate_limiting.enabled = false;
707        self
708    }
709
710    /// Complete rate limiting configuration and return to main builder
711    pub fn done(self) -> AuthBuilder {
712        self.parent
713    }
714}
715
716/// Security configuration builder
717pub struct SecurityBuilder {
718    parent: AuthBuilder,
719}
720
721impl SecurityBuilder {
722    fn new(parent: AuthBuilder) -> Self {
723        Self { parent }
724    }
725
726    /// Set minimum password length
727    pub fn min_password_length(mut self, length: usize) -> Self {
728        self.parent.config.security.min_password_length = length;
729        self
730    }
731
732    /// Enable/disable password complexity requirements
733    pub fn require_password_complexity(mut self, required: bool) -> Self {
734        self.parent.config.security.require_password_complexity = required;
735        self
736    }
737
738    /// Enable/disable secure cookies
739    pub fn secure_cookies(mut self, enabled: bool) -> Self {
740        self.parent.config.security.secure_cookies = enabled;
741        self
742    }
743
744    /// Complete security configuration and return to main builder
745    pub fn done(self) -> AuthBuilder {
746        self.parent
747    }
748}
749
750/// Audit configuration builder
751pub struct AuditBuilder {
752    parent: AuthBuilder,
753}
754
755impl AuditBuilder {
756    fn new(parent: AuthBuilder) -> Self {
757        Self { parent }
758    }
759
760    /// Enable audit logging
761    pub fn enabled(mut self, enabled: bool) -> Self {
762        self.parent.config.audit.enabled = enabled;
763        self
764    }
765
766    /// Log successful authentications
767    pub fn log_success(mut self, enabled: bool) -> Self {
768        self.parent.config.audit.log_success = enabled;
769        self
770    }
771
772    /// Log failed authentications
773    pub fn log_failures(mut self, enabled: bool) -> Self {
774        self.parent.config.audit.log_failures = enabled;
775        self
776    }
777
778    /// Complete audit configuration and return to main builder
779    pub fn done(self) -> AuthBuilder {
780        self.parent
781    }
782}
783
784impl Default for AuthBuilder {
785    fn default() -> Self {
786        Self::new()
787    }
788}