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