backbone_orm/company_scope.rs
1//! Request company scope for the Postgres RLS read/write fence (ADR-0008).
2//!
3//! The security boundary is the database: every company-scoped table carries a Row-Level-Security
4//! policy `USING (company_id = NULLIF(current_setting('app.company_id', true), '')::uuid)`. This
5//! module is the *application* half — it carries the caller's company for the duration of a request
6//! and sets `app.company_id` on the connection each statement runs on.
7//!
8//! Why a task-local and not a signature parameter: the ORM executes connection-per-statement
9//! against a shared pool (`fetch_all(&self.pool)`), so there is no request-held connection to bind,
10//! and threading a scope argument through `CrudService::list` would be a breaking change across ~40
11//! modules that *still* would not reach raw `sqlx::query` callers. The task-local rides the async
12//! task instead, and the scoped execute helpers below set `app.company_id` transaction-locally so a
13//! value never leaks onto a pooled connection reused by the next request.
14//!
15//! **The task-local is not the fence.** RLS is. A statement that runs without the task-local set
16//! (a missed call site, a raw query, a spawned job) sees `app.company_id` unset → the policy matches
17//! zero rows. That is fail-closed: such a path *breaks* (returns empty), it never leaks. These
18//! helpers exist so the ORM read path returns the caller's rows instead of empty — correctness, not
19//! safety.
20
21use sqlx::pool::PoolConnection;
22use sqlx::postgres::{PgArguments, PgRow};
23use sqlx::query::{Query, QueryAs, QueryScalar};
24use sqlx::{FromRow, PgPool, Postgres};
25use std::future::Future;
26use std::sync::Arc;
27use tokio::sync::Mutex;
28use uuid::Uuid;
29
30tokio::task_local! {
31 /// The company the current request is scoped to. `Platform` callers and unscoped code leave
32 /// this unset; `None` inside the scope means an explicit platform (no-fence) caller.
33 static COMPANY: Option<Uuid>;
34
35 /// A connection dedicated to the current request, with `app.company_id` already set at the
36 /// SESSION level. When present, every scoped execute helper runs on it — so an ID-only lookup in
37 /// a hand-written service (e.g. `SELECT … WHERE id = $1`, with no `company_id` in the query) is
38 /// still fenced, because the scope rides the connection rather than the query text. This is the
39 /// path that makes custom write services RLS-correct without threading a company argument through
40 /// every method. Set by [`with_request_scope`].
41 static REQUEST_CONN: Arc<Mutex<PoolConnection<Postgres>>>;
42}
43
44/// Run `f` with a request-dedicated connection whose `app.company_id` is set to `company`.
45///
46/// Acquires one connection from `pool`, sets the session variable on it, and binds it as the
47/// request connection for the duration of `f`. Every scoped execute helper called inside `f` — from
48/// the ORM or a hand-written service — runs on this connection, so the whole request shares one
49/// company scope set exactly once (no per-statement transaction, and ID-only lookups are fenced
50/// too). The variable is reset before the connection returns to the pool, so it can never ride into
51/// the next request.
52///
53/// Trade-off: this pins a pooled connection for the request's lifetime (vs. connection-per-statement),
54/// so size the pool for peak concurrent requests. Prefer this at the HTTP composition root; leave
55/// non-request callers (jobs) on [`with_company_scope`] (per-statement scoping).
56pub async fn with_request_scope<F, R>(pool: &PgPool, company: Uuid, f: F) -> Result<R, sqlx::Error>
57where
58 F: Future<Output = R>,
59{
60 let mut conn = pool.acquire().await?;
61 sqlx::query("SELECT set_config('app.company_id', $1, false)")
62 .bind(company.to_string())
63 .execute(&mut *conn)
64 .await?;
65
66 let holder = Arc::new(Mutex::new(conn));
67 // Publish the COMPANY task-local too, matching `with_company_scope`'s visibility contract.
68 // The dedicated connection carries the company in its session var, but code that asks
69 // `current_company()` (application-layer adapters, audit stamps) has no other way to learn
70 // it — the two scope modes must not disagree about task-local visibility, or request-scoped
71 // deployments silently degrade `current_company()` to `None` for every handler.
72 let result = COMPANY
73 .scope(Some(company), REQUEST_CONN.scope(holder.clone(), f))
74 .await;
75
76 // Unconditional reset. We do NOT gate on `Arc::try_unwrap(holder)` (sole-reference check):
77 // `REQUEST_CONN` is a clonable `Arc`, and every scoped helper takes a clone via `request_conn()`.
78 // A clone that outlives the scope (a `tokio::spawn` capturing it, a value held across an `.await`
79 // that outlives the request future, or cancellation with a lingering task) would make `try_unwrap`
80 // return `Err`, skipping this block entirely and leaving `app.company_id` set at SESSION level —
81 // the connection then returns to the pool dirty, and the next acquire reads the PREVIOUS tenant's
82 // rows. That is a non-deterministic cross-tenant leak, not fail-closed. (Regression test:
83 // `lingering_request_conn_clone_does_not_dirty_the_pooled_connection`.)
84 //
85 // Locking the mutex here serializes behind any in-flight clone query, then clears the session var
86 // regardless of how many clones exist or when they drop. The `PoolConnection` only returns to the
87 // pool when the LAST `Arc` reference drops — by which point the var is already cleared here. A
88 // clone that runs further queries after this reset does so unscoped (fail-closed), which is the
89 // correct behaviour for work that outlived its request scope.
90 {
91 let mut guard = holder.lock().await;
92 if let Err(e) = sqlx::query("SELECT set_config('app.company_id', '', false)")
93 .execute(&mut **guard)
94 .await
95 {
96 // A reset failure (transient DB error) could leave the session var set. We cannot `detach`
97 // the connection from a `&mut` borrow, so log loud at ERROR — this must surface in ops as
98 // a fence-hygiene alert, not be swallowed silently. (Previously `let _ =` hid this.)
99 tracing::error!(
100 target: "backbone_orm::company_scope",
101 error = %e,
102 "failed to reset app.company_id on request connection; the pool connection may carry \
103 the previous tenant's company_id — treat as a fence-hygiene incident",
104 );
105 }
106 }
107 Ok(result)
108}
109
110/// The request-dedicated connection, if [`with_request_scope`] set one for this task.
111fn request_conn() -> Option<Arc<Mutex<PoolConnection<Postgres>>>> {
112 REQUEST_CONN.try_with(|c| c.clone()).ok()
113}
114
115/// The request-dedicated connection for callers outside this module (`org_scope`'s
116/// statement-level helpers route onto the same connection so request-scoped sessions and
117/// per-statement callers share one fence surface).
118pub(crate) fn current_request_conn() -> Option<Arc<Mutex<PoolConnection<Postgres>>>> {
119 request_conn()
120}
121
122/// Run `f` with the request's company scope bound to the current async task.
123///
124/// Middleware calls this once per request with the company derived from the signed token, so every
125/// query issued while handling the request inherits it. `Some(uuid)` fences to that company;
126/// `None` is an explicit platform caller (no `app.company_id` is set → RLS-fenced tables return
127/// zero rows unless the connecting role bypasses RLS).
128pub async fn with_company_scope<F, R>(company: Option<Uuid>, f: F) -> R
129where
130 F: Future<Output = R>,
131{
132 COMPANY.scope(company, f).await
133}
134
135/// Internal: bind ONLY the `COMPANY` task-local around `f`, without acquiring a connection or
136/// setting any session variable.
137///
138/// For [`org_scope`](crate::org_scope), which drives its own request-dedicated connection and
139/// must not nest the full [`with_request_scope`] (that would acquire a second connection and
140/// re-set `app.company_id` from the legacy argument alone).
141pub(crate) async fn with_company_scope_internal<F, R>(company: Option<Uuid>, f: F) -> R
142where
143 F: Future<Output = R>,
144{
145 COMPANY.scope(company, f).await
146}
147
148/// Internal: bind ONLY the `REQUEST_CONN` task-local around `f`, without acquiring a connection
149/// or setting any session variable. The caller owns the connection and its fence variables.
150///
151/// For [`org_scope`](crate::org_scope), same reason as [`with_company_scope_internal`].
152pub(crate) async fn with_request_conn_internal<F, R>(
153 holder: Arc<Mutex<PoolConnection<Postgres>>>,
154 f: F,
155) -> R
156where
157 F: Future<Output = R>,
158{
159 REQUEST_CONN.scope(holder, f).await
160}
161
162/// The company bound to the current task, or `None` when no scope is set (unscoped code path).
163///
164/// `Ok(Some(id))` — fenced to a company. `Ok(None)` / no scope — no `app.company_id` will be set.
165/// The two `None` cases are intentionally indistinguishable here: neither sets the session var, and
166/// RLS fails closed for both.
167pub fn current_company() -> Option<Uuid> {
168 COMPANY.try_with(|c| *c).ok().flatten()
169}
170
171/// Set `app.company_id` transaction-locally on `conn`, with the request's audit attribution.
172///
173/// `set_config(_, _, true)` — the `true` scopes it to the surrounding transaction, so it is
174/// discarded on commit/rollback and cannot ride a pooled connection into the next request.
175/// The actor rides along: a transaction scoped here is one a write service opened itself, and
176/// without the relay its audit triggers would record the change as `'system'`.
177async fn bind_company(conn: &mut sqlx::PgConnection, company: Uuid) -> Result<(), sqlx::Error> {
178 sqlx::query("SELECT set_config('app.company_id', $1, true)")
179 .bind(company.to_string())
180 .execute(&mut *conn)
181 .await?;
182 crate::audit_context::relay_ambient_audit_on(conn).await
183}
184
185/// Bind an EXPLICIT company onto an already-open transaction/connection.
186///
187/// For call sites that know their company directly (it is on the DTO, or was just read off the row)
188/// and open their own transaction — the common shape in hand-written write services. Prefer this over
189/// [`bind_current_company`] when the company is known: it does not depend on an ambient task-local, so
190/// it is correct for non-request callers (event subscribers, jobs) too.
191pub async fn bind_company_on(
192 conn: &mut sqlx::PgConnection,
193 company: Uuid,
194) -> Result<(), sqlx::Error> {
195 bind_company(conn, company).await
196}
197
198/// Bind the current task's company onto an already-open transaction/connection.
199///
200/// For call sites that manage their own transaction (batch operations run all-or-nothing inside one
201/// `pool.begin()`): call this immediately after `begin()` so every statement in the transaction is
202/// company-scoped. A no-op when no company is in scope (fail-closed at the DB for fenced tables).
203pub async fn bind_current_company(conn: &mut sqlx::PgConnection) -> Result<(), sqlx::Error> {
204 match current_company() {
205 Some(company) => bind_company(conn, company).await,
206 // No company in scope (org-unit tenancy, jobs): nothing to fence here, but the change
207 // still belongs to whoever made the request.
208 None => crate::audit_context::relay_ambient_audit_on(conn).await,
209 }
210}
211
212// ─── Scoped execute helpers ────────────────────────────────────────────────────
213//
214// Each wraps a fully-bound query. When a company is in scope, the query runs inside a transaction
215// that first sets `app.company_id`; otherwise it runs directly against the pool (fail-closed at the
216// DB for fenced tables). The extra BEGIN/COMMIT per statement is the cost of connection-per-statement
217// pooling; a request-scoped held connection could remove it later (ADR-0008 follow-up).
218
219/// `fetch_all` for a typed row query, company-scoped.
220pub async fn fetch_all_scoped<'q, T>(
221 pool: &PgPool,
222 query: QueryAs<'q, Postgres, T, PgArguments>,
223) -> Result<Vec<T>, sqlx::Error>
224where
225 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
226{
227 if let Some(conn) = request_conn() {
228 let mut g = conn.lock().await;
229 return query.fetch_all(&mut **g).await;
230 }
231 match current_company() {
232 None => query.fetch_all(pool).await,
233 Some(company) => {
234 let mut tx = pool.begin().await?;
235 bind_company(&mut tx, company).await?;
236 let rows = query.fetch_all(&mut *tx).await?;
237 tx.commit().await?;
238 Ok(rows)
239 }
240 }
241}
242
243/// `fetch_one` for a typed row query, company-scoped.
244pub async fn fetch_one_scoped<'q, T>(
245 pool: &PgPool,
246 query: QueryAs<'q, Postgres, T, PgArguments>,
247) -> Result<T, sqlx::Error>
248where
249 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
250{
251 if let Some(conn) = request_conn() {
252 let mut g = conn.lock().await;
253 return query.fetch_one(&mut **g).await;
254 }
255 match current_company() {
256 None => query.fetch_one(pool).await,
257 Some(company) => {
258 let mut tx = pool.begin().await?;
259 bind_company(&mut tx, company).await?;
260 let row = query.fetch_one(&mut *tx).await?;
261 tx.commit().await?;
262 Ok(row)
263 }
264 }
265}
266
267/// `fetch_optional` for a typed row query, company-scoped.
268pub async fn fetch_optional_scoped<'q, T>(
269 pool: &PgPool,
270 query: QueryAs<'q, Postgres, T, PgArguments>,
271) -> Result<Option<T>, sqlx::Error>
272where
273 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
274{
275 if let Some(conn) = request_conn() {
276 let mut g = conn.lock().await;
277 return query.fetch_optional(&mut **g).await;
278 }
279 match current_company() {
280 None => query.fetch_optional(pool).await,
281 Some(company) => {
282 let mut tx = pool.begin().await?;
283 bind_company(&mut tx, company).await?;
284 let row = query.fetch_optional(&mut *tx).await?;
285 tx.commit().await?;
286 Ok(row)
287 }
288 }
289}
290
291/// `fetch_one` for a scalar query (e.g. `COUNT(*)`), company-scoped.
292pub async fn fetch_one_scalar_scoped<'q, S>(
293 pool: &PgPool,
294 query: QueryScalar<'q, Postgres, S, PgArguments>,
295) -> Result<S, sqlx::Error>
296where
297 S: Send + Unpin,
298 (S,): for<'r> FromRow<'r, PgRow>,
299{
300 if let Some(conn) = request_conn() {
301 let mut g = conn.lock().await;
302 return query.fetch_one(&mut **g).await;
303 }
304 match current_company() {
305 None => query.fetch_one(pool).await,
306 Some(company) => {
307 let mut tx = pool.begin().await?;
308 bind_company(&mut tx, company).await?;
309 let val = query.fetch_one(&mut *tx).await?;
310 tx.commit().await?;
311 Ok(val)
312 }
313 }
314}
315
316/// `fetch_optional` for a scalar query (e.g. `SELECT 1 … LIMIT 1`), company-scoped.
317pub async fn fetch_optional_scalar_scoped<'q, S>(
318 pool: &PgPool,
319 query: QueryScalar<'q, Postgres, S, PgArguments>,
320) -> Result<Option<S>, sqlx::Error>
321where
322 S: Send + Unpin,
323 (S,): for<'r> FromRow<'r, PgRow>,
324{
325 if let Some(conn) = request_conn() {
326 let mut g = conn.lock().await;
327 return query.fetch_optional(&mut **g).await;
328 }
329 match current_company() {
330 None => query.fetch_optional(pool).await,
331 Some(company) => {
332 let mut tx = pool.begin().await?;
333 bind_company(&mut tx, company).await?;
334 let val = query.fetch_optional(&mut *tx).await?;
335 tx.commit().await?;
336 Ok(val)
337 }
338 }
339}
340
341/// `fetch_optional` for an untyped row query (`sqlx::query(..)` → `PgRow`), company-scoped.
342///
343/// Hand-written services commonly read ad-hoc column sets as raw rows rather than a typed struct;
344/// these mirror the typed helpers so such a service can be scoped without restructuring its queries.
345pub async fn fetch_optional_row_scoped<'q>(
346 pool: &PgPool,
347 query: Query<'q, Postgres, PgArguments>,
348) -> Result<Option<PgRow>, sqlx::Error> {
349 if let Some(conn) = request_conn() {
350 let mut g = conn.lock().await;
351 return query.fetch_optional(&mut **g).await;
352 }
353 match current_company() {
354 None => query.fetch_optional(pool).await,
355 Some(company) => {
356 let mut tx = pool.begin().await?;
357 bind_company(&mut tx, company).await?;
358 let row = query.fetch_optional(&mut *tx).await?;
359 tx.commit().await?;
360 Ok(row)
361 }
362 }
363}
364
365/// `fetch_one` for an untyped row query (`sqlx::query(..)` → `PgRow`), company-scoped.
366pub async fn fetch_one_row_scoped<'q>(
367 pool: &PgPool,
368 query: Query<'q, Postgres, PgArguments>,
369) -> Result<PgRow, sqlx::Error> {
370 if let Some(conn) = request_conn() {
371 let mut g = conn.lock().await;
372 return query.fetch_one(&mut **g).await;
373 }
374 match current_company() {
375 None => query.fetch_one(pool).await,
376 Some(company) => {
377 let mut tx = pool.begin().await?;
378 bind_company(&mut tx, company).await?;
379 let row = query.fetch_one(&mut *tx).await?;
380 tx.commit().await?;
381 Ok(row)
382 }
383 }
384}
385
386/// `fetch_all` for an untyped row query (`sqlx::query(..)` → `Vec<PgRow>`), company-scoped.
387pub async fn fetch_all_rows_scoped<'q>(
388 pool: &PgPool,
389 query: Query<'q, Postgres, PgArguments>,
390) -> Result<Vec<PgRow>, sqlx::Error> {
391 if let Some(conn) = request_conn() {
392 let mut g = conn.lock().await;
393 return query.fetch_all(&mut **g).await;
394 }
395 match current_company() {
396 None => query.fetch_all(pool).await,
397 Some(company) => {
398 let mut tx = pool.begin().await?;
399 bind_company(&mut tx, company).await?;
400 let rows = query.fetch_all(&mut *tx).await?;
401 tx.commit().await?;
402 Ok(rows)
403 }
404 }
405}
406
407/// `execute` for a write/DDL query (INSERT/UPDATE/DELETE), company-scoped.
408///
409/// Writes are scoped too so the RLS `WITH CHECK` clause sees `app.company_id` and accepts the row
410/// (and rejects a forged cross-company write). A request whose company is unset cannot write to a
411/// fenced table — fail-closed on writes as well.
412pub async fn execute_scoped<'q>(
413 pool: &PgPool,
414 query: Query<'q, Postgres, PgArguments>,
415) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
416 if let Some(conn) = request_conn() {
417 let mut g = conn.lock().await;
418 return query.execute(&mut **g).await;
419 }
420 match current_company() {
421 None => query.execute(pool).await,
422 Some(company) => {
423 let mut tx = pool.begin().await?;
424 bind_company(&mut tx, company).await?;
425 let res = query.execute(&mut *tx).await?;
426 tx.commit().await?;
427 Ok(res)
428 }
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 //! Regression: the request-scope connection's `app.company_id` MUST be reset even when a clone
435 //! of the task-local `REQUEST_CONN` Arc outlives the scope (a `tokio::spawn`, a value held across
436 //! an `.await` that outlives the request future, cancellation). Before the fix, the reset was
437 //! gated on `Arc::try_unwrap` succeeding; a lingering clone made it return `Err`, the reset was
438 //! skipped SILENTLY, and the pooled connection returned dirty — leaking the previous tenant's
439 //! `company_id` to the next acquire (a non-deterministic cross-tenant leak).
440 //!
441 //! Gated on `BACKBONE_ORM_RLS_DSN` (a superuser DSN). Skips when unset.
442 use super::{request_conn, with_request_scope};
443 use sqlx::postgres::PgPoolOptions;
444 use sqlx::PgPool;
445 use uuid::Uuid;
446
447 fn dsn() -> Option<String> {
448 std::env::var("BACKBONE_ORM_RLS_DSN").ok()
449 }
450
451 async fn admin_pool(dsn: &str) -> PgPool {
452 PgPoolOptions::new().max_connections(4).connect(dsn).await.unwrap()
453 }
454
455 /// A single-connection pool as the non-super test role. max_connections=1 forces a
456 /// re-acquire after the leaked clone drops to land on the SAME connection the scope dirtied.
457 async fn app_pool(dsn: &str, role: &str) -> PgPool {
458 let after_at = dsn.rsplit('@').next().unwrap();
459 let url = format!("postgresql://{role}:rlspw@{after_at}");
460 PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap()
461 }
462
463 /// Mint the per-run role name. A fixed name breaks on shared dev clusters: `DROP ROLE` fails
464 /// when the role still holds grants in another database, so a leftover from earlier work
465 /// poisons every later run. A fresh name per run can never collide with residue.
466 fn role_name() -> String {
467 format!("rls_reset_app_{}", &Uuid::new_v4().simple().to_string()[..8])
468 }
469
470 async fn setup(admin: &PgPool, role: &str) {
471 sqlx::raw_sql(&format!(
472 "DROP SCHEMA IF EXISTS rls_reset_test CASCADE; \
473 CREATE SCHEMA rls_reset_test; \
474 CREATE ROLE {role} LOGIN PASSWORD 'rlspw'; \
475 GRANT USAGE ON SCHEMA rls_reset_test TO {role}; \
476 CREATE TABLE rls_reset_test.t (id uuid PRIMARY KEY, company_id uuid NOT NULL); \
477 GRANT SELECT, INSERT, UPDATE, DELETE ON rls_reset_test.t TO {role};",
478 ))
479 .execute(admin).await.unwrap();
480 }
481
482 /// Hold a clone of REQUEST_CONN past the scope, then verify the pooled connection comes back clean.
483 #[tokio::test]
484 async fn lingering_request_conn_clone_does_not_dirty_the_pooled_connection() {
485 let Some(dsn) = dsn() else { eprintln!("skipping: set BACKBONE_ORM_RLS_DSN"); return; };
486 let role = role_name();
487 let admin = admin_pool(&dsn).await;
488 setup(&admin, &role).await;
489 let pool = app_pool(&dsn, &role).await;
490 let company_a = Uuid::new_v4();
491
492 // Smuggle a clone of REQUEST_CONN OUT of the scope via a channel, so it outlives `f`.
493 let (tx, rx) = tokio::sync::oneshot::channel();
494
495 // Drive a request scope for company A; inside it, capture a clone of the request connection
496 // (the exact thing a `tokio::spawn` or a held-across-await would do) and hand it out.
497 with_request_scope(&pool, company_a, async {
498 if let Some(conn) = request_conn() {
499 let _ = tx.send(conn);
500 }
501 })
502 .await
503 .unwrap();
504
505 // The clone now outlives the scope. With the OLD (try_unwrap-gated) code the reset was
506 // skipped here and the connection would return to the pool dirty. Hold then drop the clone so
507 // the single pooled connection is returned, then re-acquire that SAME connection.
508 let held = rx.await.unwrap();
509 drop(held);
510
511 let mut conn = pool.acquire().await.unwrap();
512 let setting: String =
513 sqlx::query_scalar("SELECT current_setting('app.company_id', true)")
514 .fetch_one(&mut *conn)
515 .await
516 .unwrap();
517 // Before the fix this was `company_a.to_string()` (cross-tenant LEAK). It must be empty now.
518 assert_eq!(
519 setting, "",
520 "app.company_id leaked onto the pooled connection after scope exit — a lingering \
521 REQUEST_CONN clone must not bypass the session-var reset (cross-tenant leak)"
522 );
523 }
524}