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