seiva_http/ctx.rs
1//! The framework request context a facade method may receive as `&Ctx`.
2//!
3//! A facade/controller method can take a `&Ctx` parameter (recognised and
4//! **skipped from the wire** by `#[seiva::controller]`, ADR 0006): the transport
5//! injects it, carrying the authenticated [`Principal`]. A handler reads the
6//! caller's tenant and permissions from it to scope data **server-side** — the
7//! tenant is never taken from the request body (OWASP API1). `Ctx` is itself an
8//! axum extractor (infallible: no principal in scope → [`Principal::anonymous`]),
9//! so the generated handler builds one from the request's extensions.
10//!
11//! It also carries the request's operation coordinates (method + path) and the
12//! optional, validated `Idempotency-Key` (ADR 0011), so a write handler can fold
13//! the durable idempotency key + fingerprint **inside its transaction** without
14//! the controller macro having to grow a new parameter.
15
16use std::convert::Infallible;
17use std::sync::Arc;
18
19use axum::extract::FromRequestParts;
20use axum::http::request::Parts;
21use seiva_identity::Principal;
22use seiva_ports::Scope;
23
24use crate::idempotency::IdempotencyKey;
25
26/// The request context handed to a facade method's `&Ctx` parameter: the
27/// authenticated caller (tenant + permissions) plus the operation coordinates and
28/// an optional idempotency key.
29#[derive(Debug, Clone)]
30pub struct Ctx {
31 principal: Arc<Principal>,
32 method: String,
33 path: String,
34 idempotency_key: Option<IdempotencyKey>,
35}
36
37impl Ctx {
38 /// Builds a context around `principal` with no request coordinates and no
39 /// idempotency key (the transport fills those in via the extractor; this
40 /// constructor is what a direct caller or a test uses).
41 #[must_use]
42 pub fn new(principal: Principal) -> Self {
43 Self::from_shared(Arc::new(principal))
44 }
45
46 /// Builds a context around an **already-shared** principal — the extractor's
47 /// path. It reuses the `Arc<Principal>` the `authn` layer put in the request
48 /// extensions instead of deep-cloning the subject, tenant and permission set:
49 /// one refcount bump, no allocation (panel finding E2).
50 #[must_use]
51 pub(crate) fn from_shared(principal: Arc<Principal>) -> Self {
52 Self {
53 principal,
54 method: String::new(),
55 path: String::new(),
56 idempotency_key: None,
57 }
58 }
59
60 /// Attaches the request's method + path and an optional idempotency key — used
61 /// by the extractor, and by a test that drives a handler directly.
62 #[must_use]
63 pub fn with_request(
64 mut self,
65 method: impl Into<String>,
66 path: impl Into<String>,
67 idempotency_key: Option<IdempotencyKey>,
68 ) -> Self {
69 self.method = method.into();
70 self.path = path.into();
71 self.idempotency_key = idempotency_key;
72 self
73 }
74
75 /// The authenticated caller.
76 #[must_use]
77 pub fn principal(&self) -> &Principal {
78 self.principal.as_ref()
79 }
80
81 /// The caller's tenant, if any — the value a handler scopes its queries by.
82 /// `None` for an untenanted or anonymous caller (which must then see nothing
83 /// tenant-scoped).
84 #[must_use]
85 pub fn tenant(&self) -> Option<&str> {
86 self.principal.tenant.as_deref()
87 }
88
89 /// The caller's stable subject (empty for anonymous).
90 #[must_use]
91 pub fn subject(&self) -> &str {
92 &self.principal.subject
93 }
94
95 /// The data [`Scope`] this request runs under, derived **server-side** from the
96 /// authenticated caller — never from the request body (OWASP API1). A caller
97 /// bound to a tenant yields `Some(`[`Scope::Tenant`]`)`, so every `tenant_scoped`
98 /// write in the use case is constrained to that tenant automatically.
99 ///
100 /// **Fail-closed (SG1, ADR 0029 BOLA):** a tenant-less or anonymous caller yields
101 /// [`None`], *not* [`Scope::Global`]. The handler must treat `None` as a refusal
102 /// (the `accounts`/`notes` `scope_of` shape: `ctx.scope().ok_or(..)?`) so a
103 /// tenant-scoped command can never silently run cross-tenant. [`Scope::Global`] is
104 /// a deliberate, audited cross-tenant choice a caller writes **explicitly** (the
105 /// `seiva:allow-global` fitness-lint allowlist) — never a fallback this method
106 /// hands out.
107 #[must_use]
108 pub fn scope(&self) -> Option<Scope> {
109 self.principal.tenant.as_deref().and_then(Scope::tenant)
110 }
111
112 /// Whether the caller holds `permission`.
113 #[must_use]
114 pub fn has(&self, permission: &str) -> bool {
115 self.principal.has(permission)
116 }
117
118 /// The request method (e.g. `POST`), empty when built without a request.
119 #[must_use]
120 pub fn method(&self) -> &str {
121 &self.method
122 }
123
124 /// The request path (e.g. `/v1/catalogs`), empty when built without a request.
125 #[must_use]
126 pub fn path(&self) -> &str {
127 &self.path
128 }
129
130 /// The validated `Idempotency-Key` the caller sent, if any. Idempotency is
131 /// opt-in per request; absent (or malformed — see the extractor) means a plain,
132 /// non-deduplicated call.
133 #[must_use]
134 pub fn idempotency_key(&self) -> Option<&IdempotencyKey> {
135 self.idempotency_key.as_ref()
136 }
137}
138
139impl<S: Sync> FromRequestParts<S> for Ctx {
140 type Rejection = Infallible;
141
142 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
143 let principal = parts
144 .extensions
145 .get::<Arc<Principal>>()
146 .cloned()
147 .unwrap_or_else(|| Arc::new(Principal::anonymous()));
148 // Best-effort key: a present-but-malformed key is treated as absent (a
149 // plain create), never stored — the validation still guards the storage
150 // key. A handler that wants a hard `400` on a bad key uses the
151 // `OptionalIdempotencyKey` extractor directly instead.
152 let idempotency_key = parts
153 .headers
154 .get(crate::idempotency::IDEMPOTENCY_HEADER)
155 .and_then(|v| v.to_str().ok())
156 .and_then(|raw| IdempotencyKey::parse(raw).ok());
157 Ok(Ctx::from_shared(principal).with_request(
158 parts.method.as_str().to_owned(),
159 parts.uri.path().to_owned(),
160 idempotency_key,
161 ))
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use seiva_ports::Scope;
169
170 #[test]
171 fn a_tenant_bound_caller_scopes_to_its_tenant() {
172 let ctx = Ctx::new(Principal::in_tenant("u1", "acme", ["orders:write"]));
173 match ctx.scope() {
174 Some(Scope::Tenant(t)) => assert_eq!(t.as_str(), "acme"),
175 other => panic!("expected Some(Scope::Tenant(acme)), got {other:?}"),
176 }
177 }
178
179 #[test]
180 fn a_tenant_less_caller_fails_closed_not_global() {
181 // Audit BOLA-1: an authenticated-but-tenant-less caller must yield `None`,
182 // NEVER `Scope::Global` — the handler is forced to refuse (`.ok_or(..)?`).
183 let authn = Ctx::new(Principal::new("u1", ["orders:write"]));
184 assert_eq!(authn.scope(), None, "tenant-less must not map to a scope");
185
186 let anon = Ctx::new(Principal::anonymous());
187 assert_eq!(anon.scope(), None, "anonymous must not map to a scope");
188 }
189}