auth-framework 0.5.0-rc18

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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Health Check and Monitoring API Endpoints
//!
//! Provides system health, metrics, and monitoring endpoints

use crate::api::{ApiResponse, ApiState};
use axum::{
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::Serialize;
use std::collections::HashMap;

/// Basic health check response.
#[derive(Debug, Serialize)]
pub struct HealthResponse {
    /// Overall status: `"healthy"` or `"degraded"`.
    pub status: String,
    /// ISO-8601 timestamp of the check.
    pub timestamp: String,
    /// Per-service status summary.
    pub services: HashMap<String, String>,
    /// Crate version.
    pub version: String,
    /// Human-readable server uptime (e.g. `"3h 12m"`).
    pub uptime: String,
}

/// Extended health check response including per-service latency and system resource usage.
#[derive(Debug, Serialize)]
pub struct DetailedHealthResponse {
    pub status: String,
    pub timestamp: String,
    pub services: HashMap<String, ServiceHealth>,
    pub system: SystemHealth,
    pub version: String,
    pub uptime: String,
}

/// Per-service health details.
#[derive(Debug, Serialize)]
pub struct ServiceHealth {
    /// `"healthy"`, `"degraded"`, or `"unhealthy"`.
    pub status: String,
    /// Round-trip check latency in milliseconds.
    pub response_time_ms: u64,
    /// ISO-8601 timestamp of the last probe.
    pub last_check: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub details: HashMap<String, serde_json::Value>,
}

/// Aggregate system resource usage.
#[derive(Debug, Serialize)]
pub struct SystemHealth {
    pub memory_usage: MemoryInfo,
    pub cpu_usage: f64,
    pub disk_usage: DiskInfo,
    pub network: NetworkInfo,
}

/// Process memory usage.
#[derive(Debug, Serialize)]
pub struct MemoryInfo {
    pub total_mb: u64,
    pub used_mb: u64,
    pub free_mb: u64,
    pub usage_percent: f64,
}

/// Disk usage statistics.
#[derive(Debug, Serialize)]
pub struct DiskInfo {
    pub total_gb: u64,
    pub used_gb: u64,
    pub free_gb: u64,
    pub usage_percent: f64,
}

/// Network traffic counters.
#[derive(Debug, Serialize)]
pub struct NetworkInfo {
    pub requests_per_minute: u64,
    pub active_connections: u64,
    pub bytes_sent: u64,
    pub bytes_received: u64,
}

/// Container for exported Prometheus-style metrics.
#[derive(Debug, Serialize)]
pub struct MetricsResponse {
    pub metrics: Vec<Metric>,
    pub timestamp: String,
}

/// A single labeled metric.
#[derive(Debug, Serialize)]
pub struct Metric {
    pub name: String,
    pub value: f64,
    pub labels: HashMap<String, String>,
    pub help: String,
    pub metric_type: String,
}

/// `GET /health` — lightweight health check returning overall status and per-service summary.
pub async fn health_check(State(state): State<ApiState>) -> ApiResponse<HealthResponse> {
    let mut services = std::collections::HashMap::new();
    let mut overall_healthy = true;

    // Check AuthFramework health
    let auth_health = check_auth_framework_health(&state.auth_framework).await;
    services.insert("auth_framework".to_string(), auth_health.status.clone());
    if auth_health.status != "healthy" {
        overall_healthy = false;
    }

    // Check storage health
    let storage_health = check_storage_health(&state.auth_framework).await;
    services.insert("storage".to_string(), storage_health.status.clone());
    if storage_health.status != "healthy" {
        overall_healthy = false;
    }

    // Check token manager health
    let token_health = check_token_manager_health(&state.auth_framework).await;
    services.insert("token_manager".to_string(), token_health.status.clone());
    if token_health.status != "healthy" {
        overall_healthy = false;
    }

    // Check memory usage
    let memory_health = check_memory_health().await;
    services.insert("memory".to_string(), memory_health.status.clone());
    if memory_health.status != "healthy" {
        overall_healthy = false;
    }

    let health = HealthResponse {
        status: if overall_healthy {
            "healthy".to_string()
        } else {
            "degraded".to_string()
        },
        timestamp: chrono::Utc::now().to_rfc3339(),
        services,
        version: env!("CARGO_PKG_VERSION").to_string(),
        uptime: get_uptime().await,
    };

    ApiResponse::success(health)
}

/// `GET /health/detailed` — extended health check with latency measurements and system resource usage.
pub async fn detailed_health_check(
    State(state): State<ApiState>,
) -> ApiResponse<DetailedHealthResponse> {
    let mut services = HashMap::new();
    let mut overall_healthy = true;

    // Check AuthFramework health with detailed info
    let auth_health = check_auth_framework_health(&state.auth_framework).await;
    services.insert(
        "auth_framework".to_string(),
        ServiceHealth {
            status: auth_health.status.clone(),
            response_time_ms: auth_health.response_time_ms,
            last_check: chrono::Utc::now().to_rfc3339(),
            error: auth_health.error,
            details: {
                let mut details = HashMap::new();
                if let Ok(stats) = state.auth_framework.get_stats().await {
                    details.insert(
                        "active_sessions".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(stats.active_sessions)),
                    );
                    details.insert(
                        "auth_attempts".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(stats.auth_attempts)),
                    );
                    details.insert(
                        "tokens_issued".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(stats.tokens_issued)),
                    );
                }
                details
            },
        },
    );
    if auth_health.status != "healthy" {
        overall_healthy = false;
    }

    // Check storage health
    let storage_health = check_storage_health(&state.auth_framework).await;
    services.insert(
        "storage".to_string(),
        ServiceHealth {
            status: storage_health.status.clone(),
            response_time_ms: storage_health.response_time_ms,
            last_check: chrono::Utc::now().to_rfc3339(),
            error: storage_health.error,
            details: HashMap::new(),
        },
    );
    if storage_health.status != "healthy" {
        overall_healthy = false;
    }

    // Check token manager health
    let token_health = check_token_manager_health(&state.auth_framework).await;
    services.insert(
        "token_manager".to_string(),
        ServiceHealth {
            status: token_health.status.clone(),
            response_time_ms: token_health.response_time_ms,
            last_check: chrono::Utc::now().to_rfc3339(),
            error: token_health.error,
            details: HashMap::new(),
        },
    );
    if token_health.status != "healthy" {
        overall_healthy = false;
    }

    let system = SystemHealth {
        memory_usage: get_memory_info().await,
        cpu_usage: get_cpu_usage().await,
        disk_usage: get_disk_info().await,
        network: get_network_info().await,
    };

    let health = DetailedHealthResponse {
        status: if overall_healthy {
            "healthy".to_string()
        } else {
            "degraded".to_string()
        },
        timestamp: chrono::Utc::now().to_rfc3339(),
        services,
        system,
        version: env!("CARGO_PKG_VERSION").to_string(),
        uptime: get_uptime().await,
    };

    ApiResponse::success(health)
}

/// `GET /metrics` — export metrics in Prometheus text exposition format.
pub async fn metrics(State(state): State<ApiState>) -> impl IntoResponse {
    let metrics_text = state.auth_framework.export_prometheus_metrics().await;

    Response::builder()
        .status(StatusCode::OK)
        .header("content-type", "text/plain; version=0.0.4")
        .body(metrics_text)
        .expect("infallible: String body is always valid")
}

/// `GET /readiness` — Kubernetes readiness probe (200 when able to serve traffic).
pub async fn readiness_check(State(state): State<ApiState>) -> impl IntoResponse {
    // Check if the auth framework is ready to accept traffic by trying to get stats.
    // A successful stats call confirms storage, token manager, and core services are up.
    let ready = state.auth_framework.get_stats().await.is_ok();

    if ready {
        (StatusCode::OK, "Ready").into_response()
    } else {
        (StatusCode::SERVICE_UNAVAILABLE, "Not Ready").into_response()
    }
}

/// `GET /liveness` — Kubernetes liveness probe (200 if the async runtime is responsive).
pub async fn liveness_check(State(state): State<ApiState>) -> impl IntoResponse {
    // Verify the service can perform a basic operation — completing the await on
    // get_performance_metrics confirms the async runtime is not deadlocked.
    state.auth_framework.get_performance_metrics().await;
    (StatusCode::OK, "Alive").into_response()
}

/// Internal health check functions
async fn check_auth_framework_health(
    auth_framework: &std::sync::Arc<crate::AuthFramework>,
) -> ServiceHealthResult {
    let start = std::time::Instant::now();

    // Test basic framework operations
    match auth_framework.get_stats().await {
        Ok(_stats) => ServiceHealthResult {
            status: "healthy".to_string(),
            response_time_ms: start.elapsed().as_millis() as u64,
            error: None,
        },
        Err(e) => {
            tracing::warn!(error = %e, "Health check: framework error");
            ServiceHealthResult {
                status: "unhealthy".to_string(),
                response_time_ms: start.elapsed().as_millis() as u64,
                error: Some("Service check failed".to_string()),
            }
        }
    }
}

async fn check_storage_health(
    auth_framework: &std::sync::Arc<crate::AuthFramework>,
) -> ServiceHealthResult {
    let start = std::time::Instant::now();

    // Test storage connectivity by checking if we can perform a basic operation
    // This is a non-destructive test
    match auth_framework.get_stats().await {
        Ok(_) => ServiceHealthResult {
            status: "healthy".to_string(),
            response_time_ms: start.elapsed().as_millis() as u64,
            error: None,
        },
        Err(e) => {
            tracing::warn!(error = %e, "Health check: storage error");
            ServiceHealthResult {
                status: "unhealthy".to_string(),
                response_time_ms: start.elapsed().as_millis() as u64,
                error: Some("Service check failed".to_string()),
            }
        }
    }
}

async fn check_token_manager_health(
    auth_framework: &std::sync::Arc<crate::AuthFramework>,
) -> ServiceHealthResult {
    let start = std::time::Instant::now();

    // Test token creation and validation (without storing)
    let test_token = auth_framework.token_manager().create_jwt_token(
        "health_check_user",
        vec!["health_check".to_string()],
        Some(std::time::Duration::from_secs(1)),
    );

    match test_token {
        Ok(token) => {
            // Validate the token we just created
            match auth_framework.token_manager().validate_jwt_token(&token) {
                Ok(_) => ServiceHealthResult {
                    status: "healthy".to_string(),
                    response_time_ms: start.elapsed().as_millis() as u64,
                    error: None,
                },
                Err(e) => {
                    tracing::warn!(error = %e, "Health check: token validation error");
                    ServiceHealthResult {
                        status: "unhealthy".to_string(),
                        response_time_ms: start.elapsed().as_millis() as u64,
                        error: Some("Service check failed".to_string()),
                    }
                }
            }
        }
        Err(e) => {
            tracing::warn!(error = %e, "Health check: token creation error");
            ServiceHealthResult {
                status: "unhealthy".to_string(),
                response_time_ms: start.elapsed().as_millis() as u64,
                error: Some("Service check failed".to_string()),
            }
        }
    }
}

async fn check_memory_health() -> ServiceHealthResult {
    let start = std::time::Instant::now();

    // Simple memory allocation test
    let test_vec: Vec<u8> = vec![0; 1024]; // 1KB test allocation

    ServiceHealthResult {
        status: if test_vec.len() == 1024 {
            "healthy".to_string()
        } else {
            "unhealthy".to_string()
        },
        response_time_ms: start.elapsed().as_millis() as u64,
        error: None,
    }
}

async fn get_uptime() -> String {
    use std::time::SystemTime;

    // This is a simplified uptime calculation
    // In a real implementation, you would track the actual start time
    static START_TIME: std::sync::OnceLock<SystemTime> = std::sync::OnceLock::new();
    let start_time = START_TIME.get_or_init(SystemTime::now);

    match start_time.elapsed() {
        Ok(duration) => {
            let seconds = duration.as_secs();
            let days = seconds / 86400;
            let hours = (seconds % 86400) / 3600;
            let minutes = (seconds % 3600) / 60;

            if days > 0 {
                format!("{} days, {} hours, {} minutes", days, hours, minutes)
            } else if hours > 0 {
                format!("{} hours, {} minutes", hours, minutes)
            } else {
                format!("{} minutes", minutes)
            }
        }
        Err(_) => "Unknown".to_string(),
    }
}

async fn get_memory_info() -> MemoryInfo {
    use sysinfo::System;
    let mut sys = System::new();
    sys.refresh_memory();

    let total_mb = sys.total_memory() / (1024 * 1024);
    let used_mb = sys.used_memory() / (1024 * 1024);
    let free_mb = sys.available_memory() / (1024 * 1024);
    let usage_percent = if total_mb > 0 {
        (used_mb as f64 / total_mb as f64) * 100.0
    } else {
        0.0
    };

    MemoryInfo {
        total_mb,
        used_mb,
        free_mb,
        usage_percent,
    }
}

async fn get_cpu_usage() -> f64 {
    use sysinfo::System;
    let mut sys = System::new();
    sys.refresh_cpu_all();
    // sysinfo needs a short delay between refreshes for meaningful CPU data.
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    sys.refresh_cpu_all();
    sys.global_cpu_usage() as f64
}

async fn get_disk_info() -> DiskInfo {
    use sysinfo::Disks;
    let disks = Disks::new_with_refreshed_list();
    let (mut total, mut used) = (0u64, 0u64);
    for disk in disks.list() {
        total += disk.total_space();
        used += disk.total_space() - disk.available_space();
    }
    let total_gb = total / (1024 * 1024 * 1024);
    let used_gb = used / (1024 * 1024 * 1024);
    let free_gb = total_gb.saturating_sub(used_gb);
    let usage_percent = if total_gb > 0 {
        (used_gb as f64 / total_gb as f64) * 100.0
    } else {
        0.0
    };

    DiskInfo {
        total_gb,
        used_gb,
        free_gb,
        usage_percent,
    }
}

async fn get_network_info() -> NetworkInfo {
    use sysinfo::Networks;
    let networks = Networks::new_with_refreshed_list();
    let (mut sent, mut received) = (0u64, 0u64);
    for data in networks.list().values() {
        sent += data.total_transmitted();
        received += data.total_received();
    }

    NetworkInfo {
        requests_per_minute: 0, // Application-level metric; not available from OS counters.
        active_connections: 0,  // Application-level metric; not available from OS counters.
        bytes_sent: sent,
        bytes_received: received,
    }
}

#[derive(Debug)]
struct ServiceHealthResult {
    pub status: String,
    pub response_time_ms: u64,
    pub error: Option<String>,
}