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