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