arqen 0.8.0

Backend infrastructure for agent-ready 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Auth middleware for Arqen.
//!
//! Provides middleware that authenticates requests and inserts [`AuthContext`]
//! into request extensions, making it available to handlers via extractors.
//!
//! - [`auth_middleware`]: Enforces authentication — returns 401/403 on failure.
//! - [`optional_auth_middleware`]: Attempts authentication but continues even if it fails.
//! - [`Authenticated`]: Axum extractor that requires a valid `AuthContext`.
//! - `Option<Authenticated>`: Axum extractor for optional authentication.

use std::marker::PhantomData;
use std::sync::Arc;

use async_trait::async_trait;
use axum::extract::FromRef;
use axum::extract::FromRequestParts;
use axum::extract::State;
use axum::http::StatusCode;
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};

use crate::auth::{AuthContext, AuthError, Authentication, Policy};
use crate::core::error::{CorrelationId, ErrorCode, ErrorResponse};

/// Default resource name passed to [`Policy::check`] by the auth guards.
const DEFAULT_AUTH_RESOURCE: &str = "request";

/// Axum extractor that requires authentication.
///
/// The request must go through [`auth_middleware`] (or [`optional_auth_middleware`])
/// for this to succeed. Returns 401 if no `AuthContext` is present.
///
/// # Example
///
/// ```rust,ignore
/// use arqen::http::middleware_auth::Authenticated;
///
/// async fn protected_handler(
///     auth: Authenticated,
/// ) -> String {
///     format!("Hello, {}", auth.0.subject)
/// }
/// ```
pub struct Authenticated(pub AuthContext);

impl Authenticated {
    pub fn into_inner(self) -> AuthContext {
        self.0
    }
}

#[async_trait]
impl<S> FromRequestParts<S> for Authenticated
where
    S: Send + Sync,
{
    type Rejection = AuthRejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let _ = state;
        parts
            .extensions
            .get::<AuthContext>()
            .cloned()
            .map(Authenticated)
            .ok_or(AuthRejection::Missing)
    }
}

/// Rejection type for auth extraction errors.
#[derive(Debug)]
pub enum AuthRejection {
    /// No auth context found in request extensions.
    Missing,
    /// Authentication error from the adapter.
    Error(AuthError),
}

impl IntoResponse for AuthRejection {
    fn into_response(self) -> Response {
        let (status, code, message) = match self {
            AuthRejection::Missing => (
                StatusCode::UNAUTHORIZED,
                ErrorCode::Authentication,
                "authentication required".to_string(),
            ),
            AuthRejection::Error(AuthError::Missing) => (
                StatusCode::UNAUTHORIZED,
                ErrorCode::Authentication,
                "authentication required".to_string(),
            ),
            AuthRejection::Error(AuthError::Invalid) => (
                StatusCode::UNAUTHORIZED,
                ErrorCode::Authentication,
                "invalid credentials".to_string(),
            ),
            AuthRejection::Error(AuthError::Expired) => (
                StatusCode::UNAUTHORIZED,
                ErrorCode::Authentication,
                "credentials expired".to_string(),
            ),
            AuthRejection::Error(AuthError::Unauthorized(msg)) => {
                (StatusCode::FORBIDDEN, ErrorCode::Authorization, msg)
            }
        };

        let correlation_id = CorrelationId::current();
        let body = ErrorResponse::new(code, message, correlation_id.0);
        (status, axum::Json(body)).into_response()
    }
}

/// Auth middleware that enforces authentication.
///
/// Returns 401 if authentication fails. The authenticated [`AuthContext`] is
/// inserted into request extensions and can be extracted by handlers using
/// [`Authenticated`] or `Option<Authenticated>`.
///
/// # Example
///
/// ```rust,ignore
/// use arqen::auth::ApiKeyAuth;
/// use arqen::http::middleware_auth::auth_middleware;
/// use std::sync::Arc;
///
/// let auth = Arc::new(ApiKeyAuth::new().with_key("secret", "user-1"));
/// let router = Router::new()
///     .route("/protected", get(my_handler))
///     .layer(middleware::from_fn_with_state(auth, auth_middleware));
/// ```
pub async fn auth_middleware(
    State(auth): State<Arc<dyn Authentication>>,
    mut req: axum::http::Request<axum::body::Body>,
    next: axum::middleware::Next,
) -> Response {
    match auth.authenticate(req.headers()).await {
        Ok(ctx) => {
            req.extensions_mut().insert(ctx);
            let context = crate::context::from_extensions(req.extensions());
            req.extensions_mut().insert(context);
            next.run(req).await
        }
        Err(e) => {
            let (status, code, message) = match e {
                AuthError::Missing => (
                    StatusCode::UNAUTHORIZED,
                    ErrorCode::Authentication,
                    "authentication required".to_string(),
                ),
                AuthError::Invalid => (
                    StatusCode::UNAUTHORIZED,
                    ErrorCode::Authentication,
                    "invalid credentials".to_string(),
                ),
                AuthError::Expired => (
                    StatusCode::UNAUTHORIZED,
                    ErrorCode::Authentication,
                    "credentials expired".to_string(),
                ),
                AuthError::Unauthorized(msg) => {
                    (StatusCode::FORBIDDEN, ErrorCode::Authorization, msg)
                }
            };

            let correlation_id = CorrelationId::current();
            let body = ErrorResponse::new(code, message, correlation_id.0);
            (status, axum::Json(body)).into_response()
        }
    }
}

/// Auth middleware that optionally authenticates requests.
///
/// Always continues to the handler. If authentication succeeds, the
/// [`AuthContext`] is inserted into extensions. Handlers can use
/// `Option<Authenticated>` to check for identity without blocking.
///
/// # Example
///
/// ```rust,ignore
/// use arqen::http::middleware_auth::{optional_auth_middleware, Authenticated};
///
/// async fn public_handler(
///     auth: Option<Authenticated>,
/// ) -> String {
///     match auth {
///         Some(auth) => format!("Hello, {}", auth.0.subject),
///         None => "Hello, anonymous".to_string(),
///     }
/// }
/// ```
pub async fn optional_auth_middleware(
    State(auth): State<Arc<dyn Authentication>>,
    mut req: axum::http::Request<axum::body::Body>,
    next: axum::middleware::Next,
) -> Response {
    if let Ok(ctx) = auth.authenticate(req.headers()).await {
        req.extensions_mut().insert(ctx);
        let context = crate::context::from_extensions(req.extensions());
        req.extensions_mut().insert(context);
    }
    next.run(req).await
}

/// Extract the authenticated [`AuthContext`] from the current request.
///
/// Returns 401 when no auth middleware has inserted a context. Use this in
/// handlers behind [`auth_middleware`] or [`require_auth_middleware`].
#[async_trait]
impl<S> FromRequestParts<S> for AuthContext
where
    S: Send + Sync,
{
    type Rejection = AuthRejection;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<AuthContext>()
            .cloned()
            .ok_or(AuthRejection::Missing)
    }
}

/// Extractor that authenticates a request and enforces a policy inline.
///
/// `A` and `P` are resolved from the router state via [`FromRef`], so the
/// application state must expose an authentication adapter and a policy (for
/// example with `#[derive(FromRef)]`). Credential failures map to 401 and
/// policy failures to 403. On success the [`AuthContext`] is inserted into the
/// request extensions, so handlers can also extract it directly.
///
/// # Example
///
/// ```rust,ignore
/// use arqen::http::middleware_auth::RequireAuth;
///
/// async fn handler(auth: RequireAuth<Arc<dyn Authentication>, Arc<dyn Policy>>) -> String {
///     format!("hello {}", auth.context.subject)
/// }
/// ```
pub struct RequireAuth<A, P> {
    /// The authenticated context.
    pub context: AuthContext,
    _auth: PhantomData<A>,
    _policy: PhantomData<P>,
}

#[async_trait]
impl<S, A, P> FromRequestParts<S> for RequireAuth<A, P>
where
    S: Send + Sync,
    A: FromRef<S> + Authentication,
    P: FromRef<S> + Policy,
{
    type Rejection = AuthRejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let auth = A::from_ref(state);
        let context = auth
            .authenticate(&parts.headers)
            .await
            .map_err(AuthRejection::Error)?;
        let policy = P::from_ref(state);
        policy
            .check(&context, DEFAULT_AUTH_RESOURCE)
            .map_err(AuthRejection::Error)?;
        parts.extensions.insert(context.clone());
        Ok(Self {
            context,
            _auth: PhantomData,
            _policy: PhantomData,
        })
    }
}

/// A reusable authentication + authorization guard for a route subtree.
///
/// Holds an [`Authentication`] adapter and a [`Policy`]. The default policy is
/// [`AllowAll`](crate::auth::AllowAll), which combined with mandatory
/// authentication means "any authenticated user".
#[derive(Clone)]
pub struct AuthGuard {
    /// Authentication adapter.
    pub auth: Arc<dyn Authentication>,
    /// Authorization policy applied after authentication.
    pub policy: Arc<dyn Policy>,
}

impl AuthGuard {
    /// Create a guard that requires any authenticated user.
    pub fn new(auth: Arc<dyn Authentication>) -> Self {
        Self {
            auth,
            policy: Arc::new(crate::auth::AllowAll),
        }
    }

    /// Set a custom authorization policy.
    pub fn with_policy(mut self, policy: Arc<dyn Policy>) -> Self {
        self.policy = policy;
        self
    }
}

/// Middleware that authenticates and authorizes requests.
///
/// Pair with [`AuthGuard`] via `axum::middleware::from_fn_with_state` to
/// protect a whole route subtree:
///
/// ```rust,ignore
/// use arqen::http::middleware_auth::{AuthGuard, require_auth_middleware};
///
/// let guard = AuthGuard::new(auth);
/// let router = Router::new()
///     .route("/protected", get(handler))
///     .layer(middleware::from_fn_with_state(guard, require_auth_middleware));
/// ```
///
/// Credential failures return 401; policy failures return 403. On success the
/// [`AuthContext`] is inserted into request extensions.
pub async fn require_auth_middleware(
    State(guard): State<AuthGuard>,
    mut req: axum::http::Request<axum::body::Body>,
    next: axum::middleware::Next,
) -> Response {
    match guard.auth.authenticate(req.headers()).await {
        Ok(ctx) => {
            if let Err(e) = guard.policy.check(&ctx, DEFAULT_AUTH_RESOURCE) {
                return AuthRejection::Error(e).into_response();
            }
            req.extensions_mut().insert(ctx);
            next.run(req).await
        }
        Err(e) => AuthRejection::Error(e).into_response(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::get;
    use tower::ServiceExt;

    use crate::auth::ApiKeyAuth;

    fn test_auth() -> Arc<dyn Authentication> {
        Arc::new(ApiKeyAuth::new().with_key("test-key", "user-123"))
    }

    async fn protected_handler(auth: Authenticated) -> String {
        format!("hello {}", auth.0.subject)
    }

    async fn optional_handler(auth: Option<Authenticated>) -> String {
        match auth {
            Some(auth) => format!("hello {}", auth.0.subject),
            None => "hello anonymous".to_string(),
        }
    }

    #[tokio::test]
    async fn test_auth_middleware_success() {
        let auth = test_auth();
        let router = Router::new()
            .route("/protected", get(protected_handler))
            .layer(axum::middleware::from_fn_with_state(
                auth.clone(),
                auth_middleware,
            ));

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_auth_middleware_missing_credentials() {
        let auth = test_auth();
        let router = Router::new()
            .route("/protected", get(protected_handler))
            .layer(axum::middleware::from_fn_with_state(
                auth.clone(),
                auth_middleware,
            ));

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_auth_middleware_invalid_credentials() {
        let auth = test_auth();
        let router = Router::new()
            .route("/protected", get(protected_handler))
            .layer(axum::middleware::from_fn_with_state(
                auth.clone(),
                auth_middleware,
            ));

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "wrong-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_optional_auth_middleware_with_credentials() {
        let auth = test_auth();
        let router = Router::new().route("/public", get(optional_handler)).layer(
            axum::middleware::from_fn_with_state(auth.clone(), optional_auth_middleware),
        );

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/public")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body, "hello user-123");
    }

    #[tokio::test]
    async fn test_optional_auth_middleware_without_credentials() {
        let auth = test_auth();
        let router = Router::new().route("/public", get(optional_handler)).layer(
            axum::middleware::from_fn_with_state(auth.clone(), optional_auth_middleware),
        );

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/public")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body, "hello anonymous");
    }

    #[tokio::test]
    async fn test_authenticated_extractor_without_context() {
        let router = Router::new().route("/protected", get(protected_handler));

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_auth_rejection_display() {
        let rejection = AuthRejection::Missing;
        let response = rejection.into_response();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[derive(Clone)]
    struct GuardState {
        auth: Arc<dyn Authentication>,
        policy: Arc<dyn Policy>,
    }

    impl FromRef<GuardState> for Arc<dyn Authentication> {
        fn from_ref(state: &GuardState) -> Self {
            state.auth.clone()
        }
    }

    impl FromRef<GuardState> for Arc<dyn Policy> {
        fn from_ref(state: &GuardState) -> Self {
            state.policy.clone()
        }
    }

    async fn guard_handler(auth: AuthContext) -> String {
        format!("hello {}", auth.subject)
    }

    async fn require_auth_handler(
        auth: RequireAuth<Arc<dyn Authentication>, Arc<dyn Policy>>,
    ) -> String {
        format!("hello {}", auth.context.subject)
    }

    #[tokio::test]
    async fn test_require_auth_middleware_success() {
        let guard = AuthGuard::new(test_auth());
        let router = Router::new().route("/protected", get(guard_handler)).layer(
            axum::middleware::from_fn_with_state(guard, require_auth_middleware),
        );

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body, "hello user-123");
    }

    #[tokio::test]
    async fn test_require_auth_middleware_missing_credentials() {
        let guard = AuthGuard::new(test_auth());
        let router = Router::new().route("/protected", get(guard_handler)).layer(
            axum::middleware::from_fn_with_state(guard, require_auth_middleware),
        );

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_require_auth_middleware_policy_failure_returns_403() {
        let guard = AuthGuard::new(test_auth()).with_policy(Arc::new(crate::auth::DenyAll));
        let router = Router::new().route("/protected", get(guard_handler)).layer(
            axum::middleware::from_fn_with_state(guard, require_auth_middleware),
        );

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_require_auth_extractor_success() {
        let state = GuardState {
            auth: test_auth(),
            policy: Arc::new(crate::auth::AllowAll),
        };
        let router = Router::new()
            .route("/protected", get(require_auth_handler))
            .with_state(state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body, "hello user-123");
    }

    #[tokio::test]
    async fn test_require_auth_extractor_missing_credentials_returns_401() {
        let state = GuardState {
            auth: test_auth(),
            policy: Arc::new(crate::auth::AllowAll),
        };
        let router = Router::new()
            .route("/protected", get(require_auth_handler))
            .with_state(state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_require_auth_extractor_policy_failure_returns_403() {
        let state = GuardState {
            auth: test_auth(),
            policy: Arc::new(crate::auth::DenyAll),
        };
        let router = Router::new()
            .route("/protected", get(require_auth_handler))
            .with_state(state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header("x-api-key", "test-key")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_auth_context_extractor_without_middleware_returns_401() {
        let router = Router::new().route("/protected", get(guard_handler));

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }
}