footing 0.3.1

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
use std::ops::Deref;

use async_trait::async_trait;
use axum::{
    extract::{FromRequestParts, OptionalFromRequestParts},
    http::{Request, request::Parts},
};

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

/// 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.
#[derive(Clone)]
pub struct VerifiedAuthentication {
    principal: Principal,
    idempotency_scope: IdempotencyScope,
}

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);
    }
}

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()
    }
}

#[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.
pub trait HttpAuthenticationHook: Send + Sync + 'static {
    /// Authenticates one request without consuming its body.
    async fn authenticate(
        &self,
        request: &Parts,
    ) -> Result<Option<VerifiedAuthentication>, ApiProblem>;
}

#[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.
///
/// 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, HttpAuthenticationHook, HttpAuthorizationHook,
///     HttpMiddlewareConfig, HttpMiddlewareError, HttpMiddlewareStack, ProblemCode, RequestContext};
///
/// struct RequireAdmin;
///
/// #[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::try_new("unauthenticated").expect("valid static code"),
///                 "authentication is required",
///             ))?;
///         if !principal.has_role("admin") {
///             return Err(ApiProblem::forbidden(
///                 ProblemCode::try_new("forbidden").expect("valid static code"),
///                 "permission denied",
///             ));
///         }
///         Ok(())
///     }
/// }
///
/// fn admin_stack(authentication: Arc<dyn HttpAuthenticationHook>) -> Result<HttpMiddlewareStack, HttpMiddlewareError> {
///     HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
///         .with_authentication_hook(authentication)
///         .with_authorization_hook(Arc::new(RequireAdmin))
///         .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's [`HttpAuthenticationHook`].
///
/// ```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));
/// ```
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,
{
    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")
                .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},
        http::{Request, StatusCode},
        routing::get,
    };
    use tower::ServiceExt;

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

    use super::{CurrentPrincipal, VerifiedAuthentication};

    #[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() {
        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() }),
            );

        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 {
                VerifiedAuthentication::new(
                    Principal::user("usr_1").unwrap(),
                    IdempotencyScope::namespaced(b"test", b"usr_1"),
                )
                .install(&mut request);
            }

            let response = app.clone().oneshot(request).await.unwrap();
            let status = response.status();
            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" });
            }
        }
    }
}