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    //
133    // The signature only proves who minted the token, not that its
134    // subject is a real account, so a missing or unreadable record is a
135    // rejection, never an empty-roles fallback.
136    let roles = {
137        let user_key = format!("user:{}", user_id_str);
138        match auth_framework.storage().get_kv(&user_key).await {
139            Ok(Some(bytes)) => {
140                let json: serde_json::Value = match serde_json::from_slice(&bytes) {
141                    Ok(v) => v,
142                    Err(e) => {
143                        tracing::warn!(user_id = %user_id_str, "Failed to parse user record JSON: {}", e);
144                        return Err(AuthError::Unauthorized(
145                            "Unable to verify account".to_string(),
146                        ));
147                    }
148                };
149                // Check if account is active
150                if json["active"].as_bool() == Some(false) {
151                    return Err(AuthError::Unauthorized("Account is disabled".to_string()));
152                }
153                json["roles"]
154                    .as_array()
155                    .map(|arr| {
156                        arr.iter()
157                            .filter_map(|v| v.as_str())
158                            .map(|s| s.to_string())
159                            .collect::<Vec<_>>()
160                    })
161                    .unwrap_or_else(|| token_obj.roles.clone().unwrap_or_default())
162            }
163            Ok(None) => {
164                return Err(AuthError::Unauthorized("Unknown account".to_string()));
165            }
166            Err(e) => {
167                tracing::error!("Could not load user record for token validation: {}", e);
168                return Err(AuthError::Unauthorized(
169                    "Unable to verify account".to_string(),
170                ));
171            }
172        }
173    };
174
175    Ok(crate::tokens::AuthToken {
176        token_id: token_obj.jti.clone(),
177        user_id: user_id_str.clone(),
178        access_token: token.to_string(),
179        token_type: Some("Bearer".to_string()),
180        subject: Some(user_id_str.clone()),
181        issuer: Some(token_obj.iss.clone()),
182        refresh_token: None,
183        issued_at: chrono::DateTime::from_timestamp(token_obj.iat, 0)
184            .unwrap_or_else(chrono::Utc::now),
185        expires_at: chrono::DateTime::from_timestamp(token_obj.exp, 0)
186            .unwrap_or_else(chrono::Utc::now),
187        scopes: token_obj
188            .scope
189            .split_whitespace()
190            .map(|s| s.to_string())
191            .collect(),
192        auth_method: "jwt".to_string(),
193        client_id: token_obj.client_id,
194        user_profile: None,
195        permissions: token_obj.permissions.unwrap_or_default().into(),
196        roles: roles.into(),
197        metadata: crate::tokens::TokenMetadata {
198            session_id: None, // JWT tokens don't have session_id in claims by default
199            ..Default::default()
200        },
201    })
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use axum::http::HeaderMap;
208
209    #[test]
210    fn test_extract_bearer_token_valid() {
211        let mut headers = HeaderMap::new();
212        headers.insert("authorization", "Bearer mytoken123".parse().unwrap());
213        assert_eq!(
214            extract_bearer_token(&headers),
215            Some("mytoken123".to_string())
216        );
217    }
218
219    #[test]
220    fn test_extract_bearer_token_missing() {
221        let headers = HeaderMap::new();
222        assert_eq!(extract_bearer_token(&headers), None);
223    }
224
225    #[test]
226    fn test_extract_bearer_token_not_bearer() {
227        let mut headers = HeaderMap::new();
228        headers.insert("authorization", "Basic abc123".parse().unwrap());
229        assert_eq!(extract_bearer_token(&headers), None);
230    }
231
232    #[test]
233    fn test_extract_bearer_token_empty_value() {
234        let mut headers = HeaderMap::new();
235        headers.insert("authorization", "Bearer ".parse().unwrap());
236        // SEC-6: Empty bearer tokens are rejected
237        assert_eq!(extract_bearer_token(&headers), None);
238    }
239
240    #[tokio::test]
241    async fn test_validate_api_token_invalid() {
242        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
243        let fw = AuthFramework::new(config);
244        let result = validate_api_token(&fw, "not.a.valid.token").await;
245        assert!(result.is_err());
246    }
247
248    #[tokio::test]
249    async fn test_validate_api_token_revoked() {
250        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
251        let mut fw = AuthFramework::new(config);
252        fw.initialize().await.unwrap();
253
254        // Create a valid JWT token
255        let token = fw
256            .token_manager()
257            .create_jwt_token("user1", vec!["user".into()], None)
258            .unwrap();
259        let token_obj = fw.token_manager().validate_jwt_token(&token).unwrap();
260
261        // Revoke it
262        let revocation_key = format!("revoked_token:{}", token_obj.jti);
263        fw.storage()
264            .store_kv(&revocation_key, b"revoked", None)
265            .await
266            .unwrap();
267
268        // Should fail with "revoked"
269        let result = validate_api_token(&fw, &token).await;
270        assert!(result.is_err());
271        let err_msg = format!("{}", result.unwrap_err());
272        assert!(err_msg.contains("revoked"));
273    }
274
275    #[tokio::test]
276    async fn test_validate_api_token_success() {
277        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
278        let mut fw = AuthFramework::new(config);
279        fw.initialize().await.unwrap();
280
281        store_test_user(&fw, "user_abc", true).await;
282        let token = fw
283            .token_manager()
284            .create_jwt_token("user_abc", vec!["user".into()], None)
285            .unwrap();
286
287        let auth_token = validate_api_token(&fw, &token).await.unwrap();
288        assert_eq!(auth_token.user_id, "user_abc");
289        assert_eq!(auth_token.auth_method, "jwt");
290        assert_eq!(auth_token.token_type.as_deref(), Some("Bearer"));
291    }
292
293    async fn store_test_user(fw: &AuthFramework, user_id: &str, active: bool) {
294        let record = serde_json::json!({"user_id": user_id, "active": active});
295        fw.storage()
296            .store_kv(
297                &format!("user:{user_id}"),
298                serde_json::to_vec(&record).unwrap().as_slice(),
299                None,
300            )
301            .await
302            .unwrap();
303    }
304
305    /// A validly signed token whose `sub` has no user record must not be
306    /// accepted: the signature proves who minted it, not that the subject
307    /// is a real account.
308    #[tokio::test]
309    async fn test_validate_api_token_rejects_subject_without_user_record() {
310        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
311        let mut fw = AuthFramework::new(config);
312        fw.initialize().await.unwrap();
313
314        let token = fw
315            .token_manager()
316            .create_jwt_token("user_does_not_exist", vec!["user".into()], None)
317            .unwrap();
318
319        let result = validate_api_token(&fw, &token).await;
320        assert!(result.is_err(), "unknown subject must be rejected");
321    }
322
323    #[tokio::test]
324    async fn test_validate_api_token_rejects_inactive_user() {
325        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
326        let mut fw = AuthFramework::new(config);
327        fw.initialize().await.unwrap();
328        store_test_user(&fw, "user_off", false).await;
329        let token = fw
330            .token_manager()
331            .create_jwt_token("user_off", vec!["user".into()], None)
332            .unwrap();
333        assert!(validate_api_token(&fw, &token).await.is_err());
334    }
335
336    #[tokio::test]
337    async fn test_validate_api_token_with_roles_from_storage() {
338        let config = crate::AuthConfig::new().secret("a]Bc!d@e#f$g%h^i&j*k(l)m_n-o+p=q");
339        let mut fw = AuthFramework::new(config);
340        fw.initialize().await.unwrap();
341
342        // Store a user profile with an admin role
343        let user_json = serde_json::json!({"user_id": "role_user", "roles": ["admin", "editor"]});
344        fw.storage()
345            .store_kv(
346                "user:role_user",
347                serde_json::to_vec(&user_json).unwrap().as_slice(),
348                None,
349            )
350            .await
351            .unwrap();
352
353        let token = fw
354            .token_manager()
355            .create_jwt_token("role_user", vec!["user".into()], None)
356            .unwrap();
357
358        let auth_token = validate_api_token(&fw, &token).await.unwrap();
359        assert!(auth_token.roles.contains("admin"));
360        assert!(auth_token.roles.contains("editor"));
361    }
362}