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