Skip to main content

auth_framework/api/
mod.rs

1//! REST API Server Module
2//!
3//! This module provides a comprehensive REST API server implementation
4//! that exposes all AuthFramework functionality through HTTP endpoints.
5
6pub mod admin;
7pub mod advanced_protocols;
8pub mod auth;
9pub mod email_verification;
10pub mod error_codes;
11pub mod health;
12pub mod metrics;
13pub mod mfa;
14pub mod middleware;
15pub mod oauth2;
16pub mod oauth_advanced;
17pub mod openapi;
18pub mod responses;
19pub mod saml;
20pub mod security;
21pub mod security_simple;
22pub mod server;
23pub mod users;
24pub mod validation;
25pub mod versioning;
26pub mod webauthn;
27
28#[cfg(feature = "enhanced-rbac")]
29#[cfg(feature = "role-system")]
30pub mod rbac_endpoints;
31
32pub use responses::{ApiError, ApiResponse, ApiResult};
33pub use security::SecurityManager;
34pub use server::ApiServer;
35
36use crate::AuthFramework;
37use crate::distributed::rate_limiting::{DistributedRateLimiter, RateLimitConfig};
38use crate::errors::AuthError;
39use std::sync::Arc;
40
41/// API server state
42#[derive(Clone)]
43pub struct ApiState {
44    pub auth_framework: Arc<AuthFramework>,
45    pub rate_limiter: Arc<DistributedRateLimiter>,
46    #[cfg(feature = "enhanced-rbac")]
47    pub authorization_service: Arc<crate::authorization_enhanced::AuthorizationService>,
48}
49
50impl ApiState {
51    /// Create an [`ApiState`] wrapping the given [`AuthFramework`].
52    ///
53    /// A balanced distributed rate-limiter is initialised automatically.
54    ///
55    /// # Example
56    /// ```rust,ignore
57    /// let state = ApiState::new(Arc::new(auth_framework)).await?;
58    /// ```
59    pub async fn new(auth_framework: Arc<AuthFramework>) -> crate::errors::Result<Self> {
60        let rate_limiter =
61            Arc::new(DistributedRateLimiter::new(RateLimitConfig::balanced()).await?);
62        Ok(Self {
63            auth_framework,
64            rate_limiter,
65            #[cfg(feature = "enhanced-rbac")]
66            authorization_service: Arc::new(
67                crate::authorization_enhanced::AuthorizationService::new().await?,
68            ),
69        })
70    }
71
72    /// Build an [`ApiState`] with a pre-constructed authorization service.
73    ///
74    /// # Example
75    /// ```rust,ignore
76    /// let state = ApiState::with_authorization_service(fw, limiter, authz);
77    /// ```
78    #[cfg(feature = "enhanced-rbac")]
79    pub fn with_authorization_service(
80        auth_framework: Arc<AuthFramework>,
81        rate_limiter: Arc<DistributedRateLimiter>,
82        authorization_service: Arc<crate::authorization_enhanced::AuthorizationService>,
83    ) -> Self {
84        Self {
85            auth_framework,
86            rate_limiter,
87            authorization_service,
88        }
89    }
90}
91
92/// Extract bearer token from Authorization header
93pub fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<String> {
94    headers
95        .get("authorization")
96        .and_then(|header| header.to_str().ok())
97        .and_then(|auth_str| auth_str.strip_prefix("Bearer "))
98        .filter(|token| !token.is_empty())
99        .map(|token| token.to_string())
100}
101
102/// Validate API token and extract user information
103pub async fn validate_api_token(
104    auth_framework: &AuthFramework,
105    token: &str,
106) -> Result<crate::tokens::AuthToken, AuthError> {
107    // Validate the JWT signature and expiry
108    let token_obj = auth_framework.token_manager().validate_jwt_token(token)?;
109
110    // Check whether this token has been explicitly revoked (e.g. via logout)
111    let revocation_key = format!("revoked_token:{}", token_obj.jti);
112    match auth_framework.storage().get_kv(&revocation_key).await {
113        Ok(Some(_)) => {
114            return Err(AuthError::Unauthorized(
115                "Token has been revoked".to_string(),
116            ));
117        }
118        Ok(None) => {} // Not revoked — proceed
119        Err(e) => {
120            tracing::error!("Could not check token revocation list: {}", e);
121            return Err(AuthError::Unauthorized(
122                "Unable to verify token status".to_string(),
123            ));
124        }
125    }
126
127    // Convert the validated token claims to AuthToken.
128    // Roles are not embedded in JWT claims (create_jwt_token sets roles: None),
129    // so we load them from the user record in KV storage to allow role-based
130    // access checks (e.g. admin endpoints) to work correctly.
131    let user_id_str = token_obj.sub.clone();
132    let roles = {
133        let user_key = format!("user:{}", user_id_str);
134        match auth_framework.storage().get_kv(&user_key).await {
135            Ok(Some(bytes)) => {
136                let json: serde_json::Value = match serde_json::from_slice(&bytes) {
137                    Ok(v) => v,
138                    Err(e) => {
139                        tracing::warn!(user_id = %user_id_str, "Failed to parse user record JSON for role extraction: {}", e);
140                        serde_json::Value::default()
141                    }
142                };
143                // Check if account is active
144                if json["active"].as_bool() == Some(false) {
145                    return Err(AuthError::Unauthorized("Account is disabled".to_string()));
146                }
147                json["roles"]
148                    .as_array()
149                    .map(|arr| {
150                        arr.iter()
151                            .filter_map(|v| v.as_str())
152                            .map(|s| s.to_string())
153                            .collect::<Vec<_>>()
154                    })
155                    .unwrap_or_else(|| token_obj.roles.clone().unwrap_or_default())
156            }
157            _ => token_obj.roles.clone().unwrap_or_default(),
158        }
159    };
160
161    Ok(crate::tokens::AuthToken {
162        token_id: token_obj.jti.clone(),
163        user_id: user_id_str.clone(),
164        access_token: token.to_string(),
165        token_type: Some("Bearer".to_string()),
166        subject: Some(user_id_str.clone()),
167        issuer: Some(token_obj.iss.clone()),
168        refresh_token: None,
169        issued_at: chrono::DateTime::from_timestamp(token_obj.iat, 0)
170            .unwrap_or_else(chrono::Utc::now),
171        expires_at: chrono::DateTime::from_timestamp(token_obj.exp, 0)
172            .unwrap_or_else(chrono::Utc::now),
173        scopes: token_obj
174            .scope
175            .split_whitespace()
176            .map(|s| s.to_string())
177            .collect(),
178        auth_method: "jwt".to_string(),
179        client_id: token_obj.client_id,
180        user_profile: None,
181        permissions: token_obj.permissions.unwrap_or_default().into(),
182        roles: roles.into(),
183        metadata: crate::tokens::TokenMetadata {
184            session_id: None, // JWT tokens don't have session_id in claims by default
185            ..Default::default()
186        },
187    })
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use axum::http::HeaderMap;
194
195    #[test]
196    fn test_extract_bearer_token_valid() {
197        let mut headers = HeaderMap::new();
198        headers.insert("authorization", "Bearer mytoken123".parse().unwrap());
199        assert_eq!(
200            extract_bearer_token(&headers),
201            Some("mytoken123".to_string())
202        );
203    }
204
205    #[test]
206    fn test_extract_bearer_token_missing() {
207        let headers = HeaderMap::new();
208        assert_eq!(extract_bearer_token(&headers), None);
209    }
210
211    #[test]
212    fn test_extract_bearer_token_not_bearer() {
213        let mut headers = HeaderMap::new();
214        headers.insert("authorization", "Basic abc123".parse().unwrap());
215        assert_eq!(extract_bearer_token(&headers), None);
216    }
217
218    #[test]
219    fn test_extract_bearer_token_empty_value() {
220        let mut headers = HeaderMap::new();
221        headers.insert("authorization", "Bearer ".parse().unwrap());
222        // SEC-6: Empty bearer tokens are rejected
223        assert_eq!(extract_bearer_token(&headers), None);
224    }
225
226    #[tokio::test]
227    async fn test_validate_api_token_invalid() {
228        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
229        let fw = AuthFramework::new(config);
230        let result = validate_api_token(&fw, "not.a.valid.token").await;
231        assert!(result.is_err());
232    }
233
234    #[tokio::test]
235    async fn test_validate_api_token_revoked() {
236        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
237        let mut fw = AuthFramework::new(config);
238        fw.initialize().await.unwrap();
239
240        // Create a valid JWT token
241        let token = fw
242            .token_manager()
243            .create_jwt_token("user1", vec!["user".into()], None)
244            .unwrap();
245        let token_obj = fw.token_manager().validate_jwt_token(&token).unwrap();
246
247        // Revoke it
248        let revocation_key = format!("revoked_token:{}", token_obj.jti);
249        fw.storage()
250            .store_kv(&revocation_key, b"revoked", None)
251            .await
252            .unwrap();
253
254        // Should fail with "revoked"
255        let result = validate_api_token(&fw, &token).await;
256        assert!(result.is_err());
257        let err_msg = format!("{}", result.unwrap_err());
258        assert!(err_msg.contains("revoked"));
259    }
260
261    #[tokio::test]
262    async fn test_validate_api_token_success() {
263        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
264        let mut fw = AuthFramework::new(config);
265        fw.initialize().await.unwrap();
266
267        let token = fw
268            .token_manager()
269            .create_jwt_token("user_abc", vec!["user".into()], None)
270            .unwrap();
271
272        let auth_token = validate_api_token(&fw, &token).await.unwrap();
273        assert_eq!(auth_token.user_id, "user_abc");
274        assert_eq!(auth_token.auth_method, "jwt");
275        assert_eq!(auth_token.token_type.as_deref(), Some("Bearer"));
276    }
277
278    #[tokio::test]
279    async fn test_validate_api_token_with_roles_from_storage() {
280        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
281        let mut fw = AuthFramework::new(config);
282        fw.initialize().await.unwrap();
283
284        // Store a user profile with an admin role
285        let user_json = serde_json::json!({"user_id": "role_user", "roles": ["admin", "editor"]});
286        fw.storage()
287            .store_kv(
288                "user:role_user",
289                serde_json::to_vec(&user_json).unwrap().as_slice(),
290                None,
291            )
292            .await
293            .unwrap();
294
295        let token = fw
296            .token_manager()
297            .create_jwt_token("role_user", vec!["user".into()], None)
298            .unwrap();
299
300        let auth_token = validate_api_token(&fw, &token).await.unwrap();
301        assert!(auth_token.roles.contains(&"admin".to_string()));
302        assert!(auth_token.roles.contains(&"editor".to_string()));
303    }
304}