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