From f17ee3b5438d33416111f0503bdff47e425e519f Mon Sep 17 00:00:00 2001 From: Alex Groleau Date: Tue, 1 Sep 2026 12:21:48 -0400 Subject: [PATCH] fixed invalid use of postgres auth and punc session vars --- GEMINI.md | 2 +- src/database/executors/mock.rs | 42 +++++++++++++++++++++++----------- src/database/executors/mod.rs | 8 +++---- src/database/executors/pgrx.rs | 13 +++++------ src/database/mod.rs | 11 ++++++--- src/merger/mod.rs | 4 ++-- src/validator/rules/object.rs | 2 +- 7 files changed, 51 insertions(+), 31 deletions(-) diff --git a/GEMINI.md b/GEMINI.md index d51b457..7769fc5 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -374,7 +374,7 @@ The Queryer transforms Postgres into a pre-compiled Semantic Query Engine, desig * **Multi-Table Branching**: If the Physical Table is a parent to other tables (e.g. `organization` has variations `["organization", "bot", "person"]`), the compiler generates a dynamic `CASE WHEN type = '...' THEN ...` query, expanding into sub-queries for each variation. To ensure safe resolution, the compiler dynamically evaluates correlation boundaries: it attempts standard Relational Edge discovery first. If no explicit relational edge exists (indicating pure Table Inheritance rather than a standard foreign-key graph relationship), it safely invokes a **Table Parity Fallback**. This generates an explicit ID correlation constraint (`AND inner.id = outer.id`), perfectly binding the structural variations back to the parent row to eliminate Cartesian products. * **Single-Table Bypass**: If the Physical Table is a leaf node with only one variation (e.g. `person` has variations `["person"]`), the compiler cleanly bypasses `CASE` generation and compiles a simple `SELECT` across the base table, as all schema extensions (e.g. `light.person`, `full.person`) are guaranteed to reside in the exact same physical row. * **Polymorphic Relation Type Filtering**: When a relationship maps to a polymorphic target with variations, the Queryer compiles an `IN` clause containing all allowed table variations (e.g., `counterparty_type IN ('bot', 'organization', 'person')`) rather than matching the base type literal, ensuring all polymorphic types are loaded correctly. -* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `auth.organization_ids`, `auth.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc. +* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `punc.cue.organization_ids`, `punc.cue.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc. * **Static Relation Constraints (Kind Constraints)**: When a relationship (such as a nested object or array) is defined with a schema that constrains a field value statically using a `const` or `enum` keyword (for example, `kind` constrained to `"cover"` in a `cover_attachment`), the Queryer automatically extracts these static assertions during AST compilation. It injects them directly as static filters into the SQL subquery's `WHERE` clause (e.g. `AND attachment.kind = 'cover'`), allowing developers to query pre-filtered subsets of related tables natively through the schema. * **Proxy Schema Dereferencing / Resolution**: To support punc endpoints that return non-polymorphic table-backed shapes (using `type: "full.X"` proxy schemas at the root response level), the Queryer compiler automatically dereferences non-table schema pointers to their target schemas prior to checking the types. This allows the Queryer to correctly resolve the table relationship edges pre-compiled on the full schema, while avoiding polluting the database registry with relations on ad-hoc punc response schemas during setup. diff --git a/src/database/executors/mock.rs b/src/database/executors/mock.rs index 207ae80..703ff42 100644 --- a/src/database/executors/mock.rs +++ b/src/database/executors/mock.rs @@ -13,7 +13,8 @@ pub struct MockState { pub query_responses: Vec>, pub execute_responses: Vec>, pub mocks: Vec, - pub punc_external: bool, + pub cue_created_by: Option, + pub cue_external: bool, } #[cfg(test)] @@ -24,12 +25,12 @@ impl MockState { query_responses: Default::default(), execute_responses: Default::default(), mocks: Default::default(), - punc_external: false, + cue_created_by: Some("00000000-0000-0000-0000-000000000000".to_string()), + cue_external: false, } } } - #[cfg(test)] thread_local! { pub static MOCK_STATE: RefCell = RefCell::new(MockState::new()); @@ -80,16 +81,22 @@ impl DatabaseExecutor for MockExecutor { }) } - fn auth_user_id(&self) -> Result { - Ok("00000000-0000-0000-0000-000000000000".to_string()) + fn cue_created_by(&self) -> Result { + MOCK_STATE.with(|state| { + state + .borrow() + .cue_created_by + .clone() + .ok_or_else(|| "Missing cue.created_by in session context".to_string()) + }) } fn timestamp(&self) -> Result { Ok("2026-03-10T00:00:00Z".to_string()) } - fn punc_external(&self) -> Result { - Ok(MOCK_STATE.with(|state| state.borrow().punc_external)) + fn cue_external(&self) -> Result { + Ok(MOCK_STATE.with(|state| state.borrow().cue_external)) } #[cfg(test)] @@ -112,21 +119,27 @@ impl DatabaseExecutor for MockExecutor { s.query_responses.clear(); s.execute_responses.clear(); s.mocks.clear(); - s.punc_external = false; + s.cue_created_by = Some("00000000-0000-0000-0000-00000000000".to_string()); + s.cue_external = false; }); } } #[cfg(test)] impl MockExecutor { - pub fn set_punc_external(&self, external: bool) { + pub fn set_cue_external(&self, external: bool) { MOCK_STATE.with(|state| { - state.borrow_mut().punc_external = external; + state.borrow_mut().cue_external = external; + }); + } + + pub fn set_cue_created_by(&self, created_by: Option) { + MOCK_STATE.with(|state| { + state.borrow_mut().cue_created_by = created_by; }); } } - #[cfg(test)] fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option> { let sql_upper = sql.to_uppercase(); @@ -155,7 +168,8 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option> { let q_upper = query.to_uppercase(); // Check if mock type matches the table or any joined tables in this query - let table_regex = Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?; + let table_regex = + Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?; let tables: Vec = table_regex .captures_iter(query) .filter_map(|c| c.get(1).map(|m| m.as_str().to_string())) @@ -174,7 +188,9 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option> { where_end = limit_idx; } } - where_clause = query[where_idx + 7..where_end].trim_end_matches(')').to_string(); + where_clause = query[where_idx + 7..where_end] + .trim_end_matches(')') + .to_string(); } if where_clause.is_empty() { diff --git a/src/database/executors/mod.rs b/src/database/executors/mod.rs index e7f9b88..79ea1d1 100644 --- a/src/database/executors/mod.rs +++ b/src/database/executors/mod.rs @@ -14,14 +14,14 @@ pub trait DatabaseExecutor: Send + Sync { /// Executes an operation (INSERT, UPDATE, DELETE, or pg_notify) that does not return rows. fn execute(&self, sql: &str, args: Option>) -> Result<(), String>; - /// Returns the current authenticated user's ID - fn auth_user_id(&self) -> Result; + /// Returns the current authenticated user's ID (from cue.created_by) + fn cue_created_by(&self) -> Result; /// Returns the current transaction timestamp fn timestamp(&self) -> Result; - /// Returns true if the current execution context is marked as an external client API cue (punc.external = true) - fn punc_external(&self) -> Result; + /// Returns true if the current execution context is marked as an external client API cue (cue.external = true) + fn cue_external(&self) -> Result; #[cfg(test)] fn get_queries(&self) -> Vec; diff --git a/src/database/executors/pgrx.rs b/src/database/executors/pgrx.rs index 9041de7..808ca99 100644 --- a/src/database/executors/pgrx.rs +++ b/src/database/executors/pgrx.rs @@ -113,12 +113,12 @@ impl DatabaseExecutor for SpiExecutor { }) } - fn auth_user_id(&self) -> Result { + fn cue_created_by(&self) -> Result { self.transact(|| { Spi::connect(|client| { let mut tup_table = client .select( - "SELECT COALESCE(current_setting('auth.user_id', true), 'ffffffff-ffff-ffff-ffff-ffffffffffff')", + "SELECT NULLIF(current_setting('punc.cue', true), '')::jsonb->>'created_by'", None, &[], ) @@ -126,10 +126,10 @@ impl DatabaseExecutor for SpiExecutor { let row = tup_table .next() - .ok_or("No user id setting returned from context".to_string())?; + .ok_or("No cue setting returned from context".to_string())?; let user_id: Option = row.get(1).map_err(|e| e.to_string())?; - user_id.ok_or("Missing user_id".to_string()) + user_id.ok_or("Missing cue.created_by in session context".to_string()) }) }) } @@ -151,12 +151,12 @@ impl DatabaseExecutor for SpiExecutor { }) } - fn punc_external(&self) -> Result { + fn cue_external(&self) -> Result { self.transact(|| { Spi::connect(|client| { let mut tup_table = client .select( - "SELECT COALESCE(current_setting('punc.external', true), 'false')::boolean", + "SELECT COALESCE((NULLIF(current_setting('punc.cue', true), '')::jsonb->>'external')::boolean, false)", None, &[], ) @@ -172,4 +172,3 @@ impl DatabaseExecutor for SpiExecutor { }) } } - diff --git a/src/database/mod.rs b/src/database/mod.rs index 5b724ab..afa6eb8 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -232,9 +232,9 @@ impl Database { self.executor.execute(sql, args) } - /// Returns the current authenticated user's ID - pub fn auth_user_id(&self) -> Result { - self.executor.auth_user_id() + /// Returns the current authenticated user's ID (from cue.created_by) + pub fn cue_created_by(&self) -> Result { + self.executor.cue_created_by() } /// Returns the current transaction timestamp @@ -242,6 +242,11 @@ impl Database { self.executor.timestamp() } + /// Returns true if the current execution context is marked as an external client API cue (cue.external = true) + pub fn cue_external(&self) -> Result { + self.executor.cue_external() + } + pub fn compile(&mut self, errors: &mut Vec) { // Phase 1: Registration self.collect_schemas(errors); diff --git a/src/merger/mod.rs b/src/merger/mod.rs index a9d9f7e..9ecac1e 100644 --- a/src/merger/mod.rs +++ b/src/merger/mod.rs @@ -351,8 +351,8 @@ impl Merger { current_org_id = parent_org_id.clone(); } - let user_id = self.db.auth_user_id().map_err(|e| Error { - code: "AUTH_USER_FAILED".to_string(), + let user_id = self.db.cue_created_by().map_err(|e| Error { + code: "CUE_CREATED_BY_FAILED".to_string(), values: Some(IndexMap::from([("error".to_string(), e.clone())])), details: ErrorDetails { cause: Some(e), diff --git a/src/validator/rules/object.rs b/src/validator/rules/object.rs index cd056e6..7ad805e 100644 --- a/src/validator/rules/object.rs +++ b/src/validator/rules/object.rs @@ -180,7 +180,7 @@ impl<'a> ValidationContext<'a> { } if !self.response { - let is_external = self.db.executor.punc_external().unwrap_or(false); + let is_external = self.db.cue_external().unwrap_or(false); if let Some(compiled_props) = self.schema.compiled_properties.get() { for (key, sub_schema) in compiled_props { if sub_schema.is_immutable(is_external) && obj.contains_key(key) {