Skip to main content

backbone_orm/
org_scope.rs

1//! Org-tree request scope for the entitlement-union RLS fence (ADR-0028/0029).
2//!
3//! ADR-0028 replaces the single `company_id` scoping key with `org_unit_id`: one org tree per
4//! tenant database (root / company / branch nodes), and a session sees the UNION of the subtrees
5//! under every node it is entitled to — always including the root node, which owns tenant-wide
6//! shared rows. The database half is the policy
7//! `org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])`;
8//! this module is the application half that resolves a session's entitled ids and carries them
9//! for the duration of a request.
10//!
11//! Session variables set by an org request scope, in full:
12//! - `app.scope_unit_ids` — the entitlement-union fence (read by org policies).
13//! - `app.company_id` — the legacy equality fence during the re-key transition, resolved from
14//!   the acting node's company ancestry.
15//! - `app.acting_unit_id` — where new records land: the column DEFAULT
16//!   `nullif(current_setting('app.acting_unit_id', true), '')::uuid` on decorated tables
17//!   (ADR-0029) resolves INSERTs that omit `org_unit_id`. Unset/empty → NULL → NOT NULL
18//!   violation: an insert outside a scope fails loud, never silently unscoped.
19//! - the six `app.*` audit variables of [`crate::audit_context`] (actor, correlation id,
20//!   request facts) when the request carries a
21//!   [`RequestAuditContext`](crate::audit_context::RequestAuditContext) — set by the audited
22//!   twin [`with_org_request_scope_and_audit`], on the same request-dedicated connection, so
23//!   the auditlog capture function's triggers read attribution off every write of the request.
24//!
25//! During the module-by-module re-key both fences are live at once: some tables still read
26//! `app.company_id` (ADR-0008 equality fence), org-re-keyed tables read `app.scope_unit_ids`.
27//! [`with_org_request_scope`] therefore sets ALL THREE session variables on one request-dedicated
28//! connection. When the last company-fenced table is re-keyed, the legacy bridge retires with
29//! the old fence.
30//!
31//! The scope binds the same `REQUEST_CONN` task-local as
32//! [`with_request_scope`](crate::company_scope::with_request_scope): every scoped execute helper
33//! in this crate — and therefore every generated repository — runs on that connection and
34//! inherits the fence variables without a single call-site change.
35//!
36//! **The task-local is not the fence.** RLS is. Unscoped statements see the variables unset and
37//! match zero rows — fail-closed, identical to the ADR-0008 contract.
38
39use crate::audit_context::{AUDIT_CONTEXT_VARS, RequestAuditContext};
40use sqlx::PgPool;
41use std::fmt;
42use std::future::Future;
43use std::sync::Arc;
44use tokio::sync::Mutex;
45use uuid::Uuid;
46
47/// The fence variables an org request scope sets — the reset inventory's first half. Private:
48/// callers reset through the scope wrappers, which clear fence AND audit variables together.
49const ORG_FENCE_VARS: [&str; 3] = ["app.scope_unit_ids", "app.company_id", "app.acting_unit_id"];
50
51tokio::task_local! {
52    /// Identity of the pool the ambient request connection was drawn from. Kept beside the scope so
53    /// a nested call can prove it is asking for the SAME database before reusing that connection —
54    /// with a database per tenant, reusing across pools would run the query on the wrong one.
55    static ORG_SCOPE_POOL: std::sync::Arc<sqlx::postgres::PgConnectOptions>;
56    /// The resolved org scope of the current request: entitled unit ids (union of subtrees,
57    /// root included) and the acting node. Unset for platform callers and non-request code.
58    static ORG_SCOPE: Arc<OrgScope>;
59    /// The connection the ambient org scope bound its variables on. A nested scope of another
60    /// kind (the legacy company scope) can make a different connection the current request
61    /// connection, and that one carries none of the org variables: reuse is safe only while the
62    /// current request connection is still this one.
63    static ORG_SCOPE_CONN: Arc<Mutex<sqlx::pool::PoolConnection<sqlx::Postgres>>>;
64}
65
66/// A resolved session scope over the org tree (ADR-0028).
67///
68/// Built by [`resolve_org_scope`]; carried by [`with_org_request_scope`].
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct OrgScope {
71    scope_unit_ids: Vec<Uuid>,
72    acting_unit_id: Uuid,
73    /// The company node governing the acting node (itself for a company, nearest company
74    /// ancestor for a branch). `None` when the chain has no company node — then no legacy
75    /// `app.company_id` is set and company-fenced tables fail closed for this session.
76    legacy_company_id: Option<Uuid>,
77}
78
79impl OrgScope {
80    /// A single-company scope for paths that cannot run the resolver — chiefly composition
81    /// seams minting records on a node the request already pinned (ADR-0029's decorator makes
82    /// those inserts resolve their `org_unit_id` from `app.acting_unit_id`).
83    ///
84    /// **Precondition: `unit` must be a COMPANY node** (or whatever node kind the caller's
85    /// rows anchor on, with `legacy_company_id` semantics in mind). [`resolve_org_scope`]
86    /// derives the legacy `app.company_id` by walking ancestors from the acting node; this
87    /// constructor sets it verbatim, so a BRANCH handed here would bind a legacy variable
88    /// matching no company-fenced row and fail closed on every not-yet-stripped table.
89    ///
90    /// The scope ids are exactly `[unit]` — no root-shared rows, no sibling subtrees. That is
91    /// fail-narrow (the same property as [`execute_unit_scoped`]): inserts land on the unit
92    /// and reads see only the unit's own rows. Paths needing the session's entitlement union
93    /// must resolve a real scope instead.
94    pub fn for_company_unit(unit: Uuid) -> Self {
95        Self {
96            scope_unit_ids: vec![unit],
97            acting_unit_id: unit,
98            legacy_company_id: Some(unit),
99        }
100    }
101
102    /// Every unit id this session may see rows for: the union of the entitled subtrees plus the
103    /// root node. Order is stable (sorted) so the serialized form is deterministic.
104    pub fn scope_unit_ids(&self) -> &[Uuid] {
105        &self.scope_unit_ids
106    }
107
108    /// The node the session acts at — the default `org_unit_id` for new records and the UI's
109    /// context node.
110    pub fn acting_unit_id(&self) -> Uuid {
111        self.acting_unit_id
112    }
113
114    /// The company node for the legacy `app.company_id` fence during the re-key transition.
115    pub fn legacy_company_id(&self) -> Option<Uuid> {
116        self.legacy_company_id
117    }
118
119    /// The scope ids in the exact wire form the fence policy parses: comma-joined, no spaces.
120    fn scope_unit_ids_csv(&self) -> String {
121        self.scope_unit_ids
122            .iter()
123            .map(|id| id.to_string())
124            .collect::<Vec<_>>()
125            .join(",")
126    }
127}
128
129/// Failures of [`resolve_org_scope`] — all of them mean "do NOT open a scoped session".
130#[derive(Debug)]
131pub enum OrgScopeError {
132    /// The acting node does not exist in `organization.org_units` (wrong id, or the org spine
133    /// migration has not run in this database).
134    UnknownActingUnit(Uuid),
135    /// The database lacks the spine helpers (`organization.org_unit_subtree` / `org_unit_root`).
136    MissingSpineHelpers,
137    Database(sqlx::Error),
138}
139
140impl fmt::Display for OrgScopeError {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            Self::UnknownActingUnit(id) => {
144                write!(f, "org scope: acting unit {id} is not an organization.org_units node")
145            }
146            Self::MissingSpineHelpers => write!(
147                f,
148                "org scope: organization.org_unit_subtree / org_unit_root are missing — \
149                 has the org spine migration run in this database?"
150            ),
151            Self::Database(e) => write!(f, "org scope: resolution query failed: {e}"),
152        }
153    }
154}
155
156impl std::error::Error for OrgScopeError {}
157
158impl From<sqlx::Error> for OrgScopeError {
159    fn from(e: sqlx::Error) -> Self {
160        Self::Database(e)
161    }
162}
163
164/// Resolve a session's scope from the org tree.
165///
166/// `acting_unit` is the node the session acts at (from the signed token / tenant registry).
167/// `additional_entitled` are further nodes the session holds entitlements for (e.g. a group
168/// admin entitled to a sister company) — each contributes its whole subtree. The resolved scope
169/// is the union of those subtrees plus the root node.
170///
171/// `org_units` is unfenced by design (it IS the scoping substrate), so this runs on any
172/// connection of the tenant database regardless of fence state.
173pub async fn resolve_org_scope(
174    conn: &mut sqlx::PgConnection,
175    acting_unit: Uuid,
176    additional_entitled: &[Uuid],
177) -> Result<OrgScope, OrgScopeError> {
178    let mut roots = vec![acting_unit];
179    roots.extend_from_slice(additional_entitled);
180
181    let scope_unit_ids: Vec<Uuid> = sqlx::query_scalar(
182        "SELECT u.id FROM organization.org_unit_subtree($1::uuid[]) AS u(id) \
183         UNION SELECT organization.org_unit_root()",
184    )
185    .bind(&roots)
186    .fetch_all(&mut *conn)
187    .await
188    .map_err(|e| {
189        // 42883 undefined_function / 42P01 undefined_table both mean the spine is absent.
190        match &e {
191            sqlx::Error::Database(db) if db.code().as_deref() == Some("42883")
192                || db.code().as_deref() == Some("42P01") =>
193            {
194                OrgScopeError::MissingSpineHelpers
195            }
196            _ => OrgScopeError::Database(e),
197        }
198    })?;
199
200    if scope_unit_ids.is_empty() {
201        return Err(OrgScopeError::MissingSpineHelpers);
202    }
203    if !scope_unit_ids.contains(&acting_unit) {
204        // subtree() silently drops unknown roots; surface that instead of opening a
205        // narrower-than-asked scope (a wrong-but-working session is worse than a loud error).
206        return Err(OrgScopeError::UnknownActingUnit(acting_unit));
207    }
208
209    // Walk up from the acting node to the governing company node for the legacy fence.
210    let legacy_company_id: Option<Uuid> = sqlx::query_scalar(
211        "WITH RECURSIVE up AS ( \
212            SELECT id, parent_id, kind FROM organization.org_units WHERE id = $1 \
213            UNION ALL \
214            SELECT o.id, o.parent_id, o.kind FROM organization.org_units o \
215              JOIN up ON o.id = up.parent_id \
216         ) SELECT up.id FROM up WHERE up.kind::text = 'company' ORDER BY up.id LIMIT 1",
217    )
218    .bind(acting_unit)
219    .fetch_optional(&mut *conn)
220    .await?;
221
222    let mut sorted = scope_unit_ids;
223    sorted.sort_unstable();
224    sorted.dedup();
225
226    Ok(OrgScope {
227        scope_unit_ids: sorted,
228        acting_unit_id: acting_unit,
229        legacy_company_id,
230    })
231}
232
233/// Run `f` with a request-dedicated connection carrying the session's org scope.
234///
235/// Sets `app.scope_unit_ids` (the entitlement-union fence), the legacy `app.company_id`
236/// (equality fence, resolved from the acting node's company ancestry), and `app.acting_unit_id`
237/// (the acting-unit DEFAULT source for inserts on decorated tables, ADR-0029) at the session
238/// level, so org-re-keyed and not-yet-re-keyed tables are both fenced correctly for the whole
239/// request — including ID-only lookups, which ride the connection rather than the query text.
240///
241/// Mirrors [`with_request_scope`](crate::company_scope::with_request_scope)'s reset discipline:
242/// all three variables are cleared unconditionally before the connection returns to the pool,
243/// even when a `REQUEST_CONN` clone outlives the scope — a clone that runs queries after the
244/// reset does so unscoped (fail-closed), never with the previous session's scope.
245pub async fn with_org_request_scope<F, R>(pool: &PgPool, scope: OrgScope, f: F) -> Result<R, sqlx::Error>
246where
247    F: Future<Output = R>,
248{
249    with_org_request_scope_internal(pool, scope, None, f).await
250}
251
252/// [`with_org_request_scope`] plus the request's audit attribution (ADR-0025): the six
253/// [`RequestAuditContext`] variables are bound on the same request-dedicated connection, so
254/// every write of the request — including the ones that fire the auditlog capture function's
255/// triggers — reads the same actor and request facts off the connection it rides.
256///
257/// This is the wrapper a guarded route runs: the guard resolves the scope off the token, builds
258/// the audit context off the token's `sub` and the request itself, and the two channels travel
259/// together for the whole request. The reset discipline clears fence AND audit variables
260/// unconditionally: a pooled connection must never carry the previous request's attribution
261/// into the next one's audit rows.
262pub async fn with_org_request_scope_and_audit<F, R>(
263    pool: &PgPool,
264    scope: OrgScope,
265    audit: RequestAuditContext,
266    f: F,
267) -> Result<R, sqlx::Error>
268where
269    F: Future<Output = R>,
270{
271    with_org_request_scope_internal(pool, scope, Some(&audit), f).await
272}
273
274async fn with_org_request_scope_internal<F, R>(
275    pool: &PgPool,
276    scope: OrgScope,
277    audit: Option<&RequestAuditContext>,
278    f: F,
279) -> Result<R, sqlx::Error>
280where
281    F: Future<Output = R>,
282{
283    // Everything below the fast path lives in `open_org_request_scope`, behind a Box::pin. That is
284    // what keeps a nest cheap: this function's future would otherwise carry the whole slow path's
285    // locals — a pool connection, the Arc/Mutex holder, the bind statements and the task-local
286    // scope futures — and a three-level nest would stack three of those frames whether or not the
287    // slow path ever runs. Boxing moves them to the heap, so a nesting level costs a pointer.
288    // Reuse an ambient scope that already matches, instead of nesting a second one.
289    //
290    // A nested wrapper used to acquire a second connection, re-run the fence binds, and lay another
291    // prologue on the stack — roughly 600 KB per level in a debug build, so two levels plus the
292    // caller's own depth overflowed a default 2 MB worker thread and killed the task. It also held
293    // two pool connections for one logical request, which self-deadlocks a small pool.
294    //
295    // Three things must all hold before reuse is safe: a request connection is bound, the incoming
296    // scope is exactly the ambient one (a different scope needs its own binds), and the pool is the
297    // same (with a database per tenant, the ambient connection may be another tenant's entirely).
298    // A call carrying audit attribution always takes the slow path — its variables are not part of
299    // the scope comparison, so matching scopes say nothing about matching attribution.
300    if audit.is_none()
301        && crate::company_scope::current_request_conn()
302            .is_some_and(|conn| ORG_SCOPE_CONN.try_with(|own| Arc::ptr_eq(own, &conn)).unwrap_or(false))
303        && ORG_SCOPE.try_with(|ambient| **ambient == scope).unwrap_or(false)
304        && ORG_SCOPE_POOL
305            .try_with(|ambient| std::sync::Arc::ptr_eq(ambient, &pool.connect_options()))
306            .unwrap_or(false)
307    {
308        // The ambient scope owns the connection and will reset it; this call adds nothing to undo.
309        return Ok(f.await);
310    }
311
312    Box::pin(open_org_request_scope(pool, scope, audit, f)).await
313}
314
315/// The slow path: acquire a request-dedicated connection, bind the fence (and audit) variables on
316/// it, run `f` inside the task-locals, then reset every variable it may have set.
317async fn open_org_request_scope<F, R>(
318    pool: &PgPool,
319    scope: OrgScope,
320    audit: Option<&RequestAuditContext>,
321    f: F,
322) -> Result<R, sqlx::Error>
323where
324    F: Future<Output = R>,
325{
326    let mut conn = pool.acquire().await?;
327    sqlx::query("SELECT set_config('app.scope_unit_ids', $1, false)")
328        .bind(scope.scope_unit_ids_csv())
329        .execute(&mut *conn)
330        .await?;
331    sqlx::query("SELECT set_config('app.company_id', $1, false)")
332        .bind(scope.legacy_company_id.map(|id| id.to_string()).unwrap_or_default())
333        .execute(&mut *conn)
334        .await?;
335    sqlx::query("SELECT set_config('app.acting_unit_id', $1, false)")
336        .bind(scope.acting_unit_id.to_string())
337        .execute(&mut *conn)
338        .await?;
339    if let Some(audit) = audit {
340        audit.bind_on(&mut conn, false).await?;
341    }
342
343    let holder = Arc::new(Mutex::new(conn));
344    let scope_arc = Arc::new(scope);
345    let pool_identity = pool.connect_options();
346    // The audit attribution rides as a task-local TOO (not only as variables on
347    // the dedicated connection): write services below open their own pool
348    // transactions, whose connections the session-level binding never touches,
349    // and they relay it onto those transactions with
350    // `relay_ambient_audit_on` — the same discipline as the fence relay.
351    let audit_owned = audit.cloned();
352    let result = ORG_SCOPE_POOL
353        .scope(
354            pool_identity,
355            ORG_SCOPE_CONN.scope(holder.clone(), ORG_SCOPE.scope(scope_arc.clone(), async {
356                crate::company_scope::with_company_scope_internal(scope_arc.legacy_company_id, async {
357                    let inner = crate::company_scope::with_request_conn_internal(holder.clone(), f);
358                    match audit_owned {
359                        Some(audit) => {
360                            crate::audit_context::with_request_audit(audit, inner).await
361                        }
362                        None => inner.await,
363                    }
364                })
365                .await
366            })),
367        )
368        .await;
369
370    // Unconditional reset of every variable the scope may have set — fence always, audit when
371    // the request carried a context (resetting anyway when it did not costs six cheap
372    // set_config calls and keeps the inventory one list; see with_request_scope for the
373    // lingering-clone reasoning — the same contract applies to every variable).
374    {
375        let mut guard = holder.lock().await;
376        for var in ORG_FENCE_VARS.into_iter().chain(AUDIT_CONTEXT_VARS) {
377            if let Err(e) = sqlx::query("SELECT set_config($1, '', false)")
378                .bind(var)
379                .execute(&mut **guard)
380                .await
381            {
382                tracing::error!(
383                    target: "backbone_orm::org_scope",
384                    error = %e,
385                    var,
386                    "failed to reset fence variable on org request connection; the pool \
387                     connection may carry the previous session's scope — treat as a \
388                     fence-hygiene incident",
389                );
390            }
391        }
392    }
393    Ok(result)
394}
395
396/// The resolved org scope of the current request, if one is bound.
397///
398/// Services use the acting node as the default `org_unit_id` for new records; `None` means no
399/// org scope (platform caller or non-request code) — do not guess a node then.
400pub fn current_org_scope() -> Option<OrgScope> {
401    ORG_SCOPE.try_with(|s| s.as_ref().clone()).ok()
402}
403
404/// Bind an explicit org scope onto an already-open transaction/connection, transaction-locally.
405///
406/// The transaction twin of [`with_org_request_scope`], for hand-written write services and jobs
407/// that manage their own transaction (mirrors
408/// [`bind_company_on`](crate::company_scope::bind_company_on)). Binds all three session
409/// variables, `app.acting_unit_id` included, so an insert inside the transaction can rely on
410/// the acting-unit DEFAULT — and relays the request's audit attribution, so the transaction's
411/// changes are recorded as the caller's, not `'system'`.
412pub async fn bind_org_scope_on(
413    conn: &mut sqlx::PgConnection,
414    scope: &OrgScope,
415) -> Result<(), sqlx::Error> {
416    sqlx::query("SELECT set_config('app.scope_unit_ids', $1, true)")
417        .bind(scope.scope_unit_ids_csv())
418        .execute(&mut *conn)
419        .await?;
420    sqlx::query("SELECT set_config('app.company_id', $1, true)")
421        .bind(scope.legacy_company_id.map(|id| id.to_string()).unwrap_or_default())
422        .execute(&mut *conn)
423        .await?;
424    sqlx::query("SELECT set_config('app.acting_unit_id', $1, true)")
425        .bind(scope.acting_unit_id.to_string())
426        .execute(&mut *conn)
427        .await?;
428    // The request's actor, so the transaction's audit rows name who made the change.
429    crate::audit_context::relay_ambient_audit_on(conn).await
430}
431
432/// Statement-level org fence for a write whose row belongs to one org node — the hand-written
433/// repository path for callers outside a request scope.
434///
435/// Inside a request scope ([`with_org_request_scope`] or the legacy
436/// [`with_request_scope`](crate::company_scope::with_request_scope)) the query runs on the
437/// request connection, which already carries both fence variables. Outside one, it opens a
438/// short transaction and sets `app.scope_unit_ids` to exactly `unit`: the INSERT's
439/// `WITH CHECK` only tests the row's own `org_unit_id`, so the row's node alone satisfies it —
440/// and a read that accidentally rides this helper sees only that node (fail-narrow, never
441/// leaky). Reads that need the session's whole entitlement union must run inside a resolved
442/// request scope, not this helper.
443pub async fn execute_unit_scoped<'q>(
444    pool: &PgPool,
445    unit: Uuid,
446    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
447) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
448    if let Some(conn) = crate::company_scope::current_request_conn() {
449        let mut g = conn.lock().await;
450        return query.execute(&mut **g).await;
451    }
452    let mut tx = pool.begin().await?;
453    sqlx::query("SELECT set_config('app.scope_unit_ids', $1, true)")
454        .bind(unit.to_string())
455        .execute(&mut *tx)
456        .await?;
457    crate::audit_context::relay_ambient_audit_on(&mut tx).await?;
458    let res = query.execute(&mut *tx).await?;
459    tx.commit().await?;
460    Ok(res)
461}
462
463/// Tenant-agnostic `execute` for hand-written module SQL (ADR-0029): ride the request-dedicated
464/// connection when one is bound — carrying whatever fence variables the COMPOSING service's scope
465/// set (`with_org_request_scope` / `with_request_scope`) — otherwise execute plainly on the pool.
466///
467/// Unlike [`execute_unit_scoped`] this invents no scope of its own: a module that knows nothing
468/// about tenancy must not fabricate a unit or a company. Under a composer's request scope the
469/// database fence owns isolation; with no scope bound this is a plain unfenced execute.
470pub async fn execute_scoped<'q>(
471    pool: &PgPool,
472    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
473) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
474    if let Some(conn) = crate::company_scope::current_request_conn() {
475        let mut g = conn.lock().await;
476        return query.execute(&mut **g).await;
477    }
478    query.execute(pool).await
479}
480
481/// Tenant-agnostic `fetch_optional` for an untyped row query — the read twin of
482/// [`execute_scoped`], same connection discipline: request-dedicated connection when bound,
483/// plain pool otherwise, no scope invented.
484pub async fn fetch_optional_row_scoped<'q>(
485    pool: &PgPool,
486    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
487) -> Result<Option<sqlx::postgres::PgRow>, sqlx::Error> {
488    if let Some(conn) = crate::company_scope::current_request_conn() {
489        let mut g = conn.lock().await;
490        return query.fetch_optional(&mut **g).await;
491    }
492    query.fetch_optional(pool).await
493}
494
495/// Tenant-agnostic `fetch_all` for an untyped row query — the set-returning sibling of
496/// [`fetch_optional_row_scoped`], same connection discipline: request-dedicated connection
497/// when bound, plain pool otherwise, no scope invented. Reads that must ride the request
498/// connection (a bare-pool read under a decorated deployment lands on a fresh connection
499/// with no fence variables and returns nothing) but owe no company predicate reach for
500/// this, not the company-scoped helpers.
501pub async fn fetch_all_rows_scoped<'q>(
502    pool: &PgPool,
503    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
504) -> Result<Vec<sqlx::postgres::PgRow>, sqlx::Error> {
505    if let Some(conn) = crate::company_scope::current_request_conn() {
506        let mut g = conn.lock().await;
507        return query.fetch_all(&mut **g).await;
508    }
509    query.fetch_all(pool).await
510}
511
512/// Tenant-agnostic `fetch_one` for an untyped row query — the single-row sibling of
513/// [`fetch_optional_row_scoped`], same connection discipline: request-dedicated connection
514/// when bound, plain pool otherwise, no scope invented.
515pub async fn fetch_one_row_scoped<'q>(
516    pool: &PgPool,
517    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
518) -> Result<sqlx::postgres::PgRow, sqlx::Error> {
519    if let Some(conn) = crate::company_scope::current_request_conn() {
520        let mut g = conn.lock().await;
521        return query.fetch_one(&mut **g).await;
522    }
523    query.fetch_one(pool).await
524}
525
526#[cfg(test)]
527mod tests {
528    //! Gated on `BACKBONE_ORM_RLS_DSN` (a superuser DSN). Self-contained: builds a minimal org
529    //! spine + an org-fenced table + an app role, then proves the resolver and the request
530    //! scope against them — the same shapes the organization/inventory migrations emit.
531    use super::{resolve_org_scope, with_org_request_scope, with_org_request_scope_and_audit};
532    use crate::audit_context::RequestAuditContext;
533    use sqlx::postgres::PgPoolOptions;
534    use sqlx::PgPool;
535    use sqlx::Row;
536    use uuid::Uuid;
537
538    fn dsn() -> Option<String> {
539        std::env::var("BACKBONE_ORM_RLS_DSN").ok()
540    }
541
542    async fn admin_pool(dsn: &str) -> PgPool {
543        PgPoolOptions::new().max_connections(4).connect(dsn).await.unwrap()
544    }
545
546    async fn app_pool(dsn: &str, role: &str) -> PgPool {
547        let after_at = dsn.rsplit('@').next().unwrap();
548        let url = format!("postgresql://{role}:orgpw@{after_at}");
549        PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap()
550    }
551
552    /// Mint the per-run role name — a fixed name breaks on shared dev clusters (`DROP ROLE`
553    /// fails while the role holds grants in another database), a fresh one can never collide.
554    fn role_name() -> String {
555        format!("org_scope_app_{}", &Uuid::new_v4().simple().to_string()[..8])
556    }
557
558    async fn setup(admin: &PgPool, role: &str, root: Uuid, company: Uuid, branch: Uuid, other: Uuid) {
559        sqlx::raw_sql(&format!(
560            "DROP SCHEMA IF EXISTS organization CASCADE; \
561             DROP SCHEMA IF EXISTS org_scope_test CASCADE; \
562             CREATE SCHEMA organization; \
563             CREATE TABLE organization.org_units ( \
564                 id uuid PRIMARY KEY, kind text NOT NULL, parent_id uuid, \
565                 code text, name text NOT NULL, metadata jsonb NOT NULL DEFAULT '{{}}' \
566             ); \
567             CREATE UNIQUE INDEX one_root ON organization.org_units (kind) WHERE kind = 'root'; \
568             CREATE OR REPLACE FUNCTION organization.org_unit_subtree(p_roots uuid[]) \
569                 RETURNS SETOF uuid LANGUAGE sql STABLE AS $$ \
570                 WITH RECURSIVE tree AS ( \
571                     SELECT o.id FROM organization.org_units o WHERE o.id = ANY(p_roots) \
572                     UNION ALL \
573                     SELECT o.id FROM organization.org_units o JOIN tree t ON o.parent_id = t.id \
574                 ) SELECT id FROM tree $$; \
575             CREATE OR REPLACE FUNCTION organization.org_unit_root() RETURNS uuid \
576                 LANGUAGE sql STABLE AS $$ \
577                 SELECT id FROM organization.org_units WHERE kind = 'root' $$; \
578             CREATE SCHEMA org_scope_test; \
579             CREATE TABLE org_scope_test.t (id uuid PRIMARY KEY, org_unit_id uuid NOT NULL, code text); \
580             ALTER TABLE org_scope_test.t ENABLE ROW LEVEL SECURITY; \
581             ALTER TABLE org_scope_test.t FORCE ROW LEVEL SECURITY; \
582             CREATE POLICY t_org_isolation ON org_scope_test.t FOR ALL \
583                 USING (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])) \
584                 WITH CHECK (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])); \
585             CREATE ROLE {role} LOGIN PASSWORD 'orgpw'; \
586             GRANT USAGE ON SCHEMA organization, org_scope_test TO {role}; \
587             GRANT SELECT ON organization.org_units TO {role}; \
588             GRANT SELECT, INSERT, UPDATE, DELETE ON org_scope_test.t TO {role};",
589        ))
590        .execute(admin)
591        .await
592        .unwrap();
593
594        sqlx::query(
595            "INSERT INTO organization.org_units (id, kind, parent_id, code, name) VALUES \
596                 ($1, 'root',   NULL, 'root',  'Tenant root'), \
597                 ($2, 'company', $1,   'CO',    'Company'), \
598                 ($3, 'branch',  $2,   'BR',    'Branch'), \
599                 ($4, 'company', $1,   'OTHER', 'Other Company')",
600        )
601        .bind(root)
602        .bind(company)
603        .bind(branch)
604        .bind(other)
605        .execute(admin)
606        .await
607        .unwrap();
608    }
609
610    /// A legacy company scope nested inside an org scope makes its own connection the request
611    /// connection, and that connection carries no org variables. A second request for the same
612    /// org scope inside it must bind a connection of its own, so a write it makes reads the acting
613    /// unit, rather than reuse the legacy one and insert with no org unit.
614    #[tokio::test]
615    async fn a_nested_company_scope_never_lends_its_connection_to_an_org_scope() {
616        let Some(dsn) = dsn() else { eprintln!("skipping: set BACKBONE_ORM_RLS_DSN"); return };
617        let pool = admin_pool(&dsn).await;
618        let unit = Uuid::new_v4();
619        let scope = super::OrgScope::for_company_unit(unit);
620        let acting = with_org_request_scope(&pool, scope.clone(), async {
621            crate::company_scope::with_request_scope(&pool, unit, async {
622                with_org_request_scope(&pool, scope.clone(), async {
623                    let row = super::fetch_optional_row_scoped(
624                        &pool,
625                        sqlx::query("SELECT current_setting('app.acting_unit_id', true) AS acting"),
626                    )
627                    .await
628                    .unwrap()
629                    .unwrap();
630                    row.get::<Option<String>, _>("acting")
631                })
632                .await
633                .unwrap()
634            })
635            .await
636            .unwrap()
637        })
638        .await
639        .unwrap();
640        assert_eq!(acting.as_deref(), Some(unit.to_string().as_str()));
641    }
642
643    #[tokio::test]
644    async fn resolver_and_fence_shape() {
645        let Some(dsn) = dsn() else { eprintln!("skipping: set BACKBONE_ORM_RLS_DSN"); return };
646        let root = Uuid::new_v4();
647        let company = Uuid::new_v4();
648        let branch = Uuid::new_v4();
649        let other = Uuid::new_v4();
650        let role = role_name();
651        let admin = admin_pool(&dsn).await;
652        setup(&admin, &role, root, company, branch, other).await;
653
654        // Seed as superuser (bypasses RLS).
655        sqlx::query("INSERT INTO org_scope_test.t (id, org_unit_id, code) VALUES ($1,$2,'CO-WH'), ($3,$4,'BR-WH'), ($5,$6,'OTHER-WH')")
656            .bind(Uuid::new_v4()).bind(company)
657            .bind(Uuid::new_v4()).bind(branch)
658            .bind(Uuid::new_v4()).bind(other)
659            .execute(&admin).await.unwrap();
660
661        // Resolve from the branch node: subtree() DESCENDS only, so the scope is the branch's
662        // own subtree (itself) plus the root node — the parent company is NOT auto-included;
663        // seeing it requires entitlement. Legacy bridge = the governing company.
664        let mut conn = admin.acquire().await.unwrap();
665        let scope = resolve_org_scope(&mut conn, branch, &[]).await.unwrap();
666        let mut got = scope.scope_unit_ids().to_vec();
667        got.sort_unstable();
668        let mut want = vec![branch, root];
669        want.sort_unstable();
670        assert_eq!(got, want);
671        assert_eq!(scope.acting_unit_id(), branch);
672        assert_eq!(scope.legacy_company_id(), Some(company));
673
674        // Union entitlement: branch acting + sister company entitled.
675        let scope_union = resolve_org_scope(&mut conn, branch, &[other]).await.unwrap();
676        assert!(scope_union.scope_unit_ids().contains(&other));
677
678        // Unknown acting node is a loud error, not a narrower scope.
679        let ghost = resolve_org_scope(&mut conn, Uuid::new_v4(), &[]).await;
680        assert!(ghost.is_err());
681
682        // The request scope fences queries on the app role's pool. The scoped helper (not a raw
683        // pool fetch) is the interesting path: it must route onto the request connection the
684        // scope bound, which carries the fence variables.
685        let pool = app_pool(&dsn, &role).await;
686        let (codes, twin_codes): (Vec<String>, Vec<String>) =
687            with_org_request_scope(&pool, scope, async {
688                let codes: Vec<String> = crate::company_scope::fetch_all_scoped(
689                    &pool,
690                    sqlx::query_as::<_, (String,)>("SELECT code FROM org_scope_test.t ORDER BY code"),
691                )
692                .await
693                .unwrap()
694                .into_iter()
695                .map(|r| r.0)
696                .collect();
697                // The tenant-agnostic fetch-all twin rides the same request
698                // connection and therefore the same fence — the honest helper
699                // for reads that owe no company predicate.
700                let twin_codes: Vec<String> = super::fetch_all_rows_scoped(
701                    &pool,
702                    sqlx::query("SELECT code FROM org_scope_test.t ORDER BY code"),
703                )
704                .await
705                .unwrap()
706                .into_iter()
707                .map(|r| r.get::<String, &str>("code"))
708                .collect();
709                (codes, twin_codes)
710            })
711            .await
712            .unwrap();
713        assert_eq!(codes, ["BR-WH"], "branch session sees only its subtree (+ shared root rows), not the company or sister-company rows");
714        assert_eq!(
715            twin_codes, codes,
716            "the org-scope fetch-all twin fences identically to the scoped helper"
717        );
718
719        // A bare pool read (no request connection, no fence variables on the
720        // freshly acquired connection) sees nothing under the decorated fence —
721        // the failure mode that makes riding the request connection mandatory.
722        let bare: Vec<String> = sqlx::query("SELECT code FROM org_scope_test.t")
723            .fetch_all(&pool)
724            .await
725            .unwrap()
726            .into_iter()
727            .map(|r| r.get::<String, usize>(0))
728            .collect();
729        assert!(
730            bare.is_empty(),
731            "a bare pool read must not see fenced rows"
732        );
733
734        // After the scope, the pooled connection is clean (fail-closed for the next acquire).
735        let mut after = pool.acquire().await.unwrap();
736        let setting: String =
737            sqlx::query_scalar("SELECT current_setting('app.scope_unit_ids', true)")
738                .fetch_one(&mut *after)
739                .await
740                .unwrap();
741        assert_eq!(setting, "", "scope leaked onto the pooled connection");
742    }
743
744    /// The audit-context channel of the request scope (ADR-0025): the audited twin binds the
745    /// six `app.*` attribution variables on the request-dedicated connection, a row-level
746    /// trigger on a write through the scoped helpers reads them off that connection, and every
747    /// variable — fence AND audit — is cleared before the connection returns to the pool. The
748    /// unaudited twin leaves the audit variables unset (the capture function's `'system'`
749    /// fallback reads exactly that: empty).
750    ///
751    /// Runs in its own disposable database (dropped at the end), because the spine-building
752    /// sibling test above recreates the `organization` schema and would race this one's if they
753    /// shared a database — cargo runs test fns concurrently.
754    #[tokio::test]
755    async fn audit_context_binds_rides_and_clears_with_the_scope() {
756        let Some(maintenance_dsn) = dsn() else {
757            eprintln!("skipping: set BACKBONE_ORM_RLS_DSN");
758            return;
759        };
760        const PROOF_DB: &str = "backbone_orm_audit_ctx_probe";
761        let proof_dsn = {
762            let (before_db, ..) = maintenance_dsn.rsplit_once('/').unwrap();
763            format!("{before_db}/{PROOF_DB}")
764        };
765        let maintenance = admin_pool(&maintenance_dsn).await;
766        // Each statement rides its own simple-protocol query — CREATE/DROP DATABASE may not run
767        // inside a transaction block.
768        sqlx::raw_sql(&format!("DROP DATABASE IF EXISTS {PROOF_DB} WITH (FORCE)"))
769            .execute(&maintenance)
770            .await
771            .unwrap();
772        sqlx::raw_sql(&format!("CREATE DATABASE {PROOF_DB}"))
773            .execute(&maintenance)
774            .await
775            .unwrap();
776        let admin = admin_pool(&proof_dsn).await;
777
778        let root = Uuid::new_v4();
779        let company = Uuid::new_v4();
780        let role = role_name();
781        // The spine + fenced table of the sibling test, plus the audit probe: a table and an
782        // AFTER INSERT trigger capturing two of the attribution variables — the minimal shape
783        // of the auditlog module's capture function, whose contract this pins without the
784        // framework crate depending on a domain module.
785        sqlx::raw_sql(&format!(
786            "CREATE SCHEMA organization; \
787             CREATE TABLE organization.org_units ( \
788                 id uuid PRIMARY KEY, kind text NOT NULL, parent_id uuid, \
789                 code text, name text NOT NULL, metadata jsonb NOT NULL DEFAULT '{{}}' \
790             ); \
791             CREATE OR REPLACE FUNCTION organization.org_unit_subtree(p_roots uuid[]) \
792                 RETURNS SETOF uuid LANGUAGE sql STABLE AS $$ \
793                 WITH RECURSIVE tree AS ( \
794                     SELECT o.id FROM organization.org_units o WHERE o.id = ANY(p_roots) \
795                     UNION ALL \
796                     SELECT o.id FROM organization.org_units o JOIN tree t ON o.parent_id = t.id \
797                 ) SELECT id FROM tree $$; \
798             CREATE OR REPLACE FUNCTION organization.org_unit_root() RETURNS uuid \
799                 LANGUAGE sql STABLE AS $$ \
800                 SELECT id FROM organization.org_units WHERE kind = 'root' $$; \
801             CREATE SCHEMA org_scope_test; \
802             CREATE TABLE org_scope_test.t (id uuid PRIMARY KEY, org_unit_id uuid NOT NULL \
803                 DEFAULT nullif(current_setting('app.acting_unit_id', true), '')::uuid, code text); \
804             ALTER TABLE org_scope_test.t ENABLE ROW LEVEL SECURITY; \
805             ALTER TABLE org_scope_test.t FORCE ROW LEVEL SECURITY; \
806             CREATE POLICY t_org_isolation ON org_scope_test.t FOR ALL \
807                 USING (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])) \
808                 WITH CHECK (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])); \
809             CREATE TABLE org_scope_test.audit_probe ( \
810                 id bigserial PRIMARY KEY, actor text NOT NULL, correlation_id text NOT NULL \
811             ); \
812             CREATE FUNCTION org_scope_test.capture_probe() RETURNS trigger LANGUAGE plpgsql AS $$ \
813                 BEGIN \
814                     INSERT INTO org_scope_test.audit_probe (actor, correlation_id) \
815                     VALUES (current_setting('app.actor', true), \
816                             current_setting('app.correlation_id', true)); \
817                     RETURN NULL; \
818                 END $$; \
819             CREATE TRIGGER t_audit_probe AFTER INSERT ON org_scope_test.t \
820                 FOR EACH ROW EXECUTE FUNCTION org_scope_test.capture_probe(); \
821             CREATE ROLE {role} LOGIN PASSWORD 'orgpw'; \
822             GRANT USAGE ON SCHEMA organization, org_scope_test TO {role}; \
823             GRANT SELECT ON organization.org_units TO {role}; \
824             GRANT SELECT, INSERT ON org_scope_test.t TO {role}; \
825             GRANT INSERT ON org_scope_test.audit_probe TO {role}; \
826             GRANT USAGE, SELECT ON SEQUENCE org_scope_test.audit_probe_id_seq TO {role};",
827        ))
828        .execute(&admin)
829        .await
830        .unwrap();
831        sqlx::query(
832            "INSERT INTO organization.org_units (id, kind, parent_id, code, name) VALUES \
833                 ($1, 'root',    NULL, 'ROOT', 'Tenant root'), \
834                 ($2, 'company', $1,   'CO',   'Company')",
835        )
836        .bind(root)
837        .bind(company)
838        .execute(&admin)
839        .await
840        .unwrap();
841
842        let pool = app_pool(&proof_dsn, &role).await;
843        let scope = {
844            let mut conn = admin.acquire().await.unwrap();
845            resolve_org_scope(&mut conn, company, &[]).await.unwrap()
846        };
847
848        // 1. The audited twin: every attribution variable is set on the connection writes ride
849        //    (inventory proof, same style as the fence-variable inventory above), and a trigger
850        //    on a real insert reads them — the seam the auditlog capture function depends on.
851        let audit = RequestAuditContext {
852            actor: "user-77".to_string(),
853            correlation_id: "corr-77".to_string(),
854            client_ip: "203.0.113.7".to_string(),
855            user_agent: "probe-agent/1.0".to_string(),
856            http_method: "POST".to_string(),
857            resource_path: "/api/v1/probe/widgets".to_string(),
858        };
859        let inserted = Uuid::new_v4();
860        let settings: Vec<(String, String)> = with_org_request_scope_and_audit(
861            &pool,
862            scope.clone(),
863            audit.clone(),
864            async {
865                crate::company_scope::execute_scoped(
866                    &pool,
867                    sqlx::query("INSERT INTO org_scope_test.t (id, code) VALUES ($1, 'AUDITED')")
868                        .bind(inserted),
869                )
870                .await
871                .unwrap();
872                crate::company_scope::fetch_all_scoped(
873                    &pool,
874                    sqlx::query_as::<_, (String, String)>(
875                        "SELECT s.name, current_setting(s.name, true) FROM unnest(ARRAY[\
876                         'app.actor','app.correlation_id','app.client_ip','app.user_agent',\
877                         'app.http_method','app.resource_path']) AS s(name)",
878                    ),
879                )
880                .await
881                .unwrap()
882            },
883        )
884        .await
885        .unwrap();
886        for (var, want) in audit.pairs() {
887            let got = settings
888                .iter()
889                .find(|(n, _)| n == var)
890                .map(|(_, v)| v.as_str())
891                .unwrap_or_else(|| panic!("{var} missing from the inventory query"));
892            assert_eq!(got, want, "{var} must ride the request connection");
893        }
894        // The fence still works under the audited twin: the acting-unit DEFAULT filled the row.
895        let landed: Uuid = sqlx::query_scalar("SELECT org_unit_id FROM org_scope_test.t WHERE id = $1")
896            .bind(inserted)
897            .fetch_one(&admin)
898            .await
899            .unwrap();
900        assert_eq!(landed, company, "audit channel must not disturb the fence");
901        let probe: (String, String) =
902            sqlx::query_as("SELECT actor, correlation_id FROM org_scope_test.audit_probe ORDER BY id DESC LIMIT 1")
903                .fetch_one(&admin)
904                .await
905                .unwrap();
906        assert_eq!(probe, ("user-77".to_string(), "corr-77".to_string()),
907            "a row-level trigger on the insert must read the bound attribution");
908
909        // 2. Pool hygiene: after the scope, no audit variable survives on the pooled connection.
910        let mut after = pool.acquire().await.unwrap();
911        for var in crate::audit_context::AUDIT_CONTEXT_VARS {
912            let v: String = sqlx::query_scalar("SELECT current_setting($1, true)")
913                .bind(var)
914                .fetch_one(&mut *after)
915                .await
916                .unwrap();
917            assert_eq!(v, "", "{var} leaked onto the pooled connection");
918        }
919        drop(after);
920
921        // 3. The unaudited twin leaves the channel unset — the capture function's `'system'`
922        //    fallback and NULL columns read exactly this empty wire form.
923        let plain = Uuid::new_v4();
924        with_org_request_scope(&pool, scope, async {
925            crate::company_scope::execute_scoped(
926                &pool,
927                sqlx::query("INSERT INTO org_scope_test.t (id, code) VALUES ($1, 'PLAIN')")
928                    .bind(plain),
929            )
930            .await
931            .unwrap();
932        })
933        .await
934        .unwrap();
935        let probe: (String, String) =
936            sqlx::query_as("SELECT actor, correlation_id FROM org_scope_test.audit_probe ORDER BY id DESC LIMIT 1")
937                .fetch_one(&admin)
938                .await
939                .unwrap();
940        assert_eq!(probe, (String::new(), String::new()),
941            "without an audit context the channel reads empty, never the previous request's");
942
943        // Zero residue: schemas + role in the proof database, then the database itself.
944        sqlx::raw_sql(&format!(
945            "DROP SCHEMA organization CASCADE; DROP SCHEMA org_scope_test CASCADE; DROP ROLE {role};"
946        ))
947        .execute(&admin)
948        .await
949        .unwrap();
950        pool.close().await;
951        admin.close().await;
952        sqlx::raw_sql(&format!("DROP DATABASE IF EXISTS {PROOF_DB} WITH (FORCE);"))
953            .execute(&maintenance)
954            .await
955            .unwrap();
956        maintenance.close().await;
957    }
958}