auth-framework 0.4.2

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Axum integration for auth-framework with enhanced ergonomics.
//!
//! This module provides middleware, extractors, and helper functions for easy integration
//! with Axum web applications. The ergonomic improvements include:
//!
//! - Simple middleware setup with `RequireAuth` and `RequirePermission`
//! - Automatic route protection with `protected()` wrapper
//! - Easy user extraction with `AuthenticatedUser`
//! - Builder pattern for auth routes
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use auth_framework::prelude::*;
//! use axum::{Router, routing::get};
//!
//! let auth = AuthFramework::quick_start()
//!     .jwt_auth_from_env()
//!     .with_axum()
//!     .build().await?;
//!
//! let app = Router::new()
//!     .route("/public", get(public_handler))
//!     .route("/protected", get(protected(protected_handler)))
//!     .route("/admin", get(protected(admin_handler).require_role("admin")))
//!     .with_state(auth);
//! ```
//!
//! # Advanced Usage
//!
//! ```rust,no_run
//! use auth_framework::prelude::*;
//! use auth_framework::integrations::axum::*;
//!
//! // Custom auth routes
//! let auth_routes = AuthRouter::new()
//!     .login_route("/auth/login")
//!     .logout_route("/auth/logout")
//!     .refresh_route("/auth/refresh")
//!     .build();
//!
//! let app = Router::new()
//!     .merge(auth_routes)
//!     .route("/api/profile", get(profile_handler))
//!     .layer(RequireAuth::new())
//!     .with_state(auth);
//! ```

use crate::{AuthError, AuthFramework, AuthToken};
use axum::{
    Json, Router,
    extract::{FromRequestParts, Request, State},
    http::{StatusCode, header::AUTHORIZATION, request::Parts},
    middleware::Next,
    response::{IntoResponse, Response},
    routing::post,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Ergonomic authentication middleware that can be easily applied to routes
#[derive(Clone)]
pub struct RequireAuth {
    /// Optional specific permissions required
    pub required_permissions: Vec<String>,
    /// Optional specific roles required
    pub required_roles: Vec<String>,
}

/// Ergonomic permission middleware for fine-grained access control
#[derive(Clone)]
pub struct RequirePermission {
    /// The permission required to access the route
    pub permission: String,
    /// Optional resource context for the permission
    pub resource: Option<String>,
}

/// Authenticated user extractor that automatically validates tokens
#[derive(Debug, Clone, Serialize)]
pub struct AuthenticatedUser {
    pub user_id: String,
    pub permissions: Vec<String>,
    pub roles: Vec<String>,
    pub token: AuthToken,
}

/// Builder for creating authentication-related routes
pub struct AuthRouter {
    login_path: String,
    logout_path: String,
    refresh_path: String,
    profile_path: String,
}

/// Request/response types for auth endpoints
#[derive(Debug, Deserialize)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Serialize)]
pub struct LoginResponse {
    pub access_token: String,
    pub refresh_token: Option<String>,
    pub expires_in: u64,
    pub user: UserInfo,
}

#[derive(Debug, Serialize)]
pub struct UserInfo {
    pub id: String,
    pub username: Option<String>,
    pub email: Option<String>,
    pub roles: Vec<String>,
}

/// Protected route wrapper that automatically applies authentication
pub fn protected<F, T>(handler: F) -> ProtectedHandler<F>
where
    F: Clone,
{
    ProtectedHandler::new(handler)
}

/// Protected handler wrapper
#[derive(Clone)]
pub struct ProtectedHandler<F> {
    handler: F,
    required_permissions: Vec<String>,
    required_roles: Vec<String>,
}

impl RequireAuth {
    /// Create a new authentication middleware
    pub fn new() -> Self {
        Self {
            required_permissions: Vec::new(),
            required_roles: Vec::new(),
        }
    }

    /// Require specific permissions
    pub fn with_permissions(mut self, permissions: &[&str]) -> Self {
        self.required_permissions = permissions.iter().map(|p| p.to_string()).collect();
        self
    }

    /// Require specific roles
    pub fn with_roles(mut self, roles: &[&str]) -> Self {
        self.required_roles = roles.iter().map(|r| r.to_string()).collect();
        self
    }
}

impl RequirePermission {
    /// Create a new permission middleware
    pub fn new(permission: impl Into<String>) -> Self {
        Self {
            permission: permission.into(),
            resource: None,
        }
    }

    /// Set the resource context for the permission
    pub fn for_resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(resource.into());
        self
    }
}

impl<F> ProtectedHandler<F> {
    fn new(handler: F) -> Self {
        Self {
            handler,
            required_permissions: Vec::new(),
            required_roles: Vec::new(),
        }
    }

    /// Require specific permissions for this route
    pub fn require_permissions(mut self, permissions: &[&str]) -> Self {
        self.required_permissions = permissions.iter().map(|p| p.to_string()).collect();
        self
    }

    /// Require specific roles for this route
    pub fn require_roles(mut self, roles: &[&str]) -> Self {
        self.required_roles = roles.iter().map(|r| r.to_string()).collect();
        self
    }

    /// Require a single permission (convenience method)
    pub fn require_permission(mut self, permission: &str) -> Self {
        self.required_permissions = vec![permission.to_string()];
        self
    }

    /// Require a single role (convenience method)
    pub fn require_role(mut self, role: &str) -> Self {
        self.required_roles = vec![role.to_string()];
        self
    }
}

impl AuthRouter {
    /// Create a new auth router builder
    pub fn new() -> Self {
        Self {
            login_path: "/auth/login".to_string(),
            logout_path: "/auth/logout".to_string(),
            refresh_path: "/auth/refresh".to_string(),
            profile_path: "/auth/profile".to_string(),
        }
    }

    /// Set custom login route path
    pub fn login_route(mut self, path: impl Into<String>) -> Self {
        self.login_path = path.into();
        self
    }

    /// Set custom logout route path
    pub fn logout_route(mut self, path: impl Into<String>) -> Self {
        self.logout_path = path.into();
        self
    }

    /// Set custom token refresh route path
    pub fn refresh_route(mut self, path: impl Into<String>) -> Self {
        self.refresh_path = path.into();
        self
    }

    /// Set custom user profile route path
    pub fn profile_route(mut self, path: impl Into<String>) -> Self {
        self.profile_path = path.into();
        self
    }

    /// Build the auth routes and return a Router
    pub fn build(self) -> Router<Arc<AuthFramework>> {
        Router::new()
            .route(&self.login_path, post(login_handler))
            // .route(&self.logout_path, post(logout_handler))  // Temporarily disabled due to trait issues
            .route(&self.refresh_path, post(refresh_handler))
        // .route(&self.profile_path, get(profile_handler))  // Temporarily disabled due to trait issues
    }
}

// Route handlers for authentication endpoints
async fn login_handler(
    State(auth): State<Arc<AuthFramework>>,
    Json(request): Json<LoginRequest>,
) -> Result<impl IntoResponse, AuthError> {
    // This is a simplified login implementation
    // In a real implementation, you'd validate credentials against your user store

    let token = auth
        .create_auth_token(
            &request.username,
            vec!["read".to_string(), "write".to_string()],
            "jwt",
            None,
        )
        .await?;

    let response = LoginResponse {
        access_token: token.access_token.clone(),
        refresh_token: token.refresh_token.clone(),
        expires_in: 3600, // 1 hour
        user: UserInfo {
            id: token.user_id.clone(),
            username: Some(request.username),
            email: None,
            roles: token.roles.clone(),
        },
    };

    Ok(Json(response))
}

async fn logout_handler(
    State(_auth): State<Arc<AuthFramework>>,
    user: AuthenticatedUser,
) -> Result<impl IntoResponse, AuthError> {
    // In a real implementation, you'd revoke the token
    tracing::info!("User {} logged out", user.user_id);
    Ok(Json(
        serde_json::json!({"message": "Successfully logged out"}),
    ))
}

async fn refresh_handler(
    State(_auth): State<Arc<AuthFramework>>,
    // Extract refresh token from request
) -> Result<impl IntoResponse, AuthError> {
    // This would implement token refresh logic
    // For now, return a placeholder
    Ok(Json(
        serde_json::json!({"message": "Token refresh not implemented"}),
    ))
}

async fn profile_handler(user: AuthenticatedUser) -> Result<impl IntoResponse, AuthError> {
    Ok(Json(UserInfo {
        id: user.user_id,
        username: None, // Would come from user store
        email: None,    // Would come from user store
        roles: user.roles,
    }))
}

/// Authentication middleware implementation
pub async fn auth_middleware(
    State(auth): State<Arc<AuthFramework>>,
    mut request: Request,
    next: Next,
) -> Result<Response, AuthError> {
    let token_str = extract_bearer_token(&request)?;

    // Validate token using AuthFramework
    match auth.token_manager().validate_jwt_token(&token_str) {
        Ok(_claims) => {
            // Store token in request extensions for later extraction
            request.extensions_mut().insert(token_str);
            Ok(next.run(request).await)
        }
        Err(e) => Err(e),
    }
}

/// Extract bearer token from Authorization header
fn extract_bearer_token(request: &Request) -> Result<String, AuthError> {
    let auth_header = request
        .headers()
        .get(AUTHORIZATION)
        .and_then(|header| header.to_str().ok())
        .ok_or_else(|| AuthError::Token(crate::errors::TokenError::Missing))?;

    if auth_header.starts_with("Bearer ") {
        Ok(auth_header[7..].to_string())
    } else {
        Err(AuthError::Token(crate::errors::TokenError::Invalid {
            message: "Authorization header must use Bearer scheme".to_string(),
        }))
    }
}

/// Implement FromRequestParts for AuthenticatedUser extractor
impl<S> FromRequestParts<S> for AuthenticatedUser
where
    S: Send + Sync,
    Arc<AuthFramework>: FromRequestParts<S>,
{
    type Rejection = AuthError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // Extract auth framework from state
        let _auth = Arc::<AuthFramework>::from_request_parts(parts, state)
            .await
            .map_err(|_| AuthError::internal("Failed to extract auth framework from state"))?;

        // Extract token from request
        let token_str = extract_bearer_token_from_parts(parts)?;

        // Get token details - this is a simplified version
        // In a real implementation, you'd decode the JWT and extract user info
        let user_id = "demo_user".to_string(); // Would come from JWT claims
        let permissions = vec!["read".to_string(), "write".to_string()]; // Would come from JWT/database
        let roles = vec!["user".to_string()]; // Would come from JWT/database

        // Create a mock token for demonstration
        // In reality, you'd either decode the existing token or fetch from storage
        let token = AuthToken {
            token_id: "demo_token_id".to_string(),
            user_id: user_id.clone(),
            access_token: token_str,
            token_type: Some("Bearer".to_string()),
            subject: Some(user_id.clone()),
            issuer: Some("auth-framework".to_string()),
            refresh_token: None,
            issued_at: chrono::Utc::now(),
            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
            scopes: vec!["read".to_string(), "write".to_string()],
            auth_method: "jwt".to_string(),
            client_id: None,
            user_profile: None,
            permissions: permissions.clone(),
            roles: roles.clone(),
            metadata: crate::tokens::TokenMetadata::default(),
        };

        Ok(AuthenticatedUser {
            user_id,
            permissions,
            roles,
            token,
        })
    }
}

fn extract_bearer_token_from_parts(parts: &Parts) -> Result<String, AuthError> {
    let auth_header = parts
        .headers
        .get(AUTHORIZATION)
        .and_then(|header| header.to_str().ok())
        .ok_or_else(|| AuthError::Token(crate::errors::TokenError::Missing))?;

    if auth_header.starts_with("Bearer ") {
        Ok(auth_header[7..].to_string())
    } else {
        Err(AuthError::Token(crate::errors::TokenError::Invalid {
            message: "Authorization header must use Bearer scheme".to_string(),
        }))
    }
}

/// Implement IntoResponse for AuthError to provide proper HTTP error responses
impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (status, message) = match &self {
            AuthError::Token(_) => (StatusCode::UNAUTHORIZED, "Authentication required"),
            AuthError::Permission(_) => (StatusCode::FORBIDDEN, "Insufficient permissions"),
            AuthError::RateLimit { .. } => (StatusCode::TOO_MANY_REQUESTS, "Rate limit exceeded"),
            AuthError::Configuration { .. } | AuthError::Storage(_) => {
                (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
            }
            _ => (StatusCode::BAD_REQUEST, "Bad request"),
        };

        let body = Json(serde_json::json!({
            "error": message,
            "details": self.to_string()
        }));

        (status, body).into_response()
    }
}

/// Ergonomic middleware methods for Router
pub trait AuthRouterExt<S> {
    /// Add authentication requirement to all routes
    fn require_auth(self) -> Self;

    /// Add permission requirement to all routes
    fn require_permission(self, permission: &str) -> Self;

    /// Add role requirement to all routes
    fn require_role(self, role: &str) -> Self;
}

impl<S> AuthRouterExt<S> for Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn require_auth(self) -> Self {
        self.layer(axum::middleware::from_fn_with_state(
            (), // This would need the actual auth state
            |_state: (), request: axum::extract::Request, next: axum::middleware::Next| async move {
                // This is a placeholder - would implement actual auth middleware
                next.run(request).await
            },
        ))
    }

    fn require_permission(self, _permission: &str) -> Self {
        // This would implement permission checking middleware
        self
    }

    fn require_role(self, _role: &str) -> Self {
        // This would implement role checking middleware
        self
    }
}

// Re-export for convenience
pub use RequireAuth as AuthMiddleware;