auth-framework 0.4.45

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Enhanced authorization middleware using role-system v1.0
//!
//! This module provides comprehensive authorization middleware for Axum,
//! replacing the basic role checking with enterprise-grade RBAC.

use crate::api::{ApiResponse, ApiState};
use crate::tokens::AuthToken;
use axum::{
    extract::{Request, State},
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::collections::HashMap;
use tracing::{debug, info, warn};

/// Enhanced RBAC middleware using role-system v1.0
#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
pub async fn rbac_middleware(
    State(state): State<ApiState>,
    request: Request,
    next: Next,
) -> Result<Response, Response> {
    // Skip auth for public endpoints
    let path = request.uri().path();
    if is_public_endpoint(path) {
        return Ok(next.run(request).await);
    }

    // Get auth token from extensions (should be set by auth_middleware)
    let auth_token = match request.extensions().get::<AuthToken>() {
        Some(token) => token.clone(),
        None => {
            let error_response = ApiResponse::<()>::unauthorized();
            return Err(error_response.into_response());
        }
    };

    // Build request context for conditional permissions
    let context = build_request_context(&request, &auth_token);

    // Check authorization using role-system
    let authorized = match check_authorization(&state, &auth_token, &request, &context).await {
        Ok(granted) => granted,
        Err(e) => {
            warn!("Authorization check failed: {}", e);
            let error_response = ApiResponse::<()>::forbidden();
            return Err(error_response.into_response());
        }
    };

    if authorized {
        debug!(
            "Authorization granted for user '{}' on {}",
            auth_token.user_id, path
        );
        Ok(next.run(request).await)
    } else {
        info!(
            "Authorization denied for user '{}' on {}",
            auth_token.user_id, path
        );
        let error_response = ApiResponse::<()>::forbidden();
        Err(error_response.into_response())
    }
}

/// Conditional permission middleware for time/location-based access
#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
pub async fn conditional_permission_middleware(
    State(state): State<ApiState>,
    request: Request,
    next: Next,
) -> Result<Response, Response> {
    let path = request.uri().path();

    // Apply conditional permissions for sensitive endpoints
    if is_sensitive_endpoint(path) {
        let auth_token = match request.extensions().get::<AuthToken>() {
            Some(token) => token,
            None => {
                let error_response = ApiResponse::<()>::unauthorized();
                return Err(error_response.into_response());
            }
        };

        let context = build_conditional_context(&request);

        // Check conditional permissions
        let has_conditional_access: bool = state
            .authorization_service
            .check_permission(&auth_token.user_id, "access", path, Some(&context))
            .await
            .unwrap_or_default();

        if !has_conditional_access {
            info!(
                "Conditional access denied for user '{}' on {}",
                auth_token.user_id, path
            );
            let error_response = ApiResponse::<()>::error(
                "CONDITIONAL_ACCESS_DENIED",
                "Access denied due to conditional permissions (time, location, etc.)",
            );
            return Err(error_response.into_response());
        }
    }

    Ok(next.run(request).await)
}

/// Role elevation middleware for administrative actions
#[allow(clippy::result_large_err)] // the Err type is part of the existing public signature; boxing it would change the API of a release line
pub async fn role_elevation_middleware(
    State(state): State<ApiState>,
    request: Request,
    next: Next,
) -> Result<Response, Response> {
    let path = request.uri().path();

    // Check if this endpoint requires elevated permissions
    if requires_role_elevation(path) {
        let auth_token = match request.extensions().get::<AuthToken>() {
            Some(token) => token,
            None => {
                let error_response = ApiResponse::<()>::unauthorized();
                return Err(error_response.into_response());
            }
        };

        // Check if user has elevated permissions
        let has_elevated_access: bool = state
            .authorization_service
            .check_permission(&auth_token.user_id, "elevated", "admin", None)
            .await
            .unwrap_or_default();

        if !has_elevated_access {
            info!(
                "Elevated access required for user '{}' on {}",
                auth_token.user_id, path
            );
            let error_response = ApiResponse::<()>::error(
                "ELEVATION_REQUIRED",
                "This action requires elevated permissions. Please request temporary role elevation.",
            );
            return Err(error_response.into_response());
        }
    }

    Ok(next.run(request).await)
}

/// Check authorization using the enhanced authorization service
async fn check_authorization(
    state: &ApiState,
    auth_token: &AuthToken,
    request: &Request,
    context: &HashMap<String, String>,
) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> {
    let method = request.method().as_str();
    let path = request.uri().path();

    // Use the enhanced authorization service
    state
        .authorization_service
        .check_api_permission(&auth_token.user_id, method, path, context)
        .await
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
}

/// Build request context for conditional permissions
fn build_request_context(request: &Request, auth_token: &AuthToken) -> HashMap<String, String> {
    let mut context = HashMap::new();

    // Add user context
    context.insert("user_id".to_string(), auth_token.user_id.clone());
    context.insert("roles".to_string(), auth_token.roles.join(","));

    // Add request metadata
    if let Some(user_agent) = request.headers().get("user-agent")
        && let Ok(ua_str) = user_agent.to_str()
    {
        context.insert("user_agent".to_string(), ua_str.to_string());
    }

    // Add IP address: the connection's peer. A client-supplied X-Forwarded-For is never
    // copied into the context (use `ContextBuilder::with_trusted_proxies` behind a proxy).
    if let Some(connect_info) = request
        .extensions()
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
    {
        // No proxy list on this path: `forwarded_client_ip` canonicalises the peer
        // (IPv4-mapped IPv6 becomes IPv4) and ignores every header.
        let client = crate::api::middleware::forwarded_client_ip(
            connect_info.0.ip(),
            request.headers(),
            &[],
        );
        context.insert("ip_address".to_string(), client.to_string());
    }

    // Add time-based context
    let current_hour = chrono::Utc::now().format("%H").to_string();
    let hour: u32 = current_hour.parse().unwrap_or(0);

    if (9..=17).contains(&hour) {
        context.insert("time".to_string(), "business_hours".to_string());
    } else {
        context.insert("time".to_string(), "after_hours".to_string());
    }

    // Add day of week
    let day_of_week = chrono::Utc::now().format("%u").to_string(); // 1-7, Monday = 1
    let weekday: u32 = day_of_week.parse().unwrap_or(1);

    if (1..=5).contains(&weekday) {
        context.insert("day_type".to_string(), "weekday".to_string());
    } else {
        context.insert("day_type".to_string(), "weekend".to_string());
    }

    context
}

/// Build conditional context for sensitive operations
fn build_conditional_context(request: &Request) -> HashMap<String, String> {
    let mut context = HashMap::new();

    // Check for VPN indicators
    if let Some(via) = request.headers().get("via")
        && let Ok(via_str) = via.to_str()
        && (via_str.contains("vpn") || via_str.contains("proxy"))
    {
        context.insert("connection_type".to_string(), "vpn".to_string());
    }

    // Check for mobile device
    if let Some(user_agent) = request.headers().get("user-agent")
        && let Ok(ua_str) = user_agent.to_str()
    {
        if ua_str.contains("Mobile") || ua_str.contains("Android") || ua_str.contains("iPhone") {
            context.insert("device_type".to_string(), "mobile".to_string());
        } else {
            context.insert("device_type".to_string(), "desktop".to_string());
        }
    }

    // Add security level based on endpoint sensitivity
    let path = request.uri().path();
    if path.contains("/admin/") {
        context.insert("security_level".to_string(), "high".to_string());
    } else if path.contains("/api/") {
        context.insert("security_level".to_string(), "medium".to_string());
    } else {
        context.insert("security_level".to_string(), "low".to_string());
    }

    context
}

/// Check if endpoint is public (doesn't require authentication)
fn is_public_endpoint(path: &str) -> bool {
    match path {
        "/health" | "/health/detailed" | "/metrics" | "/readiness" | "/liveness" => true,
        "/auth/login" | "/auth/refresh" | "/auth/providers" => true,
        "/oauth/authorize" | "/oauth/token" | "/oauth/.well-known/openid_configuration" => true,
        _ if path.starts_with("/oauth/.well-known/") => true,
        _ => false,
    }
}

/// Check if endpoint contains sensitive data
fn is_sensitive_endpoint(path: &str) -> bool {
    match path {
        _ if path.starts_with("/admin/") => true,
        _ if path.contains("/secrets/") => true,
        _ if path.contains("/config/") => true,
        _ if path.contains("/keys/") => true,
        "/auth/logout" => true, // Logout should have conditional access
        _ => false,
    }
}

/// Check if endpoint requires role elevation
fn requires_role_elevation(path: &str) -> bool {
    match path {
        _ if path.starts_with("/admin/users/delete") => true,
        _ if path.starts_with("/admin/system/") => true,
        _ if path.contains("/sudo/") => true,
        _ if path.contains("/elevate/") => true,
        _ => false,
    }
}

/// Permission requirement middleware factory
pub fn require_permission(
    action: &str,
    resource: &str,
) -> impl Fn(
    Request,
    Next,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Response, Response>> + Send>>
+ Clone {
    let action = action.to_string();
    let resource = resource.to_string();

    move |request: Request, next: Next| {
        let action = action.clone();
        let resource = resource.clone();
        Box::pin(async move {
            let auth_token = match request.extensions().get::<AuthToken>() {
                Some(token) => token,
                None => {
                    let error_response = ApiResponse::<()>::unauthorized();
                    return Err(error_response.into_response());
                }
            };

            // For this implementation, we'd need access to the authorization service
            // This would typically be passed through the request state
            // For now, we'll do a basic permission check using the auth token
            if check_token_permission(auth_token, &action, &resource) {
                Ok(next.run(request).await)
            } else {
                let error_response = ApiResponse::<()>::forbidden();
                Err(error_response.into_response())
            }
        })
    }
}

/// Basic permission check using auth token (fallback)
fn check_token_permission(auth_token: &AuthToken, action: &str, resource: &str) -> bool {
    // Check for admin role (has all permissions)
    if auth_token.roles.contains(&"admin".to_string()) {
        return true;
    }

    // Check explicit permissions
    let required_permission = format!("{}:{}", action, resource);
    auth_token.permissions.iter().any(|perm| {
        perm == &required_permission
            || perm == "*"
            || (perm.ends_with("*") && required_permission.starts_with(&perm[..perm.len() - 1]))
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn request_from(peer: Option<&str>, xff: Option<&str>) -> Request {
        let mut b = axum::http::Request::builder().uri("/api/things");
        if let Some(xff) = xff {
            b = b.header("x-forwarded-for", xff);
        }
        let mut req = b.body(axum::body::Body::empty()).unwrap();
        if let Some(peer) = peer {
            let peer: std::net::SocketAddr = format!("{peer}:40000").parse().unwrap();
            req.extensions_mut()
                .insert(axum::extract::ConnectInfo(peer));
        }
        req
    }

    #[test]
    fn the_context_ip_is_the_peer_not_a_forwarded_header() {
        let token = AuthToken::new("u", "t", std::time::Duration::from_secs(60), "test");

        let spoofed = request_from(Some("198.51.100.9"), Some("10.0.0.5"));
        let ctx = build_request_context(&spoofed, &token);
        assert_eq!(ctx["ip_address"], "198.51.100.9");

        // no peer address: no ip at all, whatever the header says
        let none = request_from(None, Some("10.0.0.5"));
        assert!(!build_request_context(&none, &token).contains_key("ip_address"));
    }

    #[test]
    fn an_ipv4_mapped_peer_is_reported_as_ipv4() {
        let token = AuthToken::new("u", "t", std::time::Duration::from_secs(60), "test");
        let mut req = request_from(None, None);
        let peer: std::net::SocketAddr = "[::ffff:198.51.100.9]:40000".parse().unwrap();
        req.extensions_mut()
            .insert(axum::extract::ConnectInfo(peer));
        assert_eq!(
            build_request_context(&req, &token)["ip_address"],
            "198.51.100.9"
        );
    }

    #[test]
    fn test_public_endpoint_detection() {
        assert!(is_public_endpoint("/health"));
        assert!(is_public_endpoint("/auth/login"));
        assert!(is_public_endpoint(
            "/oauth/.well-known/openid_configuration"
        ));
        assert!(!is_public_endpoint("/api/users"));
        assert!(!is_public_endpoint("/admin/roles"));
    }

    #[test]
    fn test_sensitive_endpoint_detection() {
        assert!(is_sensitive_endpoint("/admin/users"));
        assert!(is_sensitive_endpoint("/api/secrets/vault"));
        assert!(is_sensitive_endpoint("/auth/logout"));
        assert!(!is_sensitive_endpoint("/api/health"));
        assert!(!is_sensitive_endpoint("/public/info"));
    }

    #[test]
    fn test_elevation_requirement() {
        assert!(requires_role_elevation("/admin/users/delete/123"));
        assert!(requires_role_elevation("/admin/system/shutdown"));
        assert!(requires_role_elevation("/api/sudo/execute"));
        assert!(!requires_role_elevation("/admin/users"));
        assert!(!requires_role_elevation("/api/profile"));
    }

    #[test]
    fn test_context_building() {
        // This would require setting up a mock request, which is complex
        // In a real test, we'd create a proper test request and verify context
        let context: HashMap<String, String> = HashMap::new();
        assert!(context.is_empty()); // Placeholder test
    }
}