feat(db): add compass schema + RLS day 1 migration
Sprint 4 first production migration. New `compass` schema isolates the multi-tenant data layer from the legacy Lovable `public.*` demo tables so both can coexist until the demo is retired. Tables (all with tenant_id + RLS enabled in the same file): - compass.tenants / compass.users - compass.contracts / compass.clauses (denormalized tenant_id for RLS perf) - compass.audit_log + compass.task_events (append-only: SELECT+INSERT policies only, REVOKE UPDATE/DELETE as defense-in-depth) - compass.jurisdictions (global reference, no RLS, GRANT SELECT) Fail-closed posture: when middleware does not SET LOCAL app.tenant_id, current_setting(..., true) returns NULL and policy filter evaluates false, leaving rows invisible rather than open. Audit report in docs/audits/2026-05-18_rls_day_one.md walks compass-rls-auditor checklist + CLAUDE.md security invariants 9-pkt + compass-architecture self-check 12-pkt. Verdict PASS with 5 non-blocking follow-up notes (storage bucket policy, soft-delete filter, jurisdictions Python sync, service_role runtime discipline, audit_log writer Sprint 5). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
8771a72f50
commit
142400947a
@@ -0,0 +1,130 @@
|
||||
# RLS audit — Sprint 4 day-one migration
|
||||
|
||||
- **Date:** 2026-05-18
|
||||
- **Auditor:** Claude (inline — `compass-rls-auditor` agent definition + skill checklist applied directly; Opus 4.7 subagent dispatch deferred Sprint 5+ when there is a real PR pipeline)
|
||||
- **Target:** `supabase/migrations/20260518000000_rls_day_one.sql`
|
||||
- **Verdict:** **PASS** with 5 follow-up notes (none merge-blocking)
|
||||
|
||||
## Scope
|
||||
|
||||
First production migration. Establishes Compass-native data layer in dedicated `compass` schema (separated from legacy Lovable `public.*`). Six tenant-scoped tables + one global reference (`jurisdictions`). All six tenant tables must have RLS enabled in the same file (CLAUDE.md security invariant #1 — non-negotiable).
|
||||
|
||||
## Reference checklist
|
||||
|
||||
Three independent checklists evaluated:
|
||||
|
||||
1. **CLAUDE.md security invariants 9-pkt** (compass-contract-hub project memory)
|
||||
2. **compass-architecture self-check 12-pkt** (RLS day 1 + tenant_id denormalization + audit log)
|
||||
3. **compass-rls-auditor agent definition migration checklist** (RLS+policy in same file, denormalization, no destructive drops)
|
||||
|
||||
## CLAUDE.md security invariants 9-pkt
|
||||
|
||||
| # | Invariant | Status | Evidence |
|
||||
|---|---|---|---|
|
||||
| 1 | RLS on every table with `tenant_id`; no `service_role` bypass in business logic | ✅ PASS | `ALTER TABLE compass.{tenants,users,contracts,clauses,audit_log,task_events} ENABLE ROW LEVEL SECURITY` (lines 73, 96, 124, 162, 199, 235). `service_role` discipline is a runtime concern — see Note 4 below. |
|
||||
| 2 | `tenant_id` in JWT claims, verified in FastAPI middleware | 🔵 N/A this PR | Wired up in Task #3 (`packages/core/auth.py` Supabase JWKS verify); migration only sets schema for the claim to land in. |
|
||||
| 3 | `tenant_id` propagation (Langfuse + Celery + log lines) | 🔵 N/A this PR | Schema-only change. M5/M8 enforced in gateway (Sprint 3) and per-task code. |
|
||||
| 4 | Storage isolation — paths prefixed `<tenant_id>/...` | 🟡 Note 1 | `contracts.storage_path text` allows any value. The prefix invariant lives in Supabase Storage RLS policy on the bucket, **not** here. Sprint 4 follow-up: bucket policy migration. |
|
||||
| 5 | Qdrant payload filter `tenant_id` | 🔵 N/A this PR | Qdrant deploy Sprint 5+. |
|
||||
| 6 | Audit log append-only, every mutation persisted | ✅ PASS | `compass.audit_log` has SELECT + INSERT policies only. No UPDATE/DELETE policy exists; Postgres rejects mutations when no policy matches. `REVOKE UPDATE, DELETE … FROM authenticated` adds defense-in-depth. |
|
||||
| 7 | Never log PII in plaintext | 🔵 N/A this PR | Logging concern, not schema. `compass.audit_log.diff jsonb` field requires app-layer redaction discipline. |
|
||||
| 8 | AI legal disclaimer in user-facing LLM output | 🔵 N/A this PR | Hardcoded in `LiabilityClause.enforce_counsel_disclaimer` validator (Sprint 2). |
|
||||
| 9 | Secrets never in git | ✅ PASS | No secrets in migration. |
|
||||
|
||||
## compass-architecture self-check 12-pkt
|
||||
|
||||
| # | Check | Status | Evidence |
|
||||
|---|---|---|---|
|
||||
| 1 | Monorepo boundary respected | ✅ | Migration is data layer only; no Python imports. |
|
||||
| 2 | File placement | ✅ | `supabase/migrations/YYYYMMDDHHMMSS_<verb>_<noun>.sql` naming honored. |
|
||||
| 3 | uv workspace consistent | 🔵 N/A | No package changes. |
|
||||
| 4 | **RLS day 1** — new table has RLS enabled + tenant_isolation policy in same migration | ✅ | All 6 tenant tables. `jurisdictions` correctly excluded (global reference). |
|
||||
| 5 | **tenant_id denormalized where it matters** | ✅ | `compass.clauses.tenant_id` is denormalized (also lives on `contracts`). RLS filter avoids the JOIN. Index `clauses_tenant_type_idx (tenant_id, clause_type)` supports the typical query path. |
|
||||
| 6 | Audit log entry path exists | ✅ | `compass.audit_log` table + append-only policies created. Writer (`packages/core/audit.py`) still stub — wired in Sprint 4 Task #5-adjacent work (see Note 5). |
|
||||
| 7 | tenant_id propagation | 🔵 N/A this PR | Runtime concern. |
|
||||
| 8 | No service_role bypass | 🟡 Note 4 | Migration doesn't grant `service_role` anything beyond default. Discipline lives in app code review. |
|
||||
| 9 | Storage / Vector isolation | 🟡 Note 1 | See invariant #4. |
|
||||
| 10 | Schema-first | 🔵 N/A | No endpoints. |
|
||||
| 11 | Streaming for >2s | 🔵 N/A | |
|
||||
| 12 | ADR-001 mandates cross-check | ✅ | Pure data layer, no LLM ops; mandates not triggered. |
|
||||
|
||||
## compass-rls-auditor migration checklist
|
||||
|
||||
| Check | Status | Evidence |
|
||||
|---|---|---|
|
||||
| New table with `tenant_id` → ENABLE ROW LEVEL SECURITY in same file? | ✅ | All 6 tenant tables. |
|
||||
| New table with `tenant_id` → tenant_isolation policy in same file? | ✅ | Each table has a `tenant_isolation` policy (or named pair for append-only). |
|
||||
| Nested entity denormalizes tenant_id vs JOIN? | ✅ | `clauses.tenant_id` denormalized. |
|
||||
| Migration drops columns or tables? | ✅ | None dropped. Legacy `public.*` left intact. |
|
||||
| Atomic — no "add RLS later" split across migrations? | ✅ | Single file, single transaction (`BEGIN…COMMIT`). |
|
||||
| Append-only tables protected from UPDATE/DELETE? | ✅ | `audit_log` and `task_events`: SELECT+INSERT policies only, plus explicit REVOKE. |
|
||||
| Reference tables explicit about RLS posture? | ✅ | `jurisdictions` has no RLS — global, read-only. GRANT SELECT to authenticated + anon. |
|
||||
|
||||
## Fail-closed verification
|
||||
|
||||
Mental trace of policy `USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)` when middleware fails to set the session var:
|
||||
|
||||
1. `current_setting('app.tenant_id', true)` → returns `NULL` (because `missing_ok=true`).
|
||||
2. `NULL::uuid` → `NULL`.
|
||||
3. `tenant_id = NULL` → `NULL` (SQL three-valued logic).
|
||||
4. Policy USING returning NULL is treated as FALSE → row invisible.
|
||||
|
||||
Posture is **fail-closed**: a misconfigured middleware results in zero rows visible, not full-table leak. The audit confirms this is the desired behavior; an `IS NOT NULL` guard is unnecessary and could create false confidence that the explicit check is what's protecting us.
|
||||
|
||||
## Follow-up notes (non-blocking)
|
||||
|
||||
### Note 1 — Storage bucket RLS not in this migration
|
||||
|
||||
`contracts.storage_path text` carries the path but does not enforce the `<tenant_id>/` prefix. Supabase Storage RLS lives on `storage.objects`. Sprint 4 follow-up: add migration `2026051800001_storage_rls.sql` with bucket policy:
|
||||
|
||||
```sql
|
||||
CREATE POLICY tenant_prefix_storage ON storage.objects
|
||||
FOR ALL USING (
|
||||
bucket_id = 'contracts'
|
||||
AND (storage.foldername(name))[1] = (current_setting('app.tenant_id', true))
|
||||
);
|
||||
```
|
||||
|
||||
Tracked as Sprint 4 stretch / Sprint 5 carry-over.
|
||||
|
||||
### Note 2 — Soft delete + RLS interaction
|
||||
|
||||
`contracts.deleted_at timestamptz` is the soft-delete marker, but the RLS policy does **not** filter by `deleted_at IS NULL`. Application layer must add `WHERE deleted_at IS NULL` in queries (or a view). Considered acceptable — putting soft-delete in RLS conflates two concerns (access control vs. logical lifecycle) and prevents legitimate admin recovery queries.
|
||||
|
||||
Optional Sprint 5+ optimization: partial index `CREATE INDEX … WHERE deleted_at IS NULL` once query patterns stabilize.
|
||||
|
||||
### Note 3 — Jurisdictions sync with Python
|
||||
|
||||
Inserted codes (`pl`, `de`, `fr`, `uk`, `us_ny`, `eu`) match `compass_jurisdictions.SUPPORTED_JURISDICTIONS` at the time of writing. There is no automated sync — adding a jurisdiction requires migration **and** Python list update. Acceptable for solo-founder phase; revisit when jurisdiction count crosses ~10.
|
||||
|
||||
### Note 4 — service_role discipline is a runtime concern
|
||||
|
||||
The migration grants nothing to `service_role` beyond default schema usage. By default `service_role` has BYPASSRLS — meaning *any* code path using a `service_role` key bypasses every policy in this file. CLAUDE.md anti-pattern: "`service_role` Supabase key w business logic". Enforcement lives in:
|
||||
|
||||
- `apps/api` code review — `compass-rls-auditor` agent against route handlers
|
||||
- Hook `check_secrets_stage.py` — blocks committing the key
|
||||
- Future MCP audit on `apps/api/routes/**`
|
||||
|
||||
This is a known split between schema and code that cannot be closed at the DB layer alone.
|
||||
|
||||
### Note 5 — audit_log writer still NotImplementedError
|
||||
|
||||
`packages/core/audit.py::emit` raises `NotImplementedError`. The table exists, the policies exist, but no caller currently writes to it. Sprint 4 carry-over (lower priority than JWT + tenant_context + events) or Sprint 5 — schedule next to the first mutation endpoint that needs auditing.
|
||||
|
||||
## Cross-tenant integration test
|
||||
|
||||
`tests/integration/test_tenant_isolation.py` does not exist yet (deferred — would require live Supabase instance per `pyproject.toml` deps `supabase>=2.7` + asyncpg). Acceptance pattern when written:
|
||||
|
||||
1. Create two tenants T1, T2 + one user per tenant.
|
||||
2. `SET LOCAL app.tenant_id = T1`, insert contract → reads it back, list shows 1.
|
||||
3. `SET LOCAL app.tenant_id = T2`, list contracts → empty.
|
||||
4. Attempt INSERT with `tenant_id = T1` while session is T2 → policy WITH CHECK rejects.
|
||||
5. UPDATE audit_log → fails (no policy).
|
||||
|
||||
Tracked Sprint 4 stretch.
|
||||
|
||||
## Verdict
|
||||
|
||||
**PASS.** Migration safe to apply against a fresh Supabase project. The five follow-up notes are tracked separately; none of them are conditions for merge.
|
||||
|
||||
If `compass-rls-auditor` subagent gets battle-tested on a real PR, that run produces `docs/audits/rls-audit-pr-<n>.md`. This doc is the manual baseline.
|
||||
@@ -0,0 +1,259 @@
|
||||
-- Sprint 4 RLS day 1 — Compass multi-tenant data layer
|
||||
--
|
||||
-- Per CLAUDE.md security invariant #1: every table with tenant_id has RLS
|
||||
-- enabled in the same file that creates the table. No two-step "add RLS
|
||||
-- later" pattern. Cross-tenant data leak is unrecoverable — fail closed.
|
||||
--
|
||||
-- Coexistence note: legacy Lovable tables live in `public` (contracts as
|
||||
-- TEXT PK, companies, negotiation_messages, audit_logs, app_settings — all
|
||||
-- demo data for apps/web prototype). The Compass-native data model lives in
|
||||
-- a dedicated schema `compass` to avoid name + shape collisions. When the
|
||||
-- legacy demo is retired, `public.contracts` etc. can be dropped without
|
||||
-- touching Compass production data.
|
||||
--
|
||||
-- RLS contract: middleware (apps/api) sets `app.tenant_id` via
|
||||
-- `SET LOCAL app.tenant_id = '<uuid>'` after JWT verify. Policies read that
|
||||
-- session var; if it is unset, `current_setting(..., true)` returns NULL
|
||||
-- and the policy filter `tenant_id = NULL::uuid` evaluates to false → row
|
||||
-- invisible. This is the fail-closed posture.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Schema + extensions
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS compass;
|
||||
|
||||
GRANT USAGE ON SCHEMA compass TO authenticated;
|
||||
GRANT USAGE ON SCHEMA compass TO service_role;
|
||||
|
||||
-- gen_random_uuid() lives in pgcrypto (already enabled in Supabase by default,
|
||||
-- but make the dependency explicit).
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Reference: jurisdictions (global, no RLS, read-only for clients)
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.jurisdictions (
|
||||
code text PRIMARY KEY,
|
||||
name text NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO compass.jurisdictions (code, name) VALUES
|
||||
('pl', 'Polska'),
|
||||
('de', 'Deutschland'),
|
||||
('fr', 'France'),
|
||||
('uk', 'United Kingdom'),
|
||||
('us_ny', 'New York'),
|
||||
('eu', 'European Union');
|
||||
|
||||
GRANT SELECT ON compass.jurisdictions TO authenticated;
|
||||
GRANT SELECT ON compass.jurisdictions TO anon;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- tenants — top-level RLS scope, billing target
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.tenants (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE compass.tenants ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- A user can see/touch only their own tenant row.
|
||||
CREATE POLICY tenant_self_isolation ON compass.tenants
|
||||
USING (id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- users — mirror Supabase Auth user.id, augmented with tenant_id + role
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.users (
|
||||
id uuid PRIMARY KEY, -- == auth.users.id (JWT sub)
|
||||
tenant_id uuid NOT NULL REFERENCES compass.tenants(id) ON DELETE RESTRICT,
|
||||
email text NOT NULL,
|
||||
role text NOT NULL DEFAULT 'member'
|
||||
CHECK (role IN ('admin','member','viewer')),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX users_tenant_id_idx ON compass.users(tenant_id);
|
||||
|
||||
ALTER TABLE compass.users ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY tenant_isolation ON compass.users
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- contracts — top-level doc entity
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.contracts (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id uuid NOT NULL REFERENCES compass.tenants(id) ON DELETE RESTRICT,
|
||||
title text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'draft'
|
||||
CHECK (status IN ('draft','extracting','extracted','reviewed','signed','active','expired')),
|
||||
storage_path text, -- Supabase Storage object key prefixed `<tenant_id>/`
|
||||
jurisdiction_code text REFERENCES compass.jurisdictions(code),
|
||||
created_by uuid REFERENCES compass.users(id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz -- soft delete; RLS still filters
|
||||
);
|
||||
|
||||
CREATE INDEX contracts_tenant_id_idx ON compass.contracts(tenant_id);
|
||||
CREATE INDEX contracts_tenant_status_idx ON compass.contracts(tenant_id, status);
|
||||
CREATE INDEX contracts_tenant_created_idx ON compass.contracts(tenant_id, created_at DESC);
|
||||
|
||||
ALTER TABLE compass.contracts ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY tenant_isolation ON compass.contracts
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- clauses — extracted clause payloads per contract
|
||||
--
|
||||
-- tenant_id is denormalized (also on contracts) so the RLS policy can filter
|
||||
-- without a JOIN — compass-architecture fundament 2.
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.clauses (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id uuid NOT NULL REFERENCES compass.tenants(id) ON DELETE RESTRICT,
|
||||
contract_id uuid NOT NULL REFERENCES compass.contracts(id) ON DELETE CASCADE,
|
||||
clause_type text NOT NULL
|
||||
CHECK (clause_type IN (
|
||||
'liability','ip','termination','dataPrivacy','payment','delivery',
|
||||
'confidentiality','renewal','maintenance','scopeOfWork','sla','security',
|
||||
'mileage','other'
|
||||
)),
|
||||
payload jsonb NOT NULL, -- Pydantic dump of <ClauseType>Clause
|
||||
preliminary_status text
|
||||
CHECK (preliminary_status IN ('Approved','Needs Attention','Rejected')),
|
||||
confidence numeric(3,2)
|
||||
CHECK (confidence >= 0 AND confidence <= 1),
|
||||
extraction_prompt_version text,
|
||||
jurisdiction_code text REFERENCES compass.jurisdictions(code),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX clauses_tenant_id_idx ON compass.clauses(tenant_id);
|
||||
CREATE INDEX clauses_contract_id_idx ON compass.clauses(contract_id);
|
||||
CREATE INDEX clauses_tenant_type_idx ON compass.clauses(tenant_id, clause_type);
|
||||
|
||||
ALTER TABLE compass.clauses ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY tenant_isolation ON compass.clauses
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- audit_log — append-only mutation record (CLAUDE.md security invariant #6)
|
||||
--
|
||||
-- Append-only enforced at policy level: SELECT + INSERT permitted within
|
||||
-- tenant, but no UPDATE / DELETE policy is created. Postgres rejects the
|
||||
-- statement when no policy matches.
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.audit_log (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id uuid NOT NULL REFERENCES compass.tenants(id) ON DELETE RESTRICT,
|
||||
user_id uuid REFERENCES compass.users(id) ON DELETE SET NULL, -- null = system op
|
||||
operation text NOT NULL
|
||||
CHECK (operation IN ('create','update','delete','view_sensitive','admin_override','extract')),
|
||||
entity_type text NOT NULL,
|
||||
entity_id uuid,
|
||||
diff jsonb,
|
||||
request_id text,
|
||||
ts timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX audit_log_tenant_ts_idx ON compass.audit_log(tenant_id, ts DESC);
|
||||
CREATE INDEX audit_log_entity_idx ON compass.audit_log(tenant_id, entity_type, entity_id);
|
||||
|
||||
ALTER TABLE compass.audit_log ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY audit_log_tenant_select ON compass.audit_log
|
||||
FOR SELECT
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
CREATE POLICY audit_log_tenant_insert ON compass.audit_log
|
||||
FOR INSERT
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
-- Explicit revoke — Postgres defaults already deny when no policy matches,
|
||||
-- but making it explicit guards against later careless GRANT.
|
||||
REVOKE UPDATE, DELETE ON compass.audit_log FROM authenticated;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- task_events — SSE event stream persistence per Celery task
|
||||
--
|
||||
-- Persist alongside Redis pub/sub for: SSE resumability after disconnect,
|
||||
-- post-mortem replay, audit of streaming pipeline. Append-only same as
|
||||
-- audit_log.
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE compass.task_events (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id uuid NOT NULL REFERENCES compass.tenants(id) ON DELETE RESTRICT,
|
||||
task_id uuid NOT NULL,
|
||||
event_type text NOT NULL
|
||||
CHECK (event_type IN ('phase','clause_extracted','clause_reviewed','warning','error','done')),
|
||||
payload jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX task_events_task_seq_idx ON compass.task_events(task_id, created_at);
|
||||
CREATE INDEX task_events_tenant_idx ON compass.task_events(tenant_id, created_at DESC);
|
||||
|
||||
ALTER TABLE compass.task_events ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY task_events_tenant_select ON compass.task_events
|
||||
FOR SELECT
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
CREATE POLICY task_events_tenant_insert ON compass.task_events
|
||||
FOR INSERT
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
|
||||
REVOKE UPDATE, DELETE ON compass.task_events FROM authenticated;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- updated_at trigger for contracts
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE OR REPLACE FUNCTION compass.set_updated_at()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER contracts_set_updated_at
|
||||
BEFORE UPDATE ON compass.contracts
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION compass.set_updated_at();
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Table privileges — RLS still gates row visibility on top of these grants
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON compass.tenants TO authenticated;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON compass.users TO authenticated;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON compass.contracts TO authenticated;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON compass.clauses TO authenticated;
|
||||
GRANT SELECT, INSERT ON compass.audit_log TO authenticated;
|
||||
GRANT SELECT, INSERT ON compass.task_events TO authenticated;
|
||||
|
||||
COMMIT;
|
||||
Reference in New Issue
Block a user