footing 0.6.2

Feature-gated foundations for Rust backend services
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
use std::ops::Deref;

mod challenge;
pub use challenge::{AuthenticationChallenge, InvalidAuthenticationChallenge};

#[cfg(feature = "http-stack")]
use async_trait::async_trait;
use axum::{
    extract::{FromRef, FromRequestParts, OptionalFromRequestParts},
    http::request::Parts,
};

use crate::{
    auth::{PermissionError, Principal, PrincipalRequirement},
    http::{ApiProblem, ProblemCode, RequestContext},
};

#[cfg(feature = "http-stack")]
use crate::http::IdempotencyScope;
#[cfg(feature = "http-stack")]
use axum::http::Request;

/// Authentication result installed before Foundation policies execute.
///
/// Authentication hooks return this value only after validating credentials.
/// Installing both values together prevents principal-based rate limiting and
/// authenticated idempotency from observing different identity boundaries.
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[derive(Clone)]
pub struct VerifiedAuthentication {
    principal: Principal,
    idempotency_scope: IdempotencyScope,
}

#[cfg(feature = "http-stack")]
impl VerifiedAuthentication {
    #[must_use]
    /// Creates a verified authentication result and its idempotency boundary.
    pub const fn new(principal: Principal, idempotency_scope: IdempotencyScope) -> Self {
        Self {
            principal,
            idempotency_scope,
        }
    }

    #[must_use]
    /// Returns the verified principal.
    pub const fn principal(&self) -> &Principal {
        &self.principal
    }

    #[must_use]
    /// Returns the verified idempotency scope.
    pub const fn idempotency_scope(&self) -> &IdempotencyScope {
        &self.idempotency_scope
    }

    /// Installs the verified principal and scope on a request atomically.
    pub fn install<B>(self, request: &mut Request<B>) {
        let Self {
            principal,
            idempotency_scope,
        } = self;
        let mut context = request
            .extensions_mut()
            .remove::<RequestContext>()
            .unwrap_or_else(|| RequestContext::from_headers(request.headers()));
        context.set_principal(principal);
        request.extensions_mut().insert(context);
        request.extensions_mut().insert(idempotency_scope);
    }
}

#[cfg(feature = "http-stack")]
impl std::fmt::Debug for VerifiedAuthentication {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("VerifiedAuthentication")
            .field("principal", &"[REDACTED]")
            .field("idempotency_scope", &"[REDACTED]")
            .finish()
    }
}

#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[async_trait]
/// Validates request credentials before rate-limit and idempotency policies.
///
/// Returning `None` explicitly marks an anonymous request. Implementations must
/// never derive identity from unverified header bytes.
/// Use [`ApiProblem::unauthorized`] with the application's challenge for a `401`
/// rejection. The stack preserves it when adding request correlation identifiers.
pub trait HttpAuthenticationHook: Send + Sync + 'static {
    /// Authenticates one request without consuming its body.
    async fn authenticate(
        &self,
        request: &Parts,
    ) -> Result<Option<VerifiedAuthentication>, ApiProblem>;
}

#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[async_trait]
/// Checks current access after authentication and before rate limiting or idempotency.
///
/// The verified principal is available through [`RequestContext`] in request
/// extensions. Use the method, URI and Axum's `MatchedPath` to select the policy;
/// implementations may consult application state for current permissions.
/// This hook runs on every request, including cached response replays. Rejections
/// never enter the idempotency cache. A handler can still perform checks that need
/// its body, but access required to replay a response belongs here.
/// Use [`ApiProblem::unauthorized`] with an applicable challenge for `401`.
///
/// Install it with [`super::HttpMiddlewareStackBuilder::with_authorization_hook`].
/// For example, a stack applied to an administrator-only router can use:
///
/// ```rust
/// use std::sync::Arc;
/// use footing::http::{ApiProblem, AuthenticationChallenge, HttpAuthenticationHook, HttpAuthorizationHook,
///     HttpMiddlewareConfig, HttpMiddlewareError, HttpMiddlewareStack, ProblemCode, RequestContext};
///
/// struct RequireAdmin {
///     challenge: AuthenticationChallenge,
/// }
///
/// #[async_trait::async_trait]
/// impl HttpAuthorizationHook for RequireAdmin {
///     async fn authorize(&self, request: &axum::http::request::Parts) -> Result<(), ApiProblem> {
///         let principal = request.extensions.get::<RequestContext>()
///             .and_then(RequestContext::principal)
///             .ok_or_else(|| {
///                 ApiProblem::unauthorized(
///                     ProblemCode::from_static("unauthenticated"),
///                     "authentication is required",
///                     &self.challenge,
///                 )
///             })?;
///         if !principal.has_role("admin") {
///             return Err(ApiProblem::forbidden(
///                 ProblemCode::from_static("forbidden"),
///                 "permission denied",
///             ));
///         }
///         Ok(())
///     }
/// }
///
/// fn admin_stack(authentication: Arc<dyn HttpAuthenticationHook>, challenge: AuthenticationChallenge) -> Result<HttpMiddlewareStack, HttpMiddlewareError> {
///     HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
///         .with_authentication_hook(authentication)
///         .with_authorization_hook(Arc::new(RequireAdmin { challenge }))
///         .build()
/// }
/// ```
pub trait HttpAuthorizationHook: Send + Sync + 'static {
    /// Authorizes one request without consuming its body.
    async fn authorize(&self, request: &Parts) -> Result<(), ApiProblem>;
}

#[derive(Debug, Clone)]
/// Extracts the verified principal, rejecting anonymous requests with HTTP 401.
///
/// Use `Option<CurrentPrincipal>` when anonymous requests are allowed. Both
/// forms read [`RequestContext`]; client headers alone never establish identity.
/// Credential validation belongs to the application. Install its verified principal
/// in [`RequestContext`] before this extractor runs; `http-stack` also provides
/// an authentication hook for this purpose.
/// Required extraction obtains an [`AuthenticationChallenge`] from router state
/// via [`FromRef`], so anonymous requests always receive a configured challenge.
/// Use the challenge itself as state or implement `FromRef<AppState>` for it.
/// With application state, the implementation simply returns a clone of its
/// challenge; it must not derive the challenge from unverified request headers.
/// Optional extraction has no challenge or state requirement; use it when the
/// application needs its own rejection or login redirect.
///
/// ```rust
/// use axum::{Router, routing::get};
/// use footing::http::CurrentPrincipal;
///
/// async fn identity(principal: Option<CurrentPrincipal>) -> String {
///     principal.map_or_else(|| "anonymous".to_owned(), |principal| principal.id().to_owned())
/// }
///
/// let app: Router = Router::new().route("/identity", get(identity));
/// ```
///
/// Required authentication:
///
/// ```
/// use axum::{Router, routing::get};
/// use footing::http::{AuthenticationChallenge, CurrentPrincipal};
///
/// let challenge = AuthenticationChallenge::try_new("Bearer realm=\"api\"")?;
/// let app: Router = Router::new()
///     .route("/me", get(|principal: CurrentPrincipal| async move {
///         principal.id().to_owned()
///     }))
///     .with_state(challenge);
/// // Install verified identities in RequestContext through authentication middleware.
/// # Ok::<(), footing::http::InvalidAuthenticationChallenge>(())
/// ```
///
/// A required extractor without challenge-bearing state does not compile:
///
/// ```compile_fail
/// use axum::{Router, routing::get};
/// use footing::http::CurrentPrincipal;
/// let app: Router = Router::new().route("/me", get(|_: CurrentPrincipal| async {}));
/// ```
pub struct CurrentPrincipal(Principal);

impl CurrentPrincipal {
    #[must_use]
    /// Creates a new instance.
    pub fn new(principal: Principal) -> Self {
        Self(principal)
    }

    #[must_use]
    /// Returns the principal.
    pub const fn principal(&self) -> &Principal {
        &self.0
    }

    /// Requires role.
    pub fn require_role(&self, role: impl Into<String>) -> Result<(), ApiProblem> {
        PrincipalRequirement::role(role)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    /// Requires any role.
    pub fn require_any_role(
        &self,
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<(), ApiProblem> {
        PrincipalRequirement::any_roles(roles)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    /// Requires all roles.
    pub fn require_all_roles(
        &self,
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<(), ApiProblem> {
        PrincipalRequirement::all_roles(roles)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    /// Requires scope.
    pub fn require_scope(&self, scope: impl Into<String>) -> Result<(), ApiProblem> {
        PrincipalRequirement::scope(scope)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    /// Requires any scope.
    pub fn require_any_scope(
        &self,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<(), ApiProblem> {
        PrincipalRequirement::any_scopes(scopes)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    /// Requires all scopes.
    pub fn require_all_scopes(
        &self,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<(), ApiProblem> {
        PrincipalRequirement::all_scopes(scopes)
            .and_then(|guard| guard.check(self.principal()))
            .map_err(permission_error_to_problem)
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> Principal {
        self.0
    }
}

impl AsRef<Principal> for CurrentPrincipal {
    fn as_ref(&self) -> &Principal {
        self.principal()
    }
}

impl Deref for CurrentPrincipal {
    type Target = Principal;

    fn deref(&self) -> &Self::Target {
        self.principal()
    }
}

impl<S> FromRequestParts<S> for CurrentPrincipal
where
    S: Send + Sync,
    AuthenticationChallenge: FromRef<S>,
{
    type Rejection = ApiProblem;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let context = RequestContext::from_parts(parts);

        context.principal().cloned().map(Self).ok_or_else(|| {
            ApiProblem::unauthorized(
                ProblemCode::UNAUTHENTICATED,
                "authentication is required",
                &AuthenticationChallenge::from_ref(state),
            )
            .with_request_context(context)
        })
    }
}

impl<S> OptionalFromRequestParts<S> for CurrentPrincipal
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        let context = RequestContext::from_parts(parts);

        Ok(context.principal().cloned().map(Self))
    }
}

fn permission_error_to_problem(error: PermissionError) -> ApiProblem {
    match error {
        PermissionError::Denied => {
            ApiProblem::forbidden(ProblemCode::FORBIDDEN, "permission denied")
        }
        PermissionError::Unavailable => ApiProblem::service_unavailable(
            ProblemCode::PERMISSION_UNAVAILABLE,
            "permission backend is unavailable",
        ),
        PermissionError::InvalidPrincipal(_) | PermissionError::InvalidAuthority(_) => {
            ApiProblem::bad_request(ProblemCode::INVALID_PRINCIPAL, "principal is invalid")
        }
        PermissionError::InvalidPolicy(_) => ApiProblem::internal_error(),
    }
}

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

    use crate::{auth::Principal, http::RequestContext};

    use super::{AuthenticationChallenge, CurrentPrincipal};

    #[test]
    fn current_principal_can_require_roles_and_scopes() {
        let principal = CurrentPrincipal::new(
            Principal::user("usr_1")
                .expect("static test principal id is valid")
                .with_roles(["admin", "operator"])
                .expect("static test roles are valid")
                .with_scopes(["user:*", "audit:read"])
                .expect("static test scopes are valid"),
        );

        assert!(principal.require_role("admin").is_ok());
        assert!(principal.require_all_roles(["admin", "operator"]).is_ok());
        assert!(
            principal
                .require_any_scope(["client:read", "user:read"])
                .is_ok()
        );
        assert!(
            principal
                .require_all_scopes(["user:write", "audit:read"])
                .is_ok()
        );
    }

    #[test]
    fn current_principal_maps_denial_to_forbidden_problem() {
        let principal = CurrentPrincipal::new(
            Principal::user("usr_1").expect("static test principal id is valid"),
        );
        let problem = principal
            .require_scope("admin:read")
            .expect_err("missing scope should be denied");

        assert_eq!(problem.status(), StatusCode::FORBIDDEN);
        assert_eq!(problem.body().code(), "forbidden");
    }

    #[test]
    fn current_principal_hides_invalid_policy_details() {
        let principal = CurrentPrincipal::new(
            Principal::user("usr_1").expect("static test principal id is valid"),
        );
        let problem = principal
            .require_any_role(std::iter::empty::<&str>())
            .expect_err("empty role policy should be invalid");

        assert_eq!(problem.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(problem.body().code(), "internal_error");
    }

    #[tokio::test]
    async fn principal_extractors_only_use_verified_request_context() {
        #[derive(Clone)]
        struct AppState {
            challenge: AuthenticationChallenge,
        }
        impl FromRef<AppState> for AuthenticationChallenge {
            fn from_ref(state: &AppState) -> Self {
                state.challenge.clone()
            }
        }
        let app = Router::new()
            .route(
                "/optional",
                get(|principal: Option<CurrentPrincipal>| async move {
                    principal.map_or_else(
                        || "anonymous".to_owned(),
                        |principal| principal.id().to_owned(),
                    )
                }),
            )
            .route(
                "/required",
                get(|principal: CurrentPrincipal| async move { principal.id().to_owned() }),
            )
            .with_state(AppState {
                challenge: AuthenticationChallenge::try_new("Bearer realm=\"api\"").unwrap(),
            });

        for (path, verified) in [
            ("/optional", false),
            ("/optional", true),
            ("/required", false),
            ("/required", true),
        ] {
            let mut request = Request::get(path)
                .header("x-request-id", "req_identity")
                .header("authorization", "Bearer unverified-token")
                .header("x-user-id", "unverified-user")
                .header("x-client-id", "unverified-client")
                .header("x-session-id", "unverified-session")
                .body(Body::empty())
                .unwrap();
            if verified {
                let mut context = RequestContext::from_headers(request.headers());
                context.set_principal(Principal::user("usr_1").unwrap());
                request.extensions_mut().insert(context);
            }

            let response = app.clone().oneshot(request).await.unwrap();
            let status = response.status();
            if path == "/required" && !verified {
                assert_eq!(
                    response.headers()["www-authenticate"],
                    "Bearer realm=\"api\""
                );
            } else {
                assert!(!response.headers().contains_key("www-authenticate"));
            }
            let body = to_bytes(response.into_body(), 4096).await.unwrap();
            if path == "/required" && !verified {
                assert_eq!(status, StatusCode::UNAUTHORIZED);
                let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
                assert_eq!(problem["code"], "unauthenticated");
                assert_eq!(problem["request_id"], "req_identity");
            } else {
                assert_eq!(status, StatusCode::OK);
                assert_eq!(body, if verified { "usr_1" } else { "anonymous" });
            }
        }
    }

    #[tokio::test]
    async fn optional_principal_needs_no_authentication_challenge() {
        let app = Router::new().route(
            "/",
            get(|principal: Option<CurrentPrincipal>| async move {
                assert!(principal.is_none());
                StatusCode::NO_CONTENT
            }),
        );
        let response = app.oneshot(Request::new(Body::empty())).await.unwrap();
        assert_eq!(response.status(), StatusCode::NO_CONTENT);
        assert!(!response.headers().contains_key("www-authenticate"));
    }
}