seiva_http/guard.rs
1//! The descriptor-driven permission guard.
2//!
3//! A facade's [`MethodDescriptor.requires`](seiva::contract::MethodDescriptor)
4//! names the permission a caller must hold. [`permission_guard`] is a tower
5//! middleware, parameterised by that string via [`RequiredPermission`], that
6//! reads the [`Principal`] a request carries and returns a `403`
7//! [`Problem`] when the permission is absent. An empty
8//! requirement (`""`, an unguarded method) always passes.
9//!
10//! The principal reaches a request through its extensions (an authentication
11//! layer inserts it; a test inserts it directly). A request with no principal is
12//! treated as [`Principal::anonymous`] — holding nothing — so an unauthenticated
13//! caller is denied, not admitted.
14
15use std::sync::Arc;
16
17use axum::extract::{Request, State};
18use axum::middleware::Next;
19use axum::response::{IntoResponse, Response};
20
21use seiva_identity::Principal;
22
23use crate::problem::{Problem, ProblemResponse};
24use crate::request_id::RequestIdExt;
25
26/// HTTP-flavoured object-level authorization helpers on the transport-free
27/// [`Principal`] (which lives in `seiva-identity`). These return a `403`
28/// [`Problem`], so they stay in the HTTP crate rather than in the identity crate.
29///
30/// # Function-level vs object-level authorization
31///
32/// [`permission_guard`] is **function-level** (OWASP API5): it checks the caller
33/// holds the named permission for the route. It cannot be **object-level** (OWASP
34/// API1 / BOLA), because the middleware runs before the handler loads the
35/// resource, so it does not yet know which tenant owns it. Object-level checks
36/// belong where the resource is known: once a handler (or the application layer)
37/// has loaded a record, it calls [`require_owns`](PrincipalExt::require_owns)
38/// with the record's tenant — or, fail-closed, wraps it in a [`Scoped`].
39pub trait PrincipalExt {
40 /// Asserts the caller owns a resource in `resource_tenant`, returning a `403`
41 /// [`Problem`] otherwise. The advisory object-level (API1 / BOLA) counterpart
42 /// to the function-level [`permission_guard`]; [`Scoped`] is the fail-closed one.
43 ///
44 /// # Errors
45 ///
46 /// Returns a `403` [`Problem`] when the caller does not own the resource.
47 fn require_owns(&self, resource_tenant: &str) -> Result<(), Problem>;
48}
49
50impl PrincipalExt for Principal {
51 fn require_owns(&self, resource_tenant: &str) -> Result<(), Problem> {
52 if self.owns(resource_tenant) {
53 Ok(())
54 } else {
55 Err(Problem::forbidden(
56 "caller does not own the requested resource",
57 ))
58 }
59 }
60}
61
62/// A value that belongs to a tenant and cannot be read without proving the caller
63/// owns it — the **fail-closed** object-level (OWASP API1 / BOLA) counterpart to
64/// the advisory [`Principal::require_owns`] (ADR 0005).
65///
66/// Build it where the resource is loaded, from the record's own tenant column:
67///
68/// ```
69/// # use seiva_http::{Principal, Scoped};
70/// # struct NoteDto { title: String }
71/// // In the use case / handler, right after the load:
72/// let note = Scoped::new("acme", NoteDto { title: "hi".into() });
73///
74/// // The ONLY way to reach the value is to pass the ownership check:
75/// let caller = Principal::in_tenant("alice", "acme", ["notes.read"]);
76/// let dto = note.owned_by(&caller).expect("same tenant");
77/// assert_eq!(dto.title, "hi");
78/// ```
79///
80/// There is no `into_inner`, no public field and no `Deref`: a handler that
81/// forgets the check cannot reach the resource to return it, so the omission is a
82/// compile error rather than a silent cross-tenant leak. `#[must_use]` means even
83/// dropping it unused warns.
84#[must_use = "a Scoped value must be unwrapped with `owned_by` — dropping it skips the ownership check"]
85pub struct Scoped<T> {
86 tenant: String,
87 value: T,
88}
89
90impl<T> Scoped<T> {
91 /// Tags `value` as belonging to `tenant`. The caller passes the resource's
92 /// own tenant (its database column, say), not the requester's.
93 pub fn new(tenant: impl Into<String>, value: T) -> Self {
94 Self {
95 tenant: tenant.into(),
96 value,
97 }
98 }
99
100 /// The tenant this value belongs to, readable without unwrapping — for a log
101 /// line or a metric label, never as a substitute for [`owned_by`](Self::owned_by).
102 #[must_use]
103 pub fn tenant(&self) -> &str {
104 &self.tenant
105 }
106
107 /// Unwraps the value **iff** `principal` owns its tenant, returning a `403`
108 /// [`Problem`] otherwise. This is the only accessor of the inner value, so
109 /// the ownership check cannot be skipped.
110 ///
111 /// # Errors
112 ///
113 /// Returns a `403` [`Problem`] when the caller does not own the resource.
114 pub fn owned_by(self, principal: &Principal) -> Result<T, Problem> {
115 if principal.owns(&self.tenant) {
116 Ok(self.value)
117 } else {
118 Err(Problem::forbidden(
119 "caller does not own the requested resource",
120 ))
121 }
122 }
123}
124
125/// The permission a route requires, read from a facade method's descriptor. An
126/// empty string marks an unguarded route. Used as the state of
127/// [`permission_guard`].
128#[derive(Debug, Clone, Copy)]
129pub struct RequiredPermission(pub &'static str);
130
131/// The **function-level** (OWASP API5) permission check, fail-closed per ADR 0019.
132///
133/// This is the single home of the rule shared by the tower
134/// [`permission_guard`] and the pipeline `Authorize` behavior
135/// ([`crate::bus::Authorize`]), so the two transports cannot drift: an empty
136/// `required` marks an unguarded operation and always passes; otherwise the caller
137/// must hold the named permission verbatim. An absent principal is the caller's
138/// responsibility to default to [`Principal::anonymous`] (which holds nothing), so
139/// an unauthenticated caller is denied, not admitted.
140///
141/// It returns a *bare* `403` [`Problem`] on denial — no `instance`, no
142/// `request_id`. The caller enriches it with the request coordinates it has
143/// (`permission_guard` adds the URI path and correlation id; the behavior adds the
144/// `Ctx` path), so this function stays free of any transport detail.
145///
146/// # Errors
147///
148/// Returns a `403` [`Problem`] when `required` is non-empty and `principal` does
149/// not hold it.
150pub fn require_permission(principal: &Principal, required: &str) -> Result<(), Problem> {
151 if required.is_empty() || principal.has(required) {
152 Ok(())
153 } else {
154 Err(Problem::forbidden(format!(
155 "permission `{required}` is required"
156 )))
157 }
158}
159
160/// Middleware that enforces [`RequiredPermission`] against the request's
161/// [`Principal`]. Mount it with
162/// [`axum::middleware::from_fn_with_state`]`(RequiredPermission(perm), permission_guard)`.
163pub async fn permission_guard(
164 State(required): State<RequiredPermission>,
165 request: Request,
166 next: Next,
167) -> Response {
168 // Read the principal by reference — the guard only needs `&Principal`, never
169 // an owned one, so a guarded route (and every PUBLIC route, where `required`
170 // is empty) pays no `Principal` deep-clone (panel finding E2). The decision is
171 // computed while the borrow is live, then the borrow ends before `request`
172 // moves into the inner service.
173 let anonymous;
174 let decision = {
175 let principal = match request.extensions().get::<Arc<Principal>>() {
176 Some(principal) => principal.as_ref(),
177 None => {
178 anonymous = Principal::anonymous();
179 &anonymous
180 }
181 };
182 // The fail-closed decision is shared with the `Authorize` behavior via
183 // `require_permission`, so there is one rule, not two that can diverge.
184 require_permission(principal, required.0)
185 };
186 let problem = match decision {
187 Ok(()) => return next.run(request).await,
188 Err(problem) => problem,
189 };
190
191 let request_id = request.extensions().request_id();
192 ProblemResponse(
193 problem
194 .with_instance(request.uri().path().to_owned())
195 .with_request_id_opt(request_id),
196 )
197 .into_response()
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use axum::http::StatusCode;
204
205 #[test]
206 fn tenant_scoped_principal_owns_only_its_own_tenant() {
207 let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
208 assert!(p.owns("acme"));
209 assert!(!p.owns("globex"));
210 assert!(p.has("notes.read"));
211 assert_eq!(p.tenant.as_deref(), Some("acme"));
212 }
213
214 #[test]
215 fn tenantless_and_anonymous_principals_own_nothing() {
216 // A permission alone must never imply ownership of a tenant's resource.
217 assert!(!Principal::new("svc", ["notes.read"]).owns("acme"));
218 assert!(!Principal::anonymous().owns("acme"));
219 }
220
221 #[test]
222 fn require_owns_allows_same_tenant_and_forbids_cross_tenant() {
223 let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
224 assert!(p.require_owns("acme").is_ok());
225
226 let denied = p.require_owns("globex").unwrap_err();
227 assert_eq!(denied.status, StatusCode::FORBIDDEN);
228 }
229
230 #[test]
231 fn scoped_unwraps_only_for_the_owning_tenant() {
232 let owner = Principal::in_tenant("alice", "acme", ["notes.read"]);
233 let scoped = Scoped::new("acme", "secret-note");
234 assert_eq!(scoped.tenant(), "acme");
235 assert_eq!(scoped.owned_by(&owner).unwrap(), "secret-note");
236 }
237
238 #[test]
239 fn scoped_forbids_a_cross_tenant_caller() {
240 let intruder = Principal::in_tenant("mallory", "globex", ["notes.read"]);
241 let scoped = Scoped::new("acme", "secret-note");
242 let denied = scoped.owned_by(&intruder).unwrap_err();
243 assert_eq!(denied.status, StatusCode::FORBIDDEN);
244 }
245
246 #[test]
247 fn scoped_forbids_a_tenantless_or_anonymous_caller() {
248 // A permission alone (no tenant) must never unwrap a tenant's resource.
249 assert!(Scoped::new("acme", 1)
250 .owned_by(&Principal::new("svc", ["notes.read"]))
251 .is_err());
252 assert!(Scoped::new("acme", 1)
253 .owned_by(&Principal::anonymous())
254 .is_err());
255 }
256}