auth-framework 0.5.0-rc19

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
//! API Metrics and Observability
//!
//! Provides comprehensive metrics collection for API endpoints

use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

/// Thread-safe metrics collector for API endpoints.
///
/// Tracks per-path request counts, response times, error counts,
/// and active request gauge.
///
/// # Example
/// ```rust
/// use auth_framework::api::metrics::ApiMetrics;
/// use std::time::Duration;
/// use axum::http::StatusCode;
///
/// let m = ApiMetrics::new();
/// m.record_request("/login");
/// m.record_response("/login", Duration::from_millis(5), StatusCode::OK);
///
/// let snap = m.get_metrics();
/// assert_eq!(snap.total_requests, 1);
/// ```
#[derive(Debug, Clone)]
pub struct ApiMetrics {
    inner: Arc<Mutex<ApiMetricsInner>>,
}

#[derive(Debug)]
struct ApiMetricsInner {
    request_counts: HashMap<String, u64>,
    response_times: HashMap<String, Vec<Duration>>,
    error_counts: HashMap<String, u64>,
    active_requests: u64,
    start_time: Instant,
}

impl ApiMetrics {
    /// Create a new, empty metrics collector.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    /// let m = ApiMetrics::new();
    /// assert_eq!(m.get_metrics().total_requests, 0);
    /// ```
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(ApiMetricsInner {
                request_counts: HashMap::new(),
                response_times: HashMap::new(),
                error_counts: HashMap::new(),
                active_requests: 0,
                start_time: Instant::now(),
            })),
        }
    }

    /// Record an incoming request for `path`.
    ///
    /// Increments the request counter and the active-requests gauge.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    /// let m = ApiMetrics::new();
    /// m.record_request("/health");
    /// ```
    pub fn record_request(&self, path: &str) {
        let Ok(mut inner) = self.inner.lock() else {
            return;
        };
        *inner.request_counts.entry(path.to_string()).or_insert(0) += 1;
        inner.active_requests += 1;
    }

    /// Record a completed response for `path`.
    ///
    /// Stores the response `duration`, increments error counters for
    /// 4xx/5xx status codes, and decrements the active-requests gauge.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    /// use std::time::Duration;
    /// use axum::http::StatusCode;
    ///
    /// let m = ApiMetrics::new();
    /// m.record_request("/api");
    /// m.record_response("/api", Duration::from_millis(12), StatusCode::OK);
    /// ```
    pub fn record_response(&self, path: &str, duration: Duration, status: StatusCode) {
        let Ok(mut inner) = self.inner.lock() else {
            return;
        };
        inner
            .response_times
            .entry(path.to_string())
            .or_default()
            .push(duration);

        if status.is_client_error() || status.is_server_error() {
            *inner.error_counts.entry(path.to_string()).or_insert(0) += 1;
        }

        inner.active_requests = inner.active_requests.saturating_sub(1);
    }

    /// Snapshot all collected metrics.
    ///
    /// Returns a [`MetricsSnapshot`] with uptime, totals, and per-endpoint
    /// statistics including average, p95, and p99 response times.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    ///
    /// let m = ApiMetrics::new();
    /// let snap = m.get_metrics();
    /// assert_eq!(snap.total_requests, 0);
    /// ```
    pub fn get_metrics(&self) -> MetricsSnapshot {
        let Ok(inner) = self.inner.lock() else {
            return MetricsSnapshot {
                uptime: Duration::ZERO,
                total_requests: 0,
                active_requests: 0,
                endpoint_metrics: HashMap::new(),
            };
        };
        let mut endpoint_metrics = HashMap::new();

        for (path, &count) in &inner.request_counts {
            let response_times = inner.response_times.get(path).cloned().unwrap_or_default();
            let error_count = inner.error_counts.get(path).copied().unwrap_or(0);

            let avg_response_time = if !response_times.is_empty() {
                response_times.iter().sum::<Duration>() / response_times.len() as u32
            } else {
                Duration::ZERO
            };

            let p95_response_time = calculate_percentile(&response_times, 95.0);
            let p99_response_time = calculate_percentile(&response_times, 99.0);

            endpoint_metrics.insert(
                path.clone(),
                EndpointMetrics {
                    request_count: count,
                    error_count,
                    error_rate: if count > 0 {
                        error_count as f64 / count as f64
                    } else {
                        0.0
                    },
                    avg_response_time,
                    p95_response_time,
                    p99_response_time,
                },
            );
        }

        MetricsSnapshot {
            uptime: inner.start_time.elapsed(),
            total_requests: inner.request_counts.values().sum(),
            active_requests: inner.active_requests,
            endpoint_metrics,
        }
    }

    /// Reset all counters and timers.
    ///
    /// Clears request counts, response times, error counts, and resets
    /// the uptime clock.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    /// use std::time::Duration;
    /// use axum::http::StatusCode;
    ///
    /// let m = ApiMetrics::new();
    /// m.record_request("/x");
    /// m.record_response("/x", Duration::from_millis(1), StatusCode::OK);
    /// m.reset();
    /// assert_eq!(m.get_metrics().total_requests, 0);
    /// ```
    pub fn reset(&self) {
        let Ok(mut inner) = self.inner.lock() else {
            return;
        };
        inner.request_counts.clear();
        inner.response_times.clear();
        inner.error_counts.clear();
        inner.start_time = Instant::now();
    }
}

impl Default for ApiMetrics {
    fn default() -> Self {
        Self::new()
    }
}

/// Point-in-time snapshot of API metrics.
///
/// Returned by [`ApiMetrics::get_metrics()`]. Use
/// [`to_prometheus_format()`](MetricsSnapshot::to_prometheus_format)
/// to export for Prometheus scraping.
///
/// # Example
/// ```rust
/// use auth_framework::api::metrics::ApiMetrics;
///
/// let snap = ApiMetrics::new().get_metrics();
/// assert_eq!(snap.active_requests, 0);
/// ```
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
    pub uptime: Duration,
    pub total_requests: u64,
    pub active_requests: u64,
    pub endpoint_metrics: HashMap<String, EndpointMetrics>,
}

/// Per-endpoint statistics within a [`MetricsSnapshot`].
///
/// # Example
/// ```rust
/// use auth_framework::api::metrics::{ApiMetrics, EndpointMetrics};
/// use std::time::Duration;
/// use axum::http::StatusCode;
///
/// let m = ApiMetrics::new();
/// m.record_request("/test");
/// m.record_response("/test", Duration::from_millis(50), StatusCode::OK);
///
/// let snap = m.get_metrics();
/// let ep: &EndpointMetrics = &snap.endpoint_metrics["/test"];
/// assert_eq!(ep.request_count, 1);
/// ```
#[derive(Debug, Clone)]
pub struct EndpointMetrics {
    pub request_count: u64,
    pub error_count: u64,
    pub error_rate: f64,
    pub avg_response_time: Duration,
    pub p95_response_time: Duration,
    pub p99_response_time: Duration,
}

/// Calculate percentile from a sorted list of durations
fn calculate_percentile(durations: &[Duration], percentile: f64) -> Duration {
    if durations.is_empty() {
        return Duration::ZERO;
    }

    let mut sorted = durations.to_vec();
    sorted.sort();

    let index = ((percentile / 100.0) * (sorted.len() - 1) as f64).round() as usize;
    sorted.get(index).copied().unwrap_or(Duration::ZERO)
}

/// Axum middleware that records request and response metrics.
///
/// Attach via `axum::middleware::from_fn(metrics_middleware)`.
///
/// # Example
/// ```rust,ignore
/// use axum::{Router, middleware};
/// use auth_framework::api::metrics::metrics_middleware;
///
/// let app = Router::new()
///     .layer(middleware::from_fn(metrics_middleware));
/// ```
pub async fn metrics_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
    let start_time = Instant::now();
    let path = request.uri().path().to_string();

    // Get metrics collector from extensions or create new one
    let metrics = request
        .extensions()
        .get::<ApiMetrics>()
        .cloned()
        .unwrap_or_default();

    metrics.record_request(&path);

    let response = next.run(request).await;
    let duration = start_time.elapsed();

    metrics.record_response(&path, duration, response.status());

    Ok(response)
}

impl MetricsSnapshot {
    /// Render the snapshot in Prometheus text exposition format.
    ///
    /// # Example
    /// ```rust
    /// use auth_framework::api::metrics::ApiMetrics;
    ///
    /// let prom = ApiMetrics::new().get_metrics().to_prometheus_format();
    /// assert!(prom.contains("auth_framework_uptime_seconds"));
    /// ```
    pub fn to_prometheus_format(&self) -> String {
        let mut output = String::new();

        // System metrics
        output.push_str(&format!(
            "# HELP auth_framework_uptime_seconds Total uptime in seconds\n\
             # TYPE auth_framework_uptime_seconds counter\n\
             auth_framework_uptime_seconds {}\n\n",
            self.uptime.as_secs()
        ));

        output.push_str(&format!(
            "# HELP auth_framework_requests_total Total number of requests\n\
             # TYPE auth_framework_requests_total counter\n\
             auth_framework_requests_total {}\n\n",
            self.total_requests
        ));

        output.push_str(&format!(
            "# HELP auth_framework_active_requests Current number of active requests\n\
             # TYPE auth_framework_active_requests gauge\n\
             auth_framework_active_requests {}\n\n",
            self.active_requests
        ));

        // Endpoint metrics
        for (endpoint, metrics) in &self.endpoint_metrics {
            let _safe_endpoint = endpoint.replace(['/', '-'], "_");

            output.push_str(&format!(
                "auth_framework_endpoint_requests_total{{endpoint=\"{}\"}} {}\n",
                endpoint, metrics.request_count
            ));

            output.push_str(&format!(
                "auth_framework_endpoint_errors_total{{endpoint=\"{}\"}} {}\n",
                endpoint, metrics.error_count
            ));

            output.push_str(&format!(
                "auth_framework_endpoint_response_time_avg{{endpoint=\"{}\"}} {}\n",
                endpoint,
                metrics.avg_response_time.as_secs_f64()
            ));

            output.push_str(&format!(
                "auth_framework_endpoint_response_time_p95{{endpoint=\"{}\"}} {}\n",
                endpoint,
                metrics.p95_response_time.as_secs_f64()
            ));
        }

        output
    }
}

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

    #[test]
    fn test_metrics_collection() {
        let metrics = ApiMetrics::new();

        metrics.record_request("/api/login");
        metrics.record_response("/api/login", Duration::from_millis(100), StatusCode::OK);

        let snapshot = metrics.get_metrics();
        assert_eq!(snapshot.total_requests, 1);
        assert_eq!(snapshot.endpoint_metrics["/api/login"].request_count, 1);
        assert_eq!(snapshot.endpoint_metrics["/api/login"].error_count, 0);
    }

    #[test]
    fn test_error_tracking() {
        let metrics = ApiMetrics::new();

        metrics.record_request("/api/test");
        metrics.record_response(
            "/api/test",
            Duration::from_millis(50),
            StatusCode::BAD_REQUEST,
        );

        let snapshot = metrics.get_metrics();
        assert_eq!(snapshot.endpoint_metrics["/api/test"].error_count, 1);
        assert!(snapshot.endpoint_metrics["/api/test"].error_rate > 0.0);
    }

    #[test]
    fn test_percentile_calculation() {
        let durations = vec![
            Duration::from_millis(10),
            Duration::from_millis(20),
            Duration::from_millis(30),
            Duration::from_millis(40),
            Duration::from_millis(100),
        ];

        let p95 = calculate_percentile(&durations, 95.0);
        assert_eq!(p95, Duration::from_millis(100));
    }

    #[test]
    fn test_prometheus_format() {
        let metrics = ApiMetrics::new();
        metrics.record_request("/api/test");
        metrics.record_response("/api/test", Duration::from_millis(100), StatusCode::OK);

        let snapshot = metrics.get_metrics();
        let prometheus = snapshot.to_prometheus_format();

        assert!(prometheus.contains("auth_framework_requests_total"));
        assert!(prometheus.contains("auth_framework_active_requests"));
        assert!(prometheus.contains("endpoint=\"/api/test\""));
    }
}