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`.
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.
175async fn bind_company(conn: &mut sqlx::PgConnection, company: Uuid) -> Result<(), sqlx::Error> {
176 sqlx::query("SELECT set_config('app.company_id', $1, true)")
177 .bind(company.to_string())
178 .execute(conn)
179 .await?;
180 Ok(())
181}
182
183/// Bind an EXPLICIT company onto an already-open transaction/connection.
184///
185/// For call sites that know their company directly (it is on the DTO, or was just read off the row)
186/// and open their own transaction — the common shape in hand-written write services. Prefer this over
187/// [`bind_current_company`] when the company is known: it does not depend on an ambient task-local, so
188/// it is correct for non-request callers (event subscribers, jobs) too.
189pub async fn bind_company_on(
190 conn: &mut sqlx::PgConnection,
191 company: Uuid,
192) -> Result<(), sqlx::Error> {
193 bind_company(conn, company).await
194}
195
196/// Bind the current task's company onto an already-open transaction/connection.
197///
198/// For call sites that manage their own transaction (batch operations run all-or-nothing inside one
199/// `pool.begin()`): call this immediately after `begin()` so every statement in the transaction is
200/// company-scoped. A no-op when no company is in scope (fail-closed at the DB for fenced tables).
201pub async fn bind_current_company(conn: &mut sqlx::PgConnection) -> Result<(), sqlx::Error> {
202 if let Some(company) = current_company() {
203 bind_company(conn, company).await?;
204 }
205 Ok(())
206}
207
208// ─── Scoped execute helpers ────────────────────────────────────────────────────
209//
210// Each wraps a fully-bound query. When a company is in scope, the query runs inside a transaction
211// that first sets `app.company_id`; otherwise it runs directly against the pool (fail-closed at the
212// DB for fenced tables). The extra BEGIN/COMMIT per statement is the cost of connection-per-statement
213// pooling; a request-scoped held connection could remove it later (ADR-0008 follow-up).
214
215/// `fetch_all` for a typed row query, company-scoped.
216pub async fn fetch_all_scoped<'q, T>(
217 pool: &PgPool,
218 query: QueryAs<'q, Postgres, T, PgArguments>,
219) -> Result<Vec<T>, sqlx::Error>
220where
221 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
222{
223 if let Some(conn) = request_conn() {
224 let mut g = conn.lock().await;
225 return query.fetch_all(&mut **g).await;
226 }
227 match current_company() {
228 None => query.fetch_all(pool).await,
229 Some(company) => {
230 let mut tx = pool.begin().await?;
231 bind_company(&mut tx, company).await?;
232 let rows = query.fetch_all(&mut *tx).await?;
233 tx.commit().await?;
234 Ok(rows)
235 }
236 }
237}
238
239/// `fetch_one` for a typed row query, company-scoped.
240pub async fn fetch_one_scoped<'q, T>(
241 pool: &PgPool,
242 query: QueryAs<'q, Postgres, T, PgArguments>,
243) -> Result<T, sqlx::Error>
244where
245 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
246{
247 if let Some(conn) = request_conn() {
248 let mut g = conn.lock().await;
249 return query.fetch_one(&mut **g).await;
250 }
251 match current_company() {
252 None => query.fetch_one(pool).await,
253 Some(company) => {
254 let mut tx = pool.begin().await?;
255 bind_company(&mut tx, company).await?;
256 let row = query.fetch_one(&mut *tx).await?;
257 tx.commit().await?;
258 Ok(row)
259 }
260 }
261}
262
263/// `fetch_optional` for a typed row query, company-scoped.
264pub async fn fetch_optional_scoped<'q, T>(
265 pool: &PgPool,
266 query: QueryAs<'q, Postgres, T, PgArguments>,
267) -> Result<Option<T>, sqlx::Error>
268where
269 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
270{
271 if let Some(conn) = request_conn() {
272 let mut g = conn.lock().await;
273 return query.fetch_optional(&mut **g).await;
274 }
275 match current_company() {
276 None => query.fetch_optional(pool).await,
277 Some(company) => {
278 let mut tx = pool.begin().await?;
279 bind_company(&mut tx, company).await?;
280 let row = query.fetch_optional(&mut *tx).await?;
281 tx.commit().await?;
282 Ok(row)
283 }
284 }
285}
286
287/// `fetch_one` for a scalar query (e.g. `COUNT(*)`), company-scoped.
288pub async fn fetch_one_scalar_scoped<'q, S>(
289 pool: &PgPool,
290 query: QueryScalar<'q, Postgres, S, PgArguments>,
291) -> Result<S, sqlx::Error>
292where
293 S: Send + Unpin,
294 (S,): for<'r> FromRow<'r, PgRow>,
295{
296 if let Some(conn) = request_conn() {
297 let mut g = conn.lock().await;
298 return query.fetch_one(&mut **g).await;
299 }
300 match current_company() {
301 None => query.fetch_one(pool).await,
302 Some(company) => {
303 let mut tx = pool.begin().await?;
304 bind_company(&mut tx, company).await?;
305 let val = query.fetch_one(&mut *tx).await?;
306 tx.commit().await?;
307 Ok(val)
308 }
309 }
310}
311
312/// `fetch_optional` for a scalar query (e.g. `SELECT 1 … LIMIT 1`), company-scoped.
313pub async fn fetch_optional_scalar_scoped<'q, S>(
314 pool: &PgPool,
315 query: QueryScalar<'q, Postgres, S, PgArguments>,
316) -> Result<Option<S>, sqlx::Error>
317where
318 S: Send + Unpin,
319 (S,): for<'r> FromRow<'r, PgRow>,
320{
321 if let Some(conn) = request_conn() {
322 let mut g = conn.lock().await;
323 return query.fetch_optional(&mut **g).await;
324 }
325 match current_company() {
326 None => query.fetch_optional(pool).await,
327 Some(company) => {
328 let mut tx = pool.begin().await?;
329 bind_company(&mut tx, company).await?;
330 let val = query.fetch_optional(&mut *tx).await?;
331 tx.commit().await?;
332 Ok(val)
333 }
334 }
335}
336
337/// `fetch_optional` for an untyped row query (`sqlx::query(..)` → `PgRow`), company-scoped.
338///
339/// Hand-written services commonly read ad-hoc column sets as raw rows rather than a typed struct;
340/// these mirror the typed helpers so such a service can be scoped without restructuring its queries.
341pub async fn fetch_optional_row_scoped<'q>(
342 pool: &PgPool,
343 query: Query<'q, Postgres, PgArguments>,
344) -> Result<Option<PgRow>, sqlx::Error> {
345 if let Some(conn) = request_conn() {
346 let mut g = conn.lock().await;
347 return query.fetch_optional(&mut **g).await;
348 }
349 match current_company() {
350 None => query.fetch_optional(pool).await,
351 Some(company) => {
352 let mut tx = pool.begin().await?;
353 bind_company(&mut tx, company).await?;
354 let row = query.fetch_optional(&mut *tx).await?;
355 tx.commit().await?;
356 Ok(row)
357 }
358 }
359}
360
361/// `fetch_one` for an untyped row query (`sqlx::query(..)` → `PgRow`), company-scoped.
362pub async fn fetch_one_row_scoped<'q>(
363 pool: &PgPool,
364 query: Query<'q, Postgres, PgArguments>,
365) -> Result<PgRow, sqlx::Error> {
366 if let Some(conn) = request_conn() {
367 let mut g = conn.lock().await;
368 return query.fetch_one(&mut **g).await;
369 }
370 match current_company() {
371 None => query.fetch_one(pool).await,
372 Some(company) => {
373 let mut tx = pool.begin().await?;
374 bind_company(&mut tx, company).await?;
375 let row = query.fetch_one(&mut *tx).await?;
376 tx.commit().await?;
377 Ok(row)
378 }
379 }
380}
381
382/// `fetch_all` for an untyped row query (`sqlx::query(..)` → `Vec<PgRow>`), company-scoped.
383pub async fn fetch_all_rows_scoped<'q>(
384 pool: &PgPool,
385 query: Query<'q, Postgres, PgArguments>,
386) -> Result<Vec<PgRow>, sqlx::Error> {
387 if let Some(conn) = request_conn() {
388 let mut g = conn.lock().await;
389 return query.fetch_all(&mut **g).await;
390 }
391 match current_company() {
392 None => query.fetch_all(pool).await,
393 Some(company) => {
394 let mut tx = pool.begin().await?;
395 bind_company(&mut tx, company).await?;
396 let rows = query.fetch_all(&mut *tx).await?;
397 tx.commit().await?;
398 Ok(rows)
399 }
400 }
401}
402
403/// `execute` for a write/DDL query (INSERT/UPDATE/DELETE), company-scoped.
404///
405/// Writes are scoped too so the RLS `WITH CHECK` clause sees `app.company_id` and accepts the row
406/// (and rejects a forged cross-company write). A request whose company is unset cannot write to a
407/// fenced table — fail-closed on writes as well.
408pub async fn execute_scoped<'q>(
409 pool: &PgPool,
410 query: Query<'q, Postgres, PgArguments>,
411) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
412 if let Some(conn) = request_conn() {
413 let mut g = conn.lock().await;
414 return query.execute(&mut **g).await;
415 }
416 match current_company() {
417 None => query.execute(pool).await,
418 Some(company) => {
419 let mut tx = pool.begin().await?;
420 bind_company(&mut tx, company).await?;
421 let res = query.execute(&mut *tx).await?;
422 tx.commit().await?;
423 Ok(res)
424 }
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 //! Regression: the request-scope connection's `app.company_id` MUST be reset even when a clone
431 //! of the task-local `REQUEST_CONN` Arc outlives the scope (a `tokio::spawn`, a value held across
432 //! an `.await` that outlives the request future, cancellation). Before the fix, the reset was
433 //! gated on `Arc::try_unwrap` succeeding; a lingering clone made it return `Err`, the reset was
434 //! skipped SILENTLY, and the pooled connection returned dirty — leaking the previous tenant's
435 //! `company_id` to the next acquire (a non-deterministic cross-tenant leak).
436 //!
437 //! Gated on `BACKBONE_ORM_RLS_DSN` (a superuser DSN). Skips when unset.
438 use super::{request_conn, with_request_scope};
439 use sqlx::postgres::PgPoolOptions;
440 use sqlx::PgPool;
441 use uuid::Uuid;
442
443 fn dsn() -> Option<String> {
444 std::env::var("BACKBONE_ORM_RLS_DSN").ok()
445 }
446
447 async fn admin_pool(dsn: &str) -> PgPool {
448 PgPoolOptions::new().max_connections(4).connect(dsn).await.unwrap()
449 }
450
451 /// A single-connection pool as the non-super test role. max_connections=1 forces a
452 /// re-acquire after the leaked clone drops to land on the SAME connection the scope dirtied.
453 async fn app_pool(dsn: &str, role: &str) -> PgPool {
454 let after_at = dsn.rsplit('@').next().unwrap();
455 let url = format!("postgresql://{role}:rlspw@{after_at}");
456 PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap()
457 }
458
459 /// Mint the per-run role name. A fixed name breaks on shared dev clusters: `DROP ROLE` fails
460 /// when the role still holds grants in another database, so a leftover from earlier work
461 /// poisons every later run. A fresh name per run can never collide with residue.
462 fn role_name() -> String {
463 format!("rls_reset_app_{}", &Uuid::new_v4().simple().to_string()[..8])
464 }
465
466 async fn setup(admin: &PgPool, role: &str) {
467 sqlx::raw_sql(&format!(
468 "DROP SCHEMA IF EXISTS rls_reset_test CASCADE; \
469 CREATE SCHEMA rls_reset_test; \
470 CREATE ROLE {role} LOGIN PASSWORD 'rlspw'; \
471 GRANT USAGE ON SCHEMA rls_reset_test TO {role}; \
472 CREATE TABLE rls_reset_test.t (id uuid PRIMARY KEY, company_id uuid NOT NULL); \
473 GRANT SELECT, INSERT, UPDATE, DELETE ON rls_reset_test.t TO {role};",
474 ))
475 .execute(admin).await.unwrap();
476 }
477
478 /// Hold a clone of REQUEST_CONN past the scope, then verify the pooled connection comes back clean.
479 #[tokio::test]
480 async fn lingering_request_conn_clone_does_not_dirty_the_pooled_connection() {
481 let Some(dsn) = dsn() else { eprintln!("skipping: set BACKBONE_ORM_RLS_DSN"); return; };
482 let role = role_name();
483 let admin = admin_pool(&dsn).await;
484 setup(&admin, &role).await;
485 let pool = app_pool(&dsn, &role).await;
486 let company_a = Uuid::new_v4();
487
488 // Smuggle a clone of REQUEST_CONN OUT of the scope via a channel, so it outlives `f`.
489 let (tx, rx) = tokio::sync::oneshot::channel();
490
491 // Drive a request scope for company A; inside it, capture a clone of the request connection
492 // (the exact thing a `tokio::spawn` or a held-across-await would do) and hand it out.
493 with_request_scope(&pool, company_a, async {
494 if let Some(conn) = request_conn() {
495 let _ = tx.send(conn);
496 }
497 })
498 .await
499 .unwrap();
500
501 // The clone now outlives the scope. With the OLD (try_unwrap-gated) code the reset was
502 // skipped here and the connection would return to the pool dirty. Hold then drop the clone so
503 // the single pooled connection is returned, then re-acquire that SAME connection.
504 let held = rx.await.unwrap();
505 drop(held);
506
507 let mut conn = pool.acquire().await.unwrap();
508 let setting: String =
509 sqlx::query_scalar("SELECT current_setting('app.company_id', true)")
510 .fetch_one(&mut *conn)
511 .await
512 .unwrap();
513 // Before the fix this was `company_a.to_string()` (cross-tenant LEAK). It must be empty now.
514 assert_eq!(
515 setting, "",
516 "app.company_id leaked onto the pooled connection after scope exit — a lingering \
517 REQUEST_CONN clone must not bypass the session-var reset (cross-tenant leak)"
518 );
519 }
520}