Skip to main content

plexus_auth_core/tenant/
resolver.rs

1//! `TenantResolver` — derives a sealed `Tenant` from an `AuthContext`.
2//!
3//! The framework invokes a `TenantResolver` once per request, after
4//! `SessionValidator::validate` produces the `AuthContext` and before
5//! method-scope authorization runs. The resulting `Tenant` flows through
6//! the dispatch as an extension; activation methods that declare a
7//! `&Tenant` parameter extract it from there.
8//!
9//! Two reference implementations are provided:
10//!
11//! - [`ClaimTenantResolver`] — the 80% case: pull a configured claim out
12//!   of `AuthContext.metadata` (default key: `"org_id"` per UT-S01 D3,
13//!   with a one-window `"tenant_id"` deprecation alias). When the
14//!   claim is absent and `single_user_fallback` is true, fall back to
15//!   the verified user id (single-user-deployment safe default).
16//!
17//! - [`SingleTenantResolver`] — the explicit opt-out: always resolve to
18//!   one fixed tenant value, regardless of the caller. Use this for
19//!   single-user dev installs that want tenancy off; the opt-out is
20//!   grep-able in the hub builder.
21//!
22//! See `plans/AUTHZ/AUTHZ-DATA-S01-output.md` §2 for the trait design.
23
24use crate::auth::AuthContext;
25use crate::tenant::types::{Tenant, TenantError};
26use async_trait::async_trait;
27
28/// Derives a sealed `Tenant` for an authenticated caller.
29///
30/// Backends register one resolver per hub via the hub builder
31/// (`with_tenant_resolver`); the framework invokes it once per request
32/// at dispatch entry, post-authentication and pre-method-scope-check.
33///
34/// # Failure handling
35///
36/// A `TenantError` result is converted by the dispatch layer to
37/// `AuthzError::Forbidden { reason: TenantBoundary }`; the underlying
38/// variant is captured in the `AuditRecord` (with
39/// `AuditDenyReason::TenantBoundary`) for operator investigation. The
40/// wire response is the generic forbidden error — no information is
41/// leaked about whether the failure was a missing claim, a backend
42/// lookup miss, or a malformed identifier.
43///
44/// # Bounds
45///
46/// The `Send + Sync + 'static` bounds are required by the framework's
47/// dispatch invocation pattern; the resolver is shared as an
48/// `Arc<dyn TenantResolver>` across all concurrent requests.
49#[async_trait]
50pub trait TenantResolver: Send + Sync + 'static {
51    /// Derive the tenant for the verified caller.
52    ///
53    /// Implementations should:
54    ///
55    /// - Return `Ok(Tenant)` when the caller resolves cleanly.
56    /// - Return `Err(TenantError::UnresolvedFromAuthContext)` when no
57    ///   tenant can be derived (anonymous caller, missing claim, empty
58    ///   lookup) — this is the typical denial path.
59    /// - Return `Err(TenantError::BackendResolverFailed(...))` when an
60    ///   internal lookup mechanism failed (database error, upstream
61    ///   service timeout, etc.).
62    ///
63    /// The `Ok` value is constructed through this crate's framework-
64    /// internal helpers (`mint_tenant_from_str`, crate-private), which
65    /// validate and seal the value. Resolver implementations therefore
66    /// cannot bypass the validation rules pinned on `Tenant`.
67    async fn resolve(&self, auth: &AuthContext) -> Result<Tenant, TenantError>;
68}
69
70/// Framework-internal helper that mints a `Tenant` from a string.
71///
72/// This is the only path exposed to resolver implementations (which live
73/// inside `plexus-auth-core`, so the `pub(crate)` constructor is
74/// reachable). Future ticket AUTHZ-DATA-1-DISPATCH will expose this as
75/// `pub(crate)` to plexus-core via a sealed mint trait; for now,
76/// resolvers live in this crate alongside the type and use the
77/// crate-private constructor directly.
78///
79/// Returns `TenantError::InvalidShape` if the candidate fails the
80/// validation rules pinned on `Tenant`.
81pub(crate) fn mint_tenant_from_str(s: impl Into<String>) -> Result<Tenant, TenantError> {
82    Tenant::try_new(s)
83}
84
85/// Reference impl: derive the tenant from an `AuthContext` claim.
86///
87/// Reads a configured claim key from `AuthContext.metadata` (e.g.
88/// `"org_id"`, `"tenant_id"`, `"realm"`). When `single_user_fallback`
89/// is true and the claim is absent, falls back to the caller's
90/// `user_id` so single-user deployments map each user 1:1 to their own
91/// tenant by default.
92///
93/// # Default claim key: `org_id` (UT-1, per UT-S01 D3)
94///
95/// The default claim key is **`org_id`** — the Auth0 Organizations
96/// convention pinned by the UT-S01 decision. For one deprecation window,
97/// a resolver configured with `claim_key == "org_id"` also consults the
98/// legacy `"tenant_id"` key when `org_id` is absent, so deployments whose
99/// validators still emit only `tenant_id` (e.g. pre-cutover trak) keep
100/// resolving. The alias is consulted *only* for the `org_id` default —
101/// a custom claim key is honored verbatim.
102///
103/// # Why `single_user_fallback` defaults to `true`
104///
105/// AUTHZ-DATA-S01-output Q2 leans toward the dev-safe default: a
106/// deployment without an explicit `tenant_id` claim should not silently
107/// serve cross-user data. Falling back to the user id means a
108/// misconfigured single-user install gets per-user isolation
109/// automatically; deployments that want a hard "claim required" gate
110/// flip the bool to `false`.
111#[derive(Debug, Clone)]
112pub struct ClaimTenantResolver {
113    /// The metadata key to look up (e.g. `"org_id"`, `"tenant_id"`,
114    /// `"realm"`).
115    pub claim_key: String,
116    /// When the claim is absent, fall back to the caller's `user_id` as
117    /// the tenant value. The single-user-deployment safe default.
118    pub single_user_fallback: bool,
119}
120
121/// The default claim key (UT-S01 D3: Auth0 Organizations convention).
122const ORG_ID_CLAIM: &str = "org_id";
123
124/// Legacy claim key consulted as a deprecation alias when the resolver is
125/// configured with the [`ORG_ID_CLAIM`] default and `org_id` is absent.
126/// Removed after one release window (see UT-S01 D3).
127const LEGACY_TENANT_CLAIM: &str = "tenant_id";
128
129impl ClaimTenantResolver {
130    /// Construct with the default claim key `"org_id"` and
131    /// `single_user_fallback = true`.
132    ///
133    /// Until UT-1, the default key was `"tenant_id"`; UT-S01 D3 pins
134    /// `org_id` as the tenancy claim. The legacy key remains reachable
135    /// for one deprecation window via the alias documented on the type.
136    pub fn new() -> Self {
137        Self {
138            claim_key: ORG_ID_CLAIM.into(),
139            single_user_fallback: true,
140        }
141    }
142
143    /// Construct with a custom claim key. `single_user_fallback`
144    /// remains at the dev-safe `true` default; toggle the field
145    /// directly if a strict "claim required" gate is needed.
146    pub fn with_claim_key(claim_key: impl Into<String>) -> Self {
147        Self {
148            claim_key: claim_key.into(),
149            single_user_fallback: true,
150        }
151    }
152}
153
154impl Default for ClaimTenantResolver {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160#[async_trait]
161impl TenantResolver for ClaimTenantResolver {
162    async fn resolve(&self, auth: &AuthContext) -> Result<Tenant, TenantError> {
163        if let Some(claim) = auth.get_metadata_string(&self.claim_key) {
164            return mint_tenant_from_str(claim);
165        }
166        // Deprecation alias (UT-S01 D3): the `org_id` default also reads
167        // the legacy `tenant_id` key for one release window, so pre-cutover
168        // validators that emit only `tenant_id` keep resolving. Custom
169        // claim keys are honored verbatim — no alias.
170        if self.claim_key == ORG_ID_CLAIM {
171            if let Some(claim) = auth.get_metadata_string(LEGACY_TENANT_CLAIM) {
172                return mint_tenant_from_str(claim);
173            }
174        }
175        if self.single_user_fallback && auth.is_authenticated() {
176            return mint_tenant_from_str(auth.user_id.clone());
177        }
178        Err(TenantError::UnresolvedFromAuthContext)
179    }
180}
181
182/// Reference impl: always resolve to one fixed tenant.
183///
184/// The explicit opt-out for single-user dev installs that want tenancy
185/// off (or for deployments that want a deliberately single-tenant
186/// posture). The opt-out is grep-able in the hub builder code: a
187/// reviewer searching for `SingleTenantResolver` finds every deployment
188/// that has consciously disabled multi-tenancy.
189#[derive(Debug, Clone)]
190pub struct SingleTenantResolver {
191    fixed: Tenant,
192}
193
194impl SingleTenantResolver {
195    /// Construct with the literal tenant value `"default"`.
196    ///
197    /// Panics only if `"default"` fails `Tenant::try_new` validation —
198    /// which it cannot (non-empty, short, all printable ASCII). Encoded
199    /// as `expect` so a future change to the validation rules surfaces
200    /// the failure here rather than silently shipping a non-functional
201    /// resolver.
202    pub fn new() -> Self {
203        Self {
204            fixed: Tenant::try_new("default")
205                .expect("the literal \"default\" satisfies Tenant::try_new validation"),
206        }
207    }
208
209    /// Construct with a custom fixed tenant identifier.
210    ///
211    /// Returns an error if the candidate fails `Tenant::try_new`
212    /// validation (empty, too long, non-printable bytes). The
213    /// `pub(crate)` reach to the constructor is acceptable here
214    /// because this builder is itself part of `plexus-auth-core`'s
215    /// blessed API: a backend operator who calls `with_fixed("acme")`
216    /// is explicitly opting in to a fixed tenant value at hub
217    /// configuration time, exactly as AUTHZ-DATA-S01-output §2
218    /// describes ("the opt-out is explicit and grep-able").
219    pub fn with_fixed(value: impl Into<String>) -> Result<Self, TenantError> {
220        Ok(Self {
221            fixed: Tenant::try_new(value)?,
222        })
223    }
224}
225
226impl Default for SingleTenantResolver {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232#[async_trait]
233impl TenantResolver for SingleTenantResolver {
234    async fn resolve(&self, _auth: &AuthContext) -> Result<Tenant, TenantError> {
235        Ok(self.fixed.clone())
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use serde_json::json;
243
244    fn ctx_with_metadata(user_id: &str, metadata: serde_json::Value) -> AuthContext {
245        AuthContext::new(
246            user_id.into(),
247            "sess-1".into(),
248            vec![],
249            metadata,
250        )
251    }
252
253    #[tokio::test]
254    async fn claim_resolver_pulls_org_id_by_default() {
255        // UT-1: the default claim key is `org_id` (UT-S01 D3).
256        let r = ClaimTenantResolver::new();
257        let auth = ctx_with_metadata("alice", json!({"org_id": "org_acme"}));
258        let t = r.resolve(&auth).await.unwrap();
259        assert_eq!(t.as_str(), "org_acme");
260    }
261
262    #[tokio::test]
263    async fn claim_resolver_default_prefers_org_id_over_legacy_alias() {
264        let r = ClaimTenantResolver::new();
265        let auth = ctx_with_metadata(
266            "alice",
267            json!({"org_id": "org_acme", "tenant_id": "legacy-acme"}),
268        );
269        let t = r.resolve(&auth).await.unwrap();
270        assert_eq!(t.as_str(), "org_acme");
271    }
272
273    #[tokio::test]
274    async fn claim_resolver_default_falls_back_to_legacy_tenant_id_alias() {
275        // Deprecation window (UT-S01 D3): tokens that still carry only
276        // `tenant_id` (e.g. pre-cutover trak) keep resolving.
277        let r = ClaimTenantResolver::new();
278        let auth = ctx_with_metadata("alice", json!({"tenant_id": "acme-corp"}));
279        let t = r.resolve(&auth).await.unwrap();
280        assert_eq!(t.as_str(), "acme-corp");
281    }
282
283    #[tokio::test]
284    async fn claim_resolver_custom_key_gets_no_legacy_alias() {
285        // The alias applies only to the `org_id` default; a deployment
286        // that configures `claim_key = "realm"` must not silently read
287        // `tenant_id`.
288        let r = ClaimTenantResolver {
289            claim_key: "realm".into(),
290            single_user_fallback: false,
291        };
292        let auth = ctx_with_metadata("alice", json!({"tenant_id": "acme"}));
293        let err = r.resolve(&auth).await.unwrap_err();
294        assert_eq!(err, TenantError::UnresolvedFromAuthContext);
295    }
296
297    #[tokio::test]
298    async fn claim_resolver_honors_custom_claim_key() {
299        let r = ClaimTenantResolver::with_claim_key("org_id");
300        let auth = ctx_with_metadata("alice", json!({"org_id": "neon-9"}));
301        let t = r.resolve(&auth).await.unwrap();
302        assert_eq!(t.as_str(), "neon-9");
303    }
304
305    #[tokio::test]
306    async fn claim_resolver_ignores_irrelevant_claims() {
307        let r = ClaimTenantResolver {
308            claim_key: "tenant_id".into(),
309            single_user_fallback: false,
310        };
311        let auth = ctx_with_metadata("alice", json!({"realm": "prod"}));
312        let err = r.resolve(&auth).await.unwrap_err();
313        assert_eq!(err, TenantError::UnresolvedFromAuthContext);
314    }
315
316    #[tokio::test]
317    async fn claim_resolver_falls_back_to_user_id_when_enabled() {
318        let r = ClaimTenantResolver {
319            claim_key: "tenant_id".into(),
320            single_user_fallback: true,
321        };
322        let auth = ctx_with_metadata("alice-uuid", json!({}));
323        let t = r.resolve(&auth).await.unwrap();
324        assert_eq!(t.as_str(), "alice-uuid");
325    }
326
327    #[tokio::test]
328    async fn claim_resolver_does_not_fall_back_when_disabled() {
329        let r = ClaimTenantResolver {
330            claim_key: "tenant_id".into(),
331            single_user_fallback: false,
332        };
333        let auth = ctx_with_metadata("alice", json!({}));
334        let err = r.resolve(&auth).await.unwrap_err();
335        assert_eq!(err, TenantError::UnresolvedFromAuthContext);
336    }
337
338    #[tokio::test]
339    async fn claim_resolver_rejects_anonymous_even_with_fallback() {
340        let r = ClaimTenantResolver {
341            claim_key: "tenant_id".into(),
342            single_user_fallback: true,
343        };
344        let auth = AuthContext::anonymous();
345        let err = r.resolve(&auth).await.unwrap_err();
346        assert_eq!(err, TenantError::UnresolvedFromAuthContext);
347    }
348
349    #[tokio::test]
350    async fn claim_resolver_surfaces_invalid_shape_when_claim_malformed() {
351        let r = ClaimTenantResolver::new();
352        // Claim contains a NUL — fails Tenant::try_new validation.
353        let auth = ctx_with_metadata("alice", json!({"tenant_id": "evil\0tenant"}));
354        let err = r.resolve(&auth).await.unwrap_err();
355        assert_eq!(err, TenantError::InvalidShape);
356    }
357
358    #[tokio::test]
359    async fn claim_resolver_prefers_claim_over_fallback() {
360        let r = ClaimTenantResolver {
361            claim_key: "tenant_id".into(),
362            single_user_fallback: true,
363        };
364        let auth = ctx_with_metadata("alice", json!({"tenant_id": "acme-corp"}));
365        let t = r.resolve(&auth).await.unwrap();
366        // Claim wins over fallback to user_id.
367        assert_eq!(t.as_str(), "acme-corp");
368    }
369
370    #[tokio::test]
371    async fn single_tenant_resolver_returns_default() {
372        let r = SingleTenantResolver::new();
373        let auth = ctx_with_metadata("alice", json!({"tenant_id": "ignored"}));
374        let t = r.resolve(&auth).await.unwrap();
375        assert_eq!(t.as_str(), "default");
376    }
377
378    #[tokio::test]
379    async fn single_tenant_resolver_ignores_metadata() {
380        // The whole point: the AuthContext is irrelevant to the result.
381        let r = SingleTenantResolver::new();
382        let auth1 = ctx_with_metadata("alice", json!({"tenant_id": "acme"}));
383        let auth2 = ctx_with_metadata("bob", json!({"tenant_id": "neon"}));
384        let auth3 = AuthContext::anonymous();
385        assert_eq!(r.resolve(&auth1).await.unwrap().as_str(), "default");
386        assert_eq!(r.resolve(&auth2).await.unwrap().as_str(), "default");
387        assert_eq!(r.resolve(&auth3).await.unwrap().as_str(), "default");
388    }
389
390    #[tokio::test]
391    async fn single_tenant_resolver_with_custom_fixed_value() {
392        let r = SingleTenantResolver::with_fixed("dev-tenant").unwrap();
393        let auth = AuthContext::anonymous();
394        let t = r.resolve(&auth).await.unwrap();
395        assert_eq!(t.as_str(), "dev-tenant");
396    }
397
398    #[tokio::test]
399    async fn single_tenant_resolver_rejects_invalid_fixed_value() {
400        let err = SingleTenantResolver::with_fixed("").unwrap_err();
401        assert_eq!(err, TenantError::InvalidShape);
402        let err = SingleTenantResolver::with_fixed("evil\0").unwrap_err();
403        assert_eq!(err, TenantError::InvalidShape);
404    }
405
406    #[tokio::test]
407    async fn single_tenant_resolver_never_fails_after_construction() {
408        // The trait method itself doesn't return an error path for this
409        // impl; we exercise enough auth shapes to demonstrate that.
410        let r = SingleTenantResolver::new();
411        for auth in [
412            AuthContext::anonymous(),
413            ctx_with_metadata("alice", json!({})),
414            ctx_with_metadata("bob", json!({"tenant_id": "weird"})),
415        ] {
416            assert!(r.resolve(&auth).await.is_ok());
417        }
418    }
419
420    /// Sanity: the trait is object-safe (can be stored as
421    /// `Arc<dyn TenantResolver>`). The hub builder relies on this.
422    #[tokio::test]
423    async fn resolver_is_object_safe() {
424        use std::sync::Arc;
425        let r: Arc<dyn TenantResolver> = Arc::new(SingleTenantResolver::new());
426        let auth = AuthContext::anonymous();
427        let t = r.resolve(&auth).await.unwrap();
428        assert_eq!(t.as_str(), "default");
429    }
430}