Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(security): scope user and audit-log access to the caller's company (#1725)
Brad Barbin193a2228b2e8
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 091e3af587..205162a1e3 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -518,6 +518,20 @@ Format: `Context → Problem → Rule → Applies to`**Applies to:** any new SECURITY DEFINER function that calls pg_net/`net.http_post` or is meant to be trigger/cron-only (`packages/database/supabase/migrations/`). Trigger functions returning `trigger` are not RPC-exposed (safe in public), but VOID/scalar helpers are.+**Update (2026-09-24):** pg_net is not required. On `supabase/postgres:15.14.1.112`, a plain+`LANGUAGE sql` function (`select 1`) with `REVOKE EXECUTE … FROM PUBLIC, anon, authenticated`+segfaults the backend (signal 11) when called under `SET ROLE authenticated` or `anon`. This was+reproduced in a fresh container of that image. A missing table privilege, a `RAISE`, and "must be owner"+are all ordinary errors. So `REVOKE EXECUTE` on any function in `public` is itself an unauthenticated DoS+(`POST /rest/v1/rpc/<fn>`). Gate API access INSIDE the function instead, and raise on+`current_setting('role', true) IN ('anon','authenticated')` without the permission — see+`assert_audit_log_access` in `20260924171942_audit-log-company-scope.sql`. When you test a revoke, use a+throwaway container (`docker run --rm supabase/postgres:<tag>`), never a shared dev database. The crash+restarts every backend. `20260924192316_api-function-guards-not-revokes.sql` replaced the six existing public-function+revokes (integration secrets, `upsert_company_integration_patch`, the job-completion helpers). A nested+helper of a SECURITY DEFINER function cannot use the role-GUC guard, because `current_setting('role')`+still reads `authenticated` inside the nested call. Make those `SECURITY INVOKER` instead.+## The local Inngest dev server (v1.19.4) can't handle `debounce` — it errors on every debounce item**Context:** The push-based event-queue drainer (`packages/jobs/src/inngest/functions/events/queue.ts`) was configured with `debounce: { period: "2s", timeout: "10s" }` to coalesce bursts of `carbon/event-queue.process` wake events into one run.@@ -2234,3 +2248,26 @@ categories, e.g. Polish/Russian `few`/`many`, get the extra branches).**Applies to:** any `apps/{erp,mes}/app` or `packages/{react,form}/src` stringwith a count-dependent word; grep `? "` inside `` t` `` templates when reviewingi18n.++---++**Context:** A security report: any signed-in user could read, create, update and delete every+`public."user"` row through PostgREST. The policy was `FOR ALL USING+(has_any_company_permission('users_update'))`, and a self-serve signup holds `users_update` in+its own company.++**Problem:** `has_any_company_permission(claim)` answers "does the caller hold this permission+ANYWHERE?" It never relates the row to a company, so any policy built on it alone is+cross-tenant. A table with no `companyId` (`user`) cannot use the standard four-policy template,+so the shortcut looked reasonable.++**Rule:** Never gate a policy on `has_any_company_permission`. Every policy must connect the ROW+to a company in `get_companies_with_employee_role()` or+`get_companies_with_employee_permission(...)`. For tables without `companyId`, go through a+membership table (`userToCompany`, `employee`, …), as `20260924153817` does. When a global+row is shared by several tenants, also pin the columns no single tenant owns (a BEFORE UPDATE+guard on `current_user IN ('anon','authenticated')`), and revoke INSERT/DELETE from the API+roles when only the server writes them. Also check `pg_policies` for `qual = 'true'`.++**Applies to:** `packages/database/supabase/migrations/**` RLS on global tables (`user`,+`userPermission`, `group`), and any review of an RLS helper.diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.mdindex 441ec3a921..2bf78a76ca 100644--- a/.claude/rules/audit-log-system.md+++ b/.claude/rules/audit-log-system.md@@ -47,6 +47,30 @@ forked to attach the trigger to every new (and pre-existing) table via the idemp`attach_audit_log_append_only(table)`. The DELETE branch of `prevent_audit_log_mutation` is what the`audit-archive` job relies on: it runs `delete_old_audit_logs`, so its per-day deletes carry the flag.+## Access (migration `20260924171942_audit-log-company-scope.sql`)++Each `auditLog_{companyId}` table has ONE policy, `"SELECT"`, true only for callers holding+`settings_view` in that company. INSERT/UPDATE/DELETE/TRUNCATE are revoked from `anon`/`authenticated`.+`secure_audit_log_table(companyId)` applies both, and `create_audit_log_table` calls it on every table it+creates or touches, because the default privileges on `public` re-grant ALL to the API roles on each new+table. (Before this, the policy was `audit_log_access` FOR ALL USING (true), and any holder of the anon+key could read or append to any company's log.)++The RPCs are all SECURITY DEFINER, so each one begins with+`assert_audit_log_access(p_company_id, <permission>)`:++| Permission | Functions |+|---|---|+| `settings_view` | `get_entity_audit_log`, `get_audit_log`, `get_audit_log_count` |+| `settings_update` | `create_audit_log_table` |+| `NULL` (service role only) | `insert_audit_log_batch`, `get_audit_logs_for_archive`, `delete_old_audit_logs`, `drop_audit_log_table` |++The guard only applies when `current_setting('role')` is `anon` or `authenticated`, so the service role+and direct Postgres connections pass. **Never swap it for `REVOKE EXECUTE`**: on supabase/postgres+15.14.1.112, calling any function the caller lacks EXECUTE on, as `anon`/`authenticated`, segfaults the+backend (see `.ai/lessons.md`). The controlled-environment auto-enable in the `settings+/audit-logs.tsx`+loader therefore runs as the service role, because that loader only requires `settings_view`.+## On-by-default in controlled environments (3.3.1)Audit is opt-in per company (`company.auditLogEnabled`), **except** under `CONTROLLED_ENVIRONMENT`@@ -147,4 +171,5 @@ than from config.`20260217120000_audit_log_add_table_name.sql`, `20260218000000_expand_audit_log_entities.sql`,`20260418000000_audit_log_add_record_id.sql`, `20260427120000_audit-event-timestamp.sql`,`20260513130000_audit-item-shelf-life-history.sql`,-`20260713095136_attach-inventory-count-audit-triggers.sql` (attaches triggers on `inventoryCount`/`inventoryCountLine`).+`20260713095136_attach-inventory-count-audit-triggers.sql` (attaches triggers on `inventoryCount`/`inventoryCountLine`),+`20260818014100_audit-log-append-only.sql`, `20260924171942_audit-log-company-scope.sql` (access guards).diff --git a/.claude/rules/database-migration-patterns.md b/.claude/rules/database-migration-patterns.mdindex 6d7ed87e5f..77ba927538 100644--- a/.claude/rules/database-migration-patterns.md+++ b/.claude/rules/database-migration-patterns.md@@ -141,6 +141,29 @@ add a trigger only when there's real derived state to maintain. For async/event-effects use the event system (see `event-system.md`), not ad-hoc triggers.<!-- UNVERIFIED: no GRANT statements appear in recent migrations; per-table grants are not a current convention -->+## Restricting a function: guard inside, never `REVOKE EXECUTE`++Every function in `public` is a PostgREST RPC. On supabase/postgres 15.14.1.112, calling a function+the caller lacks EXECUTE on, as `anon`/`authenticated`, **segfaults the backend** and restarts every+connection. So a `REVOKE EXECUTE … FROM anon, authenticated` turns "not allowed" into an+unauthenticated one-request DoS. (A missing TABLE privilege is an ordinary error; table REVOKEs are fine.)++- **Service-role-only function called directly by a service client** — first statement of the body:+ `IF current_setting('role', true) IN ('anon','authenticated') THEN RAISE EXCEPTION … USING ERRCODE = 'insufficient_privilege'; END IF;`+ PostgREST's `SET ROLE` stays visible inside SECURITY DEFINER, and service role / direct connections+ (`none`) pass. Examples: `get_integration_secret`, `assert_audit_log_access(company, NULL)`.+- **Tenant-scoped function** — raise unless `p_company_id = ANY(get_companies_with_employee_permission(…))`+ (`assert_audit_log_access`).+- **Internal helper of a SECURITY DEFINER function** — the role GUC still says `authenticated` inside+ the nested call, so the guard above would refuse legitimate callers. Make the helper+ `SECURITY INVOKER`: from its SECURITY DEFINER caller it runs as the owner, and from the API it runs+ under the caller's RLS (`terminal_job_operations`, `complete_job_remaining_quantities`). Or put it in+ `util` (no API `USAGE`) — see `event-system.md`.++Migration `20260924192316_api-function-guards-not-revokes.sql` converted the six functions that used+REVOKE. Test a new guard in a throwaway container (`docker run --rm supabase/postgres:<tag>`), never a+shared database.+## Enums```sqldiff --git a/.claude/rules/user-employee-job-relationships.md b/.claude/rules/user-employee-job-relationships.mdindex b9cdc41b62..2c4e33815b 100644--- a/.claude/rules/user-employee-job-relationships.md+++ b/.claude/rules/user-employee-job-relationships.md@@ -74,6 +74,16 @@ is the separate `job` table from `20240909194622_jobs.sql`).## Gotchas+- **`user` RLS is company-scoped** (`20260924153817_user-rls-company-scope.sql`). A caller+ sees themselves, users who share a `userToCompany` company, and, as an employee,+ users with an `employee` / `customerAccount` / `supplierAccount` row in their company+ (pending invites, deactivated people). Another user's row is writable only with+ `users_update` in a company where that user has an active `userToCompany` row. INSERT+ and DELETE are revoked from `anon`/`authenticated`, so they go through the service role.+ A BEFORE UPDATE trigger (`guard_user_identity_columns`) rejects any API-role change to+ `id`, `email`, `active`, `admin`, `developer` or `isConsoleOperator`. Sending those+ columns unchanged is fine. Deleting a user also deletes its identity `group`+ (`sync_delete_user_identity_group`).- `employee` and `employeeJob` share composite PK `(id, companyId)` and `id → user.id` — always scopequeries by **both** id and companyId. A user has one employee/employeeJob row **per company**.- `userToCompany.role` (membership type) is distinct from `employeeType` (which permission set);diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.tsxindex c8f59ab5e6..faef89f88a 100644--- a/apps/erp/app/routes/x+/settings+/audit-logs.tsx+++ b/apps/erp/app/routes/x+/settings+/audit-logs.tsx@@ -40,12 +40,16 @@ export async function loader({ request }: LoaderFunctionArgs) {// Table might not exist yet, that's ok}+ const serviceRole = getCarbonServiceRole();+// Controlled environments (ITAR/CUI, NIST 800-171 3.3.1): audit logging is on// by default and cannot be turned off. Enable it on demand for any controlled- // company that isn't already capturing.+ // company that isn't already capturing. This is mandatory, not the viewer's+ // choice, so it runs as the service role: create_audit_log_table requires+ // settings_update, and this loader only requires settings_view.if (CONTROLLED_ENVIRONMENT && !enabled) {try {- await enableAuditLog(client, companyId);+ await enableAuditLog(serviceRole, companyId);enabled = true;} catch {// Best-effort; the write path degrades gracefully if it can't enable here.@@ -65,7 +69,6 @@ export async function loader({ request }: LoaderFunctionArgs) {let archives: Awaited<ReturnType<typeof getAuditLogArchives>> = [];if (enabled) {try {- const serviceRole = getCarbonServiceRole();archives = await getAuditLogArchives(serviceRole, companyId);} catch {// Archives table might not existdiff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex d813257dc8..10fbbbbc42 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -96428,6 +96428,51 @@ export default {tags: ["(rpc) set_shelf_life_on_operation_done"]}},+ "/rpc/sync_delete_user_identity_group": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_new: {+ format: "jsonb"+ },+ p_old: {+ format: "jsonb"+ },+ p_operation: {+ format: "text",+ type: "string"+ },+ p_table: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_table", "p_operation", "p_new", "p_old"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) sync_delete_user_identity_group"]+ }+ },"/rpc/update_receipt_line_serial_tracking": {post: {parameters: [@@ -96711,6 +96756,49 @@ export default {tags: ["(rpc) getIntercompanyBalance"]}},+ "/rpc/complete_job_remaining_quantities": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_job_id: {+ format: "text",+ type: "string"+ },+ p_quantity_complete: {+ format: "numeric",+ type: "number"+ },+ p_user_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_job_id", "p_quantity_complete", "p_user_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) complete_job_remaining_quantities"]+ }+ },"/rpc/get_production_projections": {post: {parameters: [@@ -97164,6 +97252,73 @@ export default {tags: ["(rpc) get_direct_descendants_of_tracked_entities_strict"]}},+ "/rpc/upsert_company_integration_patch": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_active: {+ format: "boolean",+ type: "boolean"+ },+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_integration_id: {+ format: "text",+ type: "string"+ },+ p_metadata_patch: {+ format: "jsonb"+ },+ p_metadata_remove: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ p_secret_patch: {+ format: "jsonb"+ },+ p_secret_remove: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ p_updated_by: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_integration_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) upsert_company_integration_patch"]+ }+ },"/rpc/get_quote_methods": {get: {parameters: [@@ -98215,6 +98370,63 @@ export default {tags: ["(rpc) get_part_details"]}},+ "/rpc/terminal_job_operations": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_job_id",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) terminal_job_operations"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_job_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_job_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) terminal_job_operations"]+ }+ },"/rpc/sync_check_method_material_self_reference": {post: {parameters: [@@ -99364,6 +99576,74 @@ export default {tags: ["(rpc) set_shelf_life_on_operation_started"]}},+ "/rpc/assert_audit_log_access": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "p_permission",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) assert_audit_log_access"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_permission: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_permission"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) assert_audit_log_access"]+ }+ },"/rpc/groups_for_user": {post: {parameters: [@@ -99716,6 +99996,41 @@ export default {tags: ["(rpc) increment_notification_delivery"]}},+ "/rpc/secure_audit_log_table": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) secure_audit_log_table"]+ }+ },"/rpc/backflush_job_materials": {post: {parameters: [@@ -101719,6 +102034,45 @@ export default {tags: ["(rpc) get_picking_list_availability"]}},+ "/rpc/get_integration_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_integration_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_integration_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_integration_secret"]+ }+ },"/rpc/journalLinesByAccountNumber": {post: {parameters: [@@ -102811,6 +103165,48 @@ export default {tags: ["(rpc) get_picking_list_tracked_available"]}},+ "/rpc/upsert_integration_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_integration_id: {+ format: "text",+ type: "string"+ },+ p_secret: {+ format: "jsonb"+ }+ },+ required: ["p_company_id", "p_integration_id", "p_secret"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) upsert_integration_secret"]+ }+ },"/rpc/get_training_assignment_summary": {post: {parameters: [@@ -104706,74 +105102,6 @@ export default {tags: ["(rpc) sync_update_stock_transfer_status"]}},- "/rpc/insert_audit_log": {- post: {- parameters: [- {- in: "body",- name: "args",- required: true,- schema: {- properties: {- p_actor_id: {- format: "text",- type: "string"- },- p_actor_name: {- format: "text",- type: "string"- },- p_company_id: {- format: "text",- type: "string"- },- p_diff: {- format: "jsonb"- },- p_entity_id: {- format: "text",- type: "string"- },- p_entity_type: {- format: "text",- type: "string"- },- p_metadata: {- format: "jsonb"- },- p_operation: {- format: "text",- type: "string"- }- },- required: [- "p_company_id",- "p_entity_type",- "p_entity_id",- "p_operation",- "p_actor_id",- "p_actor_name"- ],- type: "object"- }- },- {- $ref: "#/parameters/preferParams"- }- ],- produces: [- "application/json",- "application/vnd.pgrst.object+json;nulls=stripped",- "application/vnd.pgrst.object+json"- ],- responses: {- "200": {- description: "OK"- }- },- tags: ["(rpc) insert_audit_log"]- }- },"/rpc/get_purchasing_planning": {post: {parameters: [@@ -105330,6 +105658,45 @@ export default {tags: ["(rpc) get_opportunity_with_related_records"]}},+ "/rpc/delete_integration_secret": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_integration_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_integration_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) delete_integration_secret"]+ }+ },"/rpc/journalDimensionPivot": {post: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 4fe2e823e2..5daef88a79 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -81989,6 +81989,10 @@ export type Database = {netChange: number}[]}+ assert_audit_log_access: {+ Args: { p_company_id: string; p_permission: string }+ Returns: undefined+ }attach_audit_log_append_only: {Args: { p_table_name: string }Returns: undefined@@ -84145,19 +84149,6 @@ export type Database = {Args: { webhook_id: string }Returns: undefined}- insert_audit_log: {- Args: {- p_actor_id: string- p_actor_name: string- p_company_id: string- p_diff?: Json- p_entity_id: string- p_entity_type: string- p_metadata?: Json- p_operation: string- }- Returns: string- }insert_audit_log_batch: {Args: { p_company_id: string; p_entries: Json[] }Returns: number@@ -84399,6 +84390,10 @@ export type Database = {title: string}[]}+ secure_audit_log_table: {+ Args: { p_company_id: string }+ Returns: undefined+ }set_shelf_life_for_operation: {Args: {p_event: Database["public"]["Enums"]["shelfLifeTriggerTiming"]@@ -84543,6 +84538,10 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ sync_delete_user_identity_group: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_edit_document_transaction: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefineddiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 4fe2e823e2..5daef88a79 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -81989,6 +81989,10 @@ export type Database = {netChange: number}[]}+ assert_audit_log_access: {+ Args: { p_company_id: string; p_permission: string }+ Returns: undefined+ }attach_audit_log_append_only: {Args: { p_table_name: string }Returns: undefined@@ -84145,19 +84149,6 @@ export type Database = {Args: { webhook_id: string }Returns: undefined}- insert_audit_log: {- Args: {- p_actor_id: string- p_actor_name: string- p_company_id: string- p_diff?: Json- p_entity_id: string- p_entity_type: string- p_metadata?: Json- p_operation: string- }- Returns: string- }insert_audit_log_batch: {Args: { p_company_id: string; p_entries: Json[] }Returns: number@@ -84399,6 +84390,10 @@ export type Database = {title: string}[]}+ secure_audit_log_table: {+ Args: { p_company_id: string }+ Returns: undefined+ }set_shelf_life_for_operation: {Args: {p_event: Database["public"]["Enums"]["shelfLifeTriggerTiming"]@@ -84543,6 +84538,10 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ sync_delete_user_identity_group: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_edit_document_transaction: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefineddiff --git a/packages/database/supabase/migrations/20260924153817_user-rls-company-scope.sql b/packages/database/supabase/migrations/20260924153817_user-rls-company-scope.sqlnew file mode 100644index 0000000000..2de8ab82f6--- /dev/null+++ b/packages/database/supabase/migrations/20260924153817_user-rls-company-scope.sql@@ -0,0 +1,133 @@+-- Scope the public."user" table to the caller's own companies.+--+-- "Claims admin can view/modify users" was FOR ALL USING+-- has_any_company_permission('users_update') — true for anyone holding+-- users_update in ANY company, which every self-serve signup does in the+-- company it creates. It never looked at the row, so any signed-in user could+-- read, insert, update and delete every user in every tenant through PostgREST.+--+-- After this migration:+-- SELECT — self, anyone sharing a company (unchanged), plus employees of a+-- company where the user has an employee / customer / supplier+-- account (pending invites and deactivated people, which have no+-- userToCompany row but are listed on the People / account pages).+-- UPDATE — self, or an employee holding users_update in a company the user+-- is an active member of (userToCompany).+-- INSERT / DELETE — service role only. No app path writes these with a user+-- JWT; the grants are revoked so a future permissive policy cannot+-- reopen them.+-- Identity columns (id, email, active, admin, developer, isConsoleOperator)+-- are shared by every company the user belongs to and are kept in+-- step with auth.users, so an API-role UPDATE may not change them at all.++DROP POLICY IF EXISTS "Claims admin can view/modify users" ON "public"."user";++DROP POLICY IF EXISTS "Employees can view users with an account in their company" ON "public"."user";+CREATE POLICY "Employees can view users with an account in their company" ON "public"."user"+FOR SELECT USING (+ "id" IN (+ SELECT "id" FROM "employee"+ WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+ )+ OR "id" IN (+ SELECT "id" FROM "customerAccount"+ WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+ )+ OR "id" IN (+ SELECT "id" FROM "supplierAccount"+ WHERE "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+ )+);++-- The old self policy had WITH CHECK only; state both sides explicitly.+DROP POLICY IF EXISTS "Users can modify themselves" ON "public"."user";+CREATE POLICY "Users can modify themselves" ON "public"."user"+FOR UPDATE+USING ((SELECT auth.uid())::text = "id")+WITH CHECK ((SELECT auth.uid())::text = "id");++DROP POLICY IF EXISTS "Employees with users_update can update users in their company" ON "public"."user";+CREATE POLICY "Employees with users_update can update users in their company" ON "public"."user"+FOR UPDATE+USING (+ "id" IN (+ SELECT "userId" FROM "userToCompany"+ WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('users_update'))::text[])+ )+)+WITH CHECK (+ "id" IN (+ SELECT "userId" FROM "userToCompany"+ WHERE "companyId" = ANY ((SELECT get_companies_with_employee_permission('users_update'))::text[])+ )+);++REVOKE INSERT, DELETE, TRUNCATE ON "public"."user" FROM anon, authenticated;++-- RLS cannot restrict columns, and a column-level GRANT would reject the+-- unchanged "id" that updatePublicAccount sends in its payload. So compare+-- instead: an API role may send these columns, but not change them.+CREATE OR REPLACE FUNCTION public.guard_user_identity_columns()+RETURNS TRIGGER+LANGUAGE plpgsql+SET search_path = public+AS $$+BEGIN+ IF current_user IN ('anon', 'authenticated') AND (+ NEW."id" IS DISTINCT FROM OLD."id" OR+ NEW."email" IS DISTINCT FROM OLD."email" OR+ NEW."active" IS DISTINCT FROM OLD."active" OR+ NEW."admin" IS DISTINCT FROM OLD."admin" OR+ NEW."developer" IS DISTINCT FROM OLD."developer" OR+ NEW."isConsoleOperator" IS DISTINCT FROM OLD."isConsoleOperator"+ ) THEN+ RAISE EXCEPTION 'These user fields can only be changed by the server'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ RETURN NEW;+END;+$$;++DROP TRIGGER IF EXISTS "guard_user_identity_columns" ON "public"."user";+CREATE TRIGGER "guard_user_identity_columns"+BEFORE UPDATE ON "public"."user"+FOR EACH ROW+EXECUTE FUNCTION public.guard_user_identity_columns();++-- Deleting a user left its identity group behind (the group's id IS the user's+-- id, with no FK), so re-creating the same user id failed on group_pkey.+CREATE OR REPLACE FUNCTION sync_delete_user_identity_group(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+BEGIN+ IF p_operation != 'DELETE' THEN RETURN; END IF;++ DELETE FROM "group"+ WHERE "id" = p_old->>'id'+ AND "isIdentityGroup" = TRUE;+END;+$$;++DROP TRIGGER IF EXISTS "trg_event_after_sync_user" ON "user";+CREATE TRIGGER "trg_event_after_sync_user"+AFTER INSERT OR UPDATE OR DELETE ON "user"+FOR EACH ROW+EXECUTE FUNCTION public.dispatch_event_after_interceptors(+ 'sync_create_user_identity_group',+ 'sync_update_user_identity_group',+ 'sync_delete_user_identity_group'+);++-- Clear identity groups already orphaned by earlier deletes.+DELETE FROM "group" g+WHERE g."isIdentityGroup" = TRUE+ AND NOT EXISTS (SELECT 1 FROM "user" u WHERE u."id" = g."id");diff --git a/packages/database/supabase/migrations/20260924171942_audit-log-company-scope.sql b/packages/database/supabase/migrations/20260924171942_audit-log-company-scope.sqlnew file mode 100644index 0000000000..872576861c--- /dev/null+++ b/packages/database/supabase/migrations/20260924171942_audit-log-company-scope.sql@@ -0,0 +1,523 @@+-- Scope the audit log to the company it belongs to.+--+-- The per-company "auditLog_<companyId>" tables had one policy,+-- "audit_log_access" FOR ALL USING (true) WITH CHECK (true), with the default+-- anon/authenticated table grants — so anyone holding the public anon key could+-- read or append to any company's audit history given its id. Every audit RPC is+-- SECURITY DEFINER, EXECUTE-able by anon, and checked nothing: get_audit_log read+-- any company's log, insert_audit_log_batch forged entries, delete_old_audit_logs+-- erased them, and drop_audit_log_table dropped the table outright.+--+-- After this migration:+-- read — get_entity_audit_log / get_audit_log / get_audit_log_count, and+-- a direct SELECT on the table, need settings_view in that company.+-- enable — create_audit_log_table needs settings_update in that company.+-- the rest (insert, archive, delete, drop) — service role only; every caller+-- (the AUDIT event handler, the archive job, the invite / ITAR /+-- acknowledge routes) already uses it.+-- The service role and direct Postgres connections (role "none") pass every+-- guard: the check is on the API role PostgREST switched to, which a SECURITY+-- DEFINER function still sees in current_setting('role').+--+-- The guards are checks INSIDE each function, not REVOKE EXECUTE. On this+-- Postgres build (supabase/postgres 15.14.1.112) calling ANY function the+-- caller lacks EXECUTE on, as anon or authenticated, segfaults the backend and+-- restarts the whole server — so a REVOKE on a function PostgREST exposes turns+-- a data leak into an unauthenticated one-request DoS. A RAISE is an ordinary+-- error. Table-level REVOKEs are unaffected and are used below.++-- p_permission NULL means no API role may call it at all (service role only).+CREATE OR REPLACE FUNCTION public.assert_audit_log_access(+ p_company_id TEXT,+ p_permission TEXT+)+RETURNS VOID+LANGUAGE plpgsql+STABLE+SECURITY DEFINER+SET search_path = public+AS $$+BEGIN+ IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN+ RETURN;+ END IF;++ IF p_permission IS NOT NULL AND p_company_id = ANY (+ COALESCE(get_companies_with_employee_permission(p_permission), '{}')::text[]+ ) THEN+ RETURN;+ END IF;++ RAISE EXCEPTION 'Not authorized to access the audit log for this company'+ USING ERRCODE = 'insufficient_privilege';+END;+$$;++-- One company's table: a read policy scoped to that company, and no API writes.+-- Called for existing tables below and by create_audit_log_table for new ones —+-- the default privileges on "public" grant ALL to anon/authenticated on every+-- table the owner creates, so each new table has to be locked down as it is made.+CREATE OR REPLACE FUNCTION public.secure_audit_log_table(p_company_id TEXT)+RETURNS VOID+LANGUAGE plpgsql+SET search_path = public+AS $$+DECLARE+ tbl_name TEXT := 'auditLog_' || p_company_id;+BEGIN+ EXECUTE format('DROP POLICY IF EXISTS "audit_log_access" ON %I', tbl_name);+ EXECUTE format('DROP POLICY IF EXISTS "SELECT" ON %I', tbl_name);+ EXECUTE format(+ 'CREATE POLICY "SELECT" ON %I FOR SELECT USING (+ %L = ANY ((SELECT get_companies_with_employee_permission(''settings_view''))::text[])+ )',+ tbl_name, p_company_id+ );+ EXECUTE format(+ 'REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON %I FROM anon, authenticated',+ tbl_name+ );+END;+$$;++DO $$+DECLARE t TEXT;+BEGIN+ FOR t IN+ SELECT tablename FROM pg_tables+ WHERE schemaname = 'public' AND tablename LIKE 'auditLog\_%' ESCAPE '\'+ LOOP+ PERFORM secure_audit_log_table(substring(t FROM length('auditLog_') + 1));+ END LOOP;+END $$;++-- Fork create_audit_log_table (live def, 20260818014100): guard first, then+-- secure_audit_log_table on both the existing-table and the new-table path.+CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id text)+ RETURNS void+ LANGUAGE plpgsql+ SECURITY DEFINER+AS $function$+DECLARE+ tbl_name TEXT;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, 'settings_update');++ tbl_name := 'auditLog_' || p_company_id;++ IF EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ -- Table exists; ensure recordId column is present (for tables created before this migration)+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_schema = 'public'+ AND information_schema.columns.table_name = tbl_name+ AND column_name = 'recordId'+ ) THEN+ EXECUTE format('ALTER TABLE %I ADD COLUMN "recordId" TEXT', tbl_name);+ EXECUTE format('UPDATE %I SET "recordId" = "entityId" WHERE "recordId" IS NULL', tbl_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',+ 'idx_' || tbl_name || '_record', tbl_name);+ END IF;+ PERFORM attach_audit_log_append_only(tbl_name);+ PERFORM secure_audit_log_table(p_company_id);+ RETURN;+ END IF;++ EXECUTE format('+ CREATE TABLE IF NOT EXISTS %I (+ "id" TEXT PRIMARY KEY DEFAULT id(''aud''),+ "tableName" TEXT NOT NULL,+ "entityType" TEXT NOT NULL,+ "entityId" TEXT NOT NULL,+ "recordId" TEXT,+ "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),+ "actorId" TEXT,+ "diff" JSONB,+ "metadata" JSONB,+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )+ ', tbl_name);++ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',+ 'idx_' || tbl_name || '_entity', tbl_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("tableName")',+ 'idx_' || tbl_name || '_table', tbl_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',+ 'idx_' || tbl_name || '_record', tbl_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',+ 'idx_' || tbl_name || '_actor', tbl_name);+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',+ 'idx_' || tbl_name || '_created', tbl_name);++ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);++ PERFORM attach_audit_log_append_only(tbl_name);+ PERFORM secure_audit_log_table(p_company_id);+END;+$function$;++-- Fork get_entity_audit_log (live def, 20260418000000) with the read guard.+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(+ p_company_id TEXT,+ p_entity_type TEXT,+ p_entity_id TEXT,+ p_limit INTEGER DEFAULT 50,+ p_offset INTEGER DEFAULT 0,+ p_record_id TEXT DEFAULT NULL+)+RETURNS TABLE (+ "id" TEXT,+ "tableName" TEXT,+ "entityType" TEXT,+ "entityId" TEXT,+ "recordId" TEXT,+ "operation" TEXT,+ "actorId" TEXT,+ "diff" JSONB,+ "metadata" JSONB,+ "createdAt" TIMESTAMPTZ+) AS $$+DECLARE+ tbl_name TEXT;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');++ tbl_name := 'auditLog_' || p_company_id;++ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ RETURN;+ END IF;++ IF p_record_id IS NULL THEN+ RETURN QUERY EXECUTE format('+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"+ FROM %I+ WHERE "entityType" = $1 AND "entityId" = $2+ ORDER BY "createdAt" DESC+ LIMIT $3 OFFSET $4+ ', tbl_name)+ USING p_entity_type, p_entity_id, p_limit, p_offset;+ ELSE+ RETURN QUERY EXECUTE format('+ SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"+ FROM %I+ WHERE "entityType" = $1 AND "entityId" = $2 AND "recordId" = $3+ ORDER BY "createdAt" DESC+ LIMIT $4 OFFSET $5+ ', tbl_name)+ USING p_entity_type, p_entity_id, p_record_id, p_limit, p_offset;+ END IF;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- Fork get_audit_log (live def, 20260217120000) with the read guard.+CREATE OR REPLACE FUNCTION public.get_audit_log(+ p_company_id TEXT,+ p_entity_type TEXT DEFAULT NULL,+ p_entity_id TEXT DEFAULT NULL,+ p_actor_id TEXT DEFAULT NULL,+ p_operation TEXT DEFAULT NULL,+ p_start_date TIMESTAMPTZ DEFAULT NULL,+ p_end_date TIMESTAMPTZ DEFAULT NULL,+ p_limit INTEGER DEFAULT 50,+ p_offset INTEGER DEFAULT 0,+ p_search TEXT DEFAULT NULL+)+RETURNS TABLE (+ "id" TEXT,+ "tableName" TEXT,+ "entityType" TEXT,+ "entityId" TEXT,+ "operation" TEXT,+ "actorId" TEXT,+ "diff" JSONB,+ "metadata" JSONB,+ "createdAt" TIMESTAMPTZ,+ "totalCount" BIGINT+) AS $$+DECLARE+ tbl_name TEXT;+ where_clauses TEXT[] := ARRAY[]::TEXT[];+ where_clause TEXT := '';+ query_text TEXT;+ count_query TEXT;+ total BIGINT;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');++ tbl_name := 'auditLog_' || p_company_id;++ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ RETURN;+ END IF;++ IF p_entity_type IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));+ END IF;++ IF p_entity_id IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));+ END IF;++ IF p_actor_id IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));+ END IF;++ IF p_operation IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));+ END IF;++ IF p_start_date IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));+ END IF;++ IF p_end_date IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));+ END IF;++ IF p_search IS NOT NULL AND p_search != '' THEN+ where_clauses := array_append(where_clauses,+ format('"entityId" ILIKE %L', '%' || p_search || '%'));+ END IF;++ IF array_length(where_clauses, 1) > 0 THEN+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');+ END IF;++ count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);+ EXECUTE count_query INTO total;++ query_text := format('+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"+ FROM %I+ %s+ ORDER BY "createdAt" DESC+ LIMIT %s OFFSET %s+ ', total, tbl_name, where_clause, p_limit, p_offset);++ RETURN QUERY EXECUTE query_text;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- Fork get_audit_log_count (live def, 20260217120000) with the read guard.+CREATE OR REPLACE FUNCTION public.get_audit_log_count(+ p_company_id TEXT,+ p_entity_type TEXT DEFAULT NULL,+ p_actor_id TEXT DEFAULT NULL,+ p_operation TEXT DEFAULT NULL,+ p_start_date TIMESTAMPTZ DEFAULT NULL,+ p_end_date TIMESTAMPTZ DEFAULT NULL,+ p_search TEXT DEFAULT NULL+)+RETURNS INTEGER AS $$+DECLARE+ tbl_name TEXT;+ where_clauses TEXT[] := ARRAY[]::TEXT[];+ where_clause TEXT := '';+ count_val INTEGER;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, 'settings_view');++ tbl_name := 'auditLog_' || p_company_id;++ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ RETURN 0;+ END IF;++ IF p_entity_type IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));+ END IF;++ IF p_actor_id IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));+ END IF;++ IF p_operation IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));+ END IF;++ IF p_start_date IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));+ END IF;++ IF p_end_date IS NOT NULL THEN+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));+ END IF;++ IF p_search IS NOT NULL AND p_search != '' THEN+ where_clauses := array_append(where_clauses,+ format('"entityId" ILIKE %L', '%' || p_search || '%'));+ END IF;++ IF array_length(where_clauses, 1) > 0 THEN+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');+ END IF;++ EXECUTE format('SELECT COUNT(*)::INTEGER FROM %I %s', tbl_name, where_clause) INTO count_val;+ RETURN count_val;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- The remaining audit functions are service role only.++-- insert_audit_log is the pre-batch single-row writer. It still writes the+-- "actorName" column that 20260212174458 dropped, so it cannot succeed, and+-- nothing calls it.+DROP FUNCTION IF EXISTS public.insert_audit_log(TEXT, TEXT, TEXT, TEXT, TEXT, TEXT, JSONB, JSONB);++-- Fork drop_audit_log_table (live def, 20260212154954).+CREATE OR REPLACE FUNCTION public.drop_audit_log_table(p_company_id TEXT)+RETURNS VOID AS $$+DECLARE+ tbl_name TEXT;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, NULL);++ tbl_name := 'auditLog_' || p_company_id;++ EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', tbl_name);+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- Fork insert_audit_log_batch (live def, 20260427120000).+CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(+ p_company_id TEXT,+ p_entries JSONB[]+)+RETURNS INTEGER AS $$+DECLARE+ tbl_name TEXT;+ entry JSONB;+ inserted_count INTEGER := 0;+ v_created_at TIMESTAMPTZ;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, NULL);++ tbl_name := 'auditLog_' || p_company_id;++ PERFORM create_audit_log_table(p_company_id);++ FOREACH entry IN ARRAY p_entries+ LOOP+ -- Use the entry's createdAt if provided (the original event time);+ -- otherwise fall back to clock_timestamp() so rows in the same+ -- transaction still get unique values rather than sharing NOW().+ v_created_at := COALESCE(+ (entry->>'createdAt')::TIMESTAMPTZ,+ clock_timestamp()+ );++ EXECUTE format('+ INSERT INTO %I ("tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ ', tbl_name)+ USING+ entry->>'tableName',+ entry->>'entityType',+ entry->>'entityId',+ entry->>'recordId',+ entry->>'operation',+ entry->>'actorId',+ CASE WHEN entry->'diff' = 'null'::jsonb THEN NULL ELSE entry->'diff' END,+ CASE WHEN entry->'metadata' = 'null'::jsonb THEN NULL ELSE entry->'metadata' END,+ v_created_at;++ inserted_count := inserted_count + 1;+ END LOOP;++ RETURN inserted_count;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- Fork get_audit_logs_for_archive (live def, 20260217120000).+CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(+ p_company_id TEXT,+ p_before_date TIMESTAMPTZ+)+RETURNS TABLE (+ "id" TEXT,+ "tableName" TEXT,+ "entityType" TEXT,+ "entityId" TEXT,+ "operation" TEXT,+ "actorId" TEXT,+ "diff" JSONB,+ "metadata" JSONB,+ "createdAt" TIMESTAMPTZ+) AS $$+DECLARE+ tbl_name TEXT;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, NULL);++ tbl_name := 'auditLog_' || p_company_id;++ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ RETURN;+ END IF;++ RETURN QUERY EXECUTE format('+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"+ FROM %I+ WHERE "createdAt" < $1+ ORDER BY "createdAt" ASC+ ', tbl_name)+ USING p_before_date;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- Fork delete_old_audit_logs (live def, 20260818014100).+CREATE OR REPLACE FUNCTION public.delete_old_audit_logs(p_company_id text, p_cutoff_date timestamp with time zone)+ RETURNS integer+ LANGUAGE plpgsql+ SECURITY DEFINER+AS $function$+DECLARE+ tbl_name TEXT;+ deleted_count INTEGER;+BEGIN+ PERFORM assert_audit_log_access(p_company_id, NULL);++ tbl_name := 'auditLog_' || p_company_id;++ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name+ ) THEN+ RETURN 0;+ END IF;++ -- Authorize the append-only trigger to permit these retention deletes.+ PERFORM set_config('app.audit_archiving', 'on', true);++ EXECUTE format('+ WITH deleted AS (+ DELETE FROM %I+ WHERE "createdAt" < $1+ RETURNING *+ )+ SELECT COUNT(*) FROM deleted+ ', tbl_name)+ USING p_cutoff_date+ INTO deleted_count;++ RETURN deleted_count;+END;+$function$;++NOTIFY pgrst, 'reload schema';diff --git a/packages/database/supabase/migrations/20260924192316_api-function-guards-not-revokes.sql b/packages/database/supabase/migrations/20260924192316_api-function-guards-not-revokes.sqlnew file mode 100644index 0000000000..a1152773ac--- /dev/null+++ b/packages/database/supabase/migrations/20260924192316_api-function-guards-not-revokes.sql@@ -0,0 +1,314 @@+-- Replace REVOKE EXECUTE on API-exposed functions with in-function guards.+--+-- On supabase/postgres 15.14.1.112, calling a function the caller lacks EXECUTE+-- on, as anon or authenticated, segfaults the backend (signal 11) and the+-- postmaster restarts every connection. Reproduced with a plain+-- `LANGUAGE sql` function in a fresh container of that image; a RAISE, a+-- missing TABLE privilege and "must be owner" are all ordinary errors. Every+-- function in "public" is a PostgREST RPC, so each of the six below was an+-- unauthenticated one-request restart of the database:+-- POST /rest/v1/rpc/get_integration_secret (anon key only)+--+-- The four integration-secret functions keep their service-role-only contract,+-- now enforced by the first statement of the body. PostgREST switches to the+-- JWT's role with SET ROLE, and a SECURITY DEFINER function still sees that in+-- current_setting('role'), so anon/authenticated are refused while the service+-- role and direct Postgres connections (role "none") pass. All four are only+-- called by service-role clients (packages/ee/src/integrations/secrets.ts,+-- apps/erp/app/modules/settings/settings.server.ts).+--+-- The two job helpers cannot use that guard: complete_job_to_inventory calls+-- them, and an MES user reaches it as authenticated, which the role GUC still+-- reports inside the nested call. They become SECURITY INVOKER instead. Called+-- from complete_job_to_inventory (SECURITY DEFINER) they run as its owner,+-- exactly as before; called directly through the API they run as the caller,+-- under RLS, and can touch only what that caller could already read or update+-- through the jobOperation table.++-- ---------------------------------------------------------------------------+-- Integration secrets (fork of the live defs: 20260911164732 for+-- upsert_integration_secret, 20260817122916 for get/delete, 20260919152233 for+-- upsert_company_integration_patch), guard added as the first statement.+-- ---------------------------------------------------------------------------++CREATE OR REPLACE FUNCTION upsert_integration_secret(p_company_id text, p_integration_id text, p_secret jsonb)+RETURNS text LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, vault AS $$+DECLARE+ v_name text := 'integration:' || p_company_id || ':' || p_integration_id;+ v_id uuid;+ v_existing jsonb;+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'upsert_integration_secret is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ SELECT id INTO v_id FROM vault.secrets WHERE name = v_name;+ IF v_id IS NULL THEN+ v_id := vault.create_secret(p_secret::text, v_name, 'Carbon integration secret');+ ELSE+ -- Merge into the stored bag: an omitted key keeps its existing value.+ SELECT decrypted_secret::jsonb INTO v_existing+ FROM vault.decrypted_secrets WHERE id = v_id;+ -- Vault restricts direct UPDATE on vault.secrets; use the supported function.+ PERFORM vault.update_secret(v_id, (COALESCE(v_existing, '{}'::jsonb) || p_secret)::text);+ END IF;+ UPDATE "companyIntegration" SET "secretRef" = v_id::text+ WHERE "companyId" = p_company_id AND id = p_integration_id;+ RETURN v_id::text;+END;+$$;++CREATE OR REPLACE FUNCTION get_integration_secret(p_company_id text, p_integration_id text)+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, vault AS $$+DECLARE+ v_ref text;+ v_secret text;+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'get_integration_secret is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ SELECT "secretRef" INTO v_ref FROM "companyIntegration"+ WHERE "companyId" = p_company_id AND id = p_integration_id;+ IF v_ref IS NULL THEN RETURN NULL; END IF; -- caller applies transitional fallback / fails closed+ SELECT decrypted_secret INTO v_secret FROM vault.decrypted_secrets WHERE id = v_ref::uuid;+ IF v_secret IS NULL THEN RETURN NULL; END IF;+ RETURN v_secret::jsonb;+END;+$$;++CREATE OR REPLACE FUNCTION delete_integration_secret(p_company_id text, p_integration_id text)+RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, vault AS $$+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'delete_integration_secret is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ DELETE FROM vault.secrets WHERE name = 'integration:' || p_company_id || ':' || p_integration_id;+END;+$$;++CREATE OR REPLACE FUNCTION public.upsert_company_integration_patch(+ p_company_id text,+ p_integration_id text,+ p_metadata_patch jsonb DEFAULT '{}'::jsonb,+ p_secret_patch jsonb DEFAULT '{}'::jsonb,+ p_metadata_remove text[] DEFAULT ARRAY[]::text[],+ p_secret_remove text[] DEFAULT ARRAY[]::text[],+ p_active boolean DEFAULT NULL,+ p_updated_by text DEFAULT NULL+) RETURNS jsonb+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = pg_catalog, public, vault+AS $function$+DECLARE+ v_existing public."companyIntegration"%ROWTYPE;+ v_result public."companyIntegration"%ROWTYPE;+ v_exists boolean;+ v_metadata jsonb;+ v_secret jsonb := '{}'::jsonb;+ v_secret_ref text;+ v_secret_changed boolean;+ v_key text;+ v_path text[];+ v_value jsonb;+ v_index integer;+ v_vault_id uuid;+ v_vault_name text := 'integration:' || p_company_id || ':' || p_integration_id;+BEGIN+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN+ RAISE EXCEPTION 'upsert_company_integration_patch is service role only'+ USING ERRCODE = 'insufficient_privilege';+ END IF;++ IF p_company_id IS NULL OR p_company_id = '' THEN+ RAISE EXCEPTION 'company id is required';+ END IF;+ IF p_integration_id IS NULL OR p_integration_id = '' THEN+ RAISE EXCEPTION 'integration id is required';+ END IF;+ IF jsonb_typeof(COALESCE(p_metadata_patch, '{}'::jsonb)) <> 'object' THEN+ RAISE EXCEPTION 'metadata patch must be a JSON object';+ END IF;+ IF jsonb_typeof(COALESCE(p_secret_patch, '{}'::jsonb)) <> 'object' THEN+ RAISE EXCEPTION 'secret patch must be a JSON object';+ END IF;++ p_metadata_patch := COALESCE(p_metadata_patch, '{}'::jsonb);+ p_secret_patch := COALESCE(p_secret_patch, '{}'::jsonb);+ p_metadata_remove := COALESCE(p_metadata_remove, ARRAY[]::text[]);+ p_secret_remove := COALESCE(p_secret_remove, ARRAY[]::text[]);++ -- Serialize both existing-row updates and concurrent first-time upserts.+ PERFORM pg_advisory_xact_lock(+ hashtextextended(p_company_id || E'\x1f' || p_integration_id, 0)+ );++ SELECT ci.* INTO v_existing+ FROM public."companyIntegration" ci+ WHERE ci."companyId" = p_company_id+ AND ci.id = p_integration_id+ FOR UPDATE;+ v_exists := FOUND;++ v_metadata := CASE+ WHEN v_exists THEN COALESCE(v_existing.metadata::jsonb, '{}'::jsonb)+ ELSE '{}'::jsonb+ END;+ IF jsonb_typeof(v_metadata) <> 'object' THEN+ RAISE EXCEPTION 'stored integration metadata must be a JSON object';+ END IF;+ v_secret_ref := CASE WHEN v_exists THEN v_existing."secretRef" ELSE NULL END;++ FOREACH v_key IN ARRAY p_metadata_remove LOOP+ v_path := string_to_array(v_key, '.');+ IF v_key = '' OR array_position(v_path, '') IS NOT NULL THEN+ RAISE EXCEPTION 'invalid metadata remove path: %', v_key;+ END IF;+ v_metadata := v_metadata #- v_path;+ END LOOP;++ FOR v_key, v_value IN SELECT key, value FROM jsonb_each(p_metadata_patch)+ LOOP+ v_path := string_to_array(v_key, '.');+ IF v_key = '' OR array_position(v_path, '') IS NOT NULL THEN+ RAISE EXCEPTION 'invalid metadata patch path: %', v_key;+ END IF;+ IF cardinality(v_path) > 1 THEN+ FOR v_index IN 1..cardinality(v_path) - 1 LOOP+ IF v_metadata #> v_path[1:v_index] IS NULL+ OR jsonb_typeof(v_metadata #> v_path[1:v_index]) <> 'object'+ THEN+ v_metadata := jsonb_set(+ v_metadata,+ v_path[1:v_index],+ '{}'::jsonb,+ true+ );+ END IF;+ END LOOP;+ END IF;+ v_metadata := jsonb_set(v_metadata, v_path, v_value, true);+ END LOOP;++ v_secret_changed := p_secret_patch <> '{}'::jsonb+ OR cardinality(p_secret_remove) > 0;+ IF v_secret_changed THEN+ IF v_secret_ref IS NOT NULL THEN+ SELECT ds.id, ds.decrypted_secret::jsonb INTO v_vault_id, v_secret+ FROM vault.decrypted_secrets ds+ WHERE ds.id = v_secret_ref::uuid;+ IF NOT FOUND OR jsonb_typeof(v_secret) <> 'object' THEN+ RAISE EXCEPTION 'stored integration secret is unavailable';+ END IF;+ ELSE+ -- Recover a deterministic Vault record whose row pointer was lost. Load+ -- its whole bag before patching so adopting it cannot erase siblings.+ SELECT ds.id, ds.decrypted_secret::jsonb INTO v_vault_id, v_secret+ FROM vault.decrypted_secrets ds+ WHERE ds.name = v_vault_name;+ IF FOUND THEN+ IF jsonb_typeof(v_secret) <> 'object' THEN+ RAISE EXCEPTION 'stored integration secret is unavailable';+ END IF;+ v_secret_ref := v_vault_id::text;+ ELSE+ -- SELECT INTO clears its targets when no row is found. Restore the+ -- empty bag before applying the first secret patch.+ v_secret := '{}'::jsonb;+ END IF;+ END IF;++ FOREACH v_key IN ARRAY p_secret_remove LOOP+ IF v_key = '' OR array_position(string_to_array(v_key, '.'), '') IS NOT NULL THEN+ RAISE EXCEPTION 'invalid secret remove path: %', v_key;+ END IF;+ -- Vault bags intentionally use literal flat dot-path keys; the TS reader+ -- expands each key back into nested metadata with setPath().+ v_secret := v_secret - v_key;+ END LOOP;++ FOR v_key, v_value IN SELECT key, value FROM jsonb_each(p_secret_patch)+ LOOP+ IF v_key = '' OR array_position(string_to_array(v_key, '.'), '') IS NOT NULL THEN+ RAISE EXCEPTION 'invalid secret patch path: %', v_key;+ END IF;+ v_secret := v_secret || jsonb_build_object(v_key, v_value);+ END LOOP;++ IF v_secret = '{}'::jsonb THEN+ IF v_secret_ref IS NOT NULL THEN+ DELETE FROM vault.secrets WHERE id = v_secret_ref::uuid;+ END IF;+ v_secret_ref := NULL;+ ELSIF v_secret_ref IS NULL THEN+ v_vault_id := vault.create_secret(+ v_secret::text,+ v_vault_name,+ 'Carbon integration secret'+ );+ v_secret_ref := v_vault_id::text;+ ELSE+ PERFORM vault.update_secret(v_secret_ref::uuid, v_secret::text);+ END IF;+ END IF;++ IF v_exists THEN+ UPDATE public."companyIntegration"+ SET metadata = v_metadata::json,+ active = COALESCE(p_active, v_existing.active),+ "secretRef" = v_secret_ref,+ "updatedBy" = COALESCE(p_updated_by, v_existing."updatedBy"),+ "updatedAt" = now()+ WHERE id = p_integration_id+ AND "companyId" = p_company_id+ RETURNING * INTO v_result;+ ELSE+ INSERT INTO public."companyIntegration" (+ id,+ "companyId",+ metadata,+ active,+ "secretRef",+ "updatedBy"+ ) VALUES (+ p_integration_id,+ p_company_id,+ v_metadata::json,+ COALESCE(p_active, false),+ v_secret_ref,+ p_updated_by+ )+ RETURNING * INTO v_result;+ END IF;++ RETURN to_jsonb(v_result);+END;+$function$;++-- The guards are in place, so give EXECUTE back: a refused call must reach the+-- RAISE rather than the privilege check that crashes the backend.+GRANT EXECUTE ON FUNCTION upsert_integration_secret(text, text, jsonb) TO anon, authenticated;+GRANT EXECUTE ON FUNCTION get_integration_secret(text, text) TO anon, authenticated;+GRANT EXECUTE ON FUNCTION delete_integration_secret(text, text) TO anon, authenticated;+GRANT EXECUTE ON FUNCTION public.upsert_company_integration_patch(+ text, text, jsonb, jsonb, text[], text[], boolean, text+) TO anon, authenticated;++-- ---------------------------------------------------------------------------+-- Job completion helpers (20260922050131 / 20260922183000): internal to+-- complete_job_to_inventory. SECURITY INVOKER, then EXECUTE back to the API+-- roles.+-- ---------------------------------------------------------------------------++ALTER FUNCTION terminal_job_operations(TEXT) SECURITY INVOKER;+ALTER FUNCTION complete_job_remaining_quantities(TEXT, NUMERIC, TEXT) SECURITY INVOKER;++GRANT EXECUTE ON FUNCTION terminal_job_operations(TEXT) TO anon, authenticated;+GRANT EXECUTE ON FUNCTION complete_job_remaining_quantities(TEXT, NUMERIC, TEXT) TO anon, authenticated;++NOTIFY pgrst, 'reload schema';