Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,59 @@
-- R-P5 · Apps-Engine — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to prisma/rls/tenant-isolation.sql (R-P2b) and the per-module RLS
-- blocks (file/task/hr/crypto). The Apps-Engine tables ship in the tracked merge
-- migration (created at main-merge per AD-21); this RLS block stays out of the
-- auto-migration path (activation = coordinated P5 cutover, not a schema diff).
--
-- IMPORTANT: `App` is a GLOBAL catalog table (no tenantId) → NO policy, NO RLS.
-- Only the tenant-scoped rows are isolated: DataConnection, AppSyncRun,
-- AppSyncRunLog, AppSyncItem.
--
-- WHY DEFERRED: with RLS + FORCE on, any query WITHOUT `app.tenant_id` returns
-- ZERO rows. The dataConnection/appSync services always scope by
-- `where: { tenantId }` and run inside withTenantRLS(), so app-level scoping
-- carries isolation until the cutover (runtime role → hivegrid_app).
--
-- Forward-only (DoD 28). Inverse SQL as comment. Idempotent, DO-guarded (P3018).
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
-- =============================================================================
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY['DataConnection', 'AppSyncRun', 'AppSyncRunLog', 'AppSyncItem']
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
-- App is global → the restricted role only ever reads the catalog.
GRANT SELECT ON "App" TO hivegrid_app;
END
$$;
-- =============================================================================
-- Verify before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate · pnpm prisma migrate status
-- CI: prisma migrate deploy against an EMPTY DB (reproducible from scratch).
-- =============================================================================
@@ -0,0 +1,50 @@
-- R-P9a · Auftrag sub-areas — RLS ROLLOUT ARTIFACT (deferred)
--
-- Code-side access runs through withTenantRLS(); this block is applied during
-- the coordinated restricted-role cutover, not as an automatic schema diff.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'ProjektMitglied',
'ProjektTermin',
'Rechnung',
'ProjektChecklist',
'ProjektChecklistItem',
'AuftragPipelineStageConfig',
'AcceptanceFormTemplate',
'ProjectTemplate',
'ScheduleEntry',
'ScheduleConflict',
'AbnahmeProtokoll',
'AbnahmeSignatur',
'OfflineSyncMutation'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,62 @@
-- R-P12a Automation isolation artifact.
-- Companion to prisma/rls/tenant-isolation.sql. Enable during the merge
-- migration once the schema lands and the automation service has shipped.
--
-- Verification:
-- psql "$DIRECT_URL" -f prisma/rls/automation-isolation.sql
ALTER TABLE "AutomationRule" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationRule" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_rule" ON "AutomationRule";
CREATE POLICY "tenant_isolation_automation_rule" ON "AutomationRule"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationRuleStep" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationRuleStep" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_rule_step" ON "AutomationRuleStep";
CREATE POLICY "tenant_isolation_automation_rule_step" ON "AutomationRuleStep"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationExecution" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationExecution" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_execution" ON "AutomationExecution";
CREATE POLICY "tenant_isolation_automation_execution" ON "AutomationExecution"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationStepExecution" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationStepExecution" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_step_execution" ON "AutomationStepExecution";
CREATE POLICY "tenant_isolation_automation_step_execution" ON "AutomationStepExecution"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationCredential" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationCredential" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_credential" ON "AutomationCredential";
CREATE POLICY "tenant_isolation_automation_credential" ON "AutomationCredential"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationTemplate" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationTemplate" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_template" ON "AutomationTemplate";
CREATE POLICY "tenant_isolation_automation_template" ON "AutomationTemplate"
USING ("tenantId" IS NULL OR "tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" IS NULL OR "tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "AutomationTriggerMeter" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "AutomationTriggerMeter" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_automation_trigger_meter" ON "AutomationTriggerMeter";
CREATE POLICY "tenant_isolation_automation_trigger_meter" ON "AutomationTriggerMeter"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
@@ -0,0 +1,57 @@
-- AK-P16b · P16 Booking — HARD DOUBLE-BOOKING GUARD (deferred, NOT in the Prisma schema)
-- =============================================================================
-- The race-protection backstop for DoD 2: a PostgreSQL EXCLUDE USING gist
-- constraint that makes it physically impossible to persist two OVERLAPPING active
-- appointments for the SAME provider. This cannot be expressed in the Prisma schema
-- (Prisma has no exclusion-constraint primitive), so — like the RLS block — it
-- ships out-of-band: `psql -f` on the feature branch, folded into the merge
-- migration at main-merge (AD-21).
--
-- This is the second layer. The first layer is the application Serializable
-- transaction in BookingSubmitService that re-checks slot availability and returns
-- Klartext alternatives; this constraint guarantees correctness even under a lost
-- race / concurrent writer, surfacing as a unique-violation the submit path maps to
-- the same "slot just taken" Klartext.
--
-- `held` counts as occupying (a past appointment that took place still blocks its
-- slot for history integrity). `cancelled` / `no_show` / `rescheduled` free the slot.
--
-- Forward-only (DoD 28). Idempotent + DO-guarded (reproducible from an empty DB,
-- P3018-safe — order-independent except for the extension, which is IF NOT EXISTS).
--
-- Inverse SQL:
-- ALTER TABLE "Appointment" DROP CONSTRAINT IF EXISTS appointment_no_overlap;
-- -- (leave btree_gist installed; other modules may rely on it)
-- =============================================================================
-- gist over a scalar (providerUserId) + a range (tstzrange) needs the btree_gist
-- extension to put the equality column into the same gist index.
CREATE EXTENSION IF NOT EXISTS btree_gist;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'appointment_no_overlap'
) THEN
-- One active appointment per provider per time range. The half-open range
-- [startAt, endAt) means back-to-back appointments (end == next start) do NOT
-- conflict. Partial WHERE so only occupying statuses participate.
EXECUTE '
ALTER TABLE "Appointment"
ADD CONSTRAINT appointment_no_overlap
EXCLUDE USING gist (
"providerUserId" WITH =,
tstzrange("startAt", "endAt", ''[)'') WITH &&
)
WHERE (status IN (''scheduled'', ''held''))
';
END IF;
END
$$;
-- =============================================================================
-- Verify (after `prisma db push`):
-- psql "$DIRECT_URL" -f prisma/rls/booking-constraints.sql
-- -- then attempt two overlapping inserts for one providerUserId → 2nd raises
-- -- 23P01 exclusion_violation (mapped to Klartext "slot just taken").
-- =============================================================================
@@ -0,0 +1,91 @@
-- AK-P16b · P16 Booking — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to calendar-isolation.sql / email-isolation.sql / apps-engine-isolation.sql.
-- The AK-P16b tables + enums + indexes ship in the tracked merge migration
-- (prisma/migrations/<ts>_p16b_booking, created at main-merge per AD-21). What
-- lives in THIS file is the Row-Level-Security block, DELIBERATELY kept out of the
-- auto-migration path: enabling RLS + FORCE before every access sets the GUC would
-- make queries return ZERO rows, so activation is a coordinated cutover (R-P2b's
-- org-wide P5 RLS cutover), not a schema diff.
--
-- SCOPE: every AK-P16b table is ALWAYS tenant-scoped, so all get policies here:
-- BookingPage, BookingPageProvider, AvailabilityRule, AvailabilityException,
-- Appointment.
-- NOTE on per-user owner-filtering (bookings.read_own): RLS isolates by TENANT. The
-- stronger per-USER ownership rule (read_own users see only their own appointments,
-- providerUserId = self) is enforced in the service layer (bookingAccess.server.ts
-- owner-check + where: { providerUserId }).
--
-- CODE-SIDE PRECONDITIONS — DONE (AK-P16b):
-- 1. [x] Every AK-P16b web service runs each DB op for these tables inside
-- withTenantRLS() (booking submit/admin/lifecycle paths). The public
-- booking flow resolves the tenant from the {tenant} URL segment first.
-- The app-level scoping (where: { tenantId, ... }) carries isolation until cutover.
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser and
-- an empty-read trap for a non-superuser owner. The GRANTs below cover it.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all AK-P16b tenant-scoped booking tables ---------------
-- Pattern: "tenantId" = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet) set
-- — the policy then matches nothing (fail-closed).
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'BookingPage',
'BookingPageProvider',
'AvailabilityRule',
'AvailabilityException',
'Appointment'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,93 @@
-- AK-P16a · P16 Calendar-Sync (Google) — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to email-isolation.sql / apps-engine-isolation.sql / hr-isolation.sql.
-- The AK-P16a tables + enums + indexes ship in the tracked merge migration
-- (prisma/migrations/<ts>_p16a_calendar, created at main-merge per AD-21). What
-- lives in THIS file is the Row-Level-Security block, DELIBERATELY kept out of the
-- auto-migration path: enabling RLS + FORCE before every access sets the GUC would
-- make queries return ZERO rows, so activation is a coordinated cutover (R-P2b's
-- org-wide P5 RLS cutover), not a schema diff.
--
-- SCOPE: every AK-P16a table is ALWAYS tenant-scoped, so all get policies here:
-- CalendarConnection, CalendarEvent, CalendarEventMapping, CalendarSyncCursor,
-- CalendarWebhookEvent, CalendarConflict.
-- NOTE on per-user leak-protection (DoD 3): RLS isolates by TENANT. The stronger
-- per-USER ownership rule (external event contents are owner-only) is enforced in
-- the service layer (calendarAccess.server.ts owner-check + where: { userId }).
-- CalendarEventMapping has no userId column; its isolation is tenant-level here
-- and owner-level via its parent CalendarConnection in code.
--
-- CODE-SIDE PRECONDITIONS — DONE (AK-P16a):
-- 1. [x] Every AK-P16a web/worker service runs each DB op for these tables
-- inside withTenantRLS() (calendar sync/write/conflict paths).
-- The app-level scoping (where: { tenantId, userId }) carries isolation until
-- cutover.
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser and
-- an empty-read trap for a non-superuser owner. The GRANTs below cover it.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all AK-P16a tenant-scoped calendar tables --------------
-- Pattern: "tenantId" = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet) set
-- — the policy then matches nothing (fail-closed).
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'CalendarConnection',
'CalendarEvent',
'CalendarEventMapping',
'CalendarSyncCursor',
'CalendarWebhookEvent',
'CalendarConflict'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,87 @@
-- R-P6 · P6 CRM core — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to R-P2b's prisma/rls/tenant-isolation.sql, AK-P4a's file-isolation.sql
-- and AK-P4b's task-isolation.sql. The CRM tables + enums + indexes ship in the
-- tracked merge migration prisma/migrations/<ts>_p6_crm (forward-only, DoD 28).
-- What lives in THIS file is the Row-Level-Security block, DELIBERATELY kept out
-- of the auto-migration path (same stance as task/file-isolation.sql): turning RLS
-- on before every access sets the GUC would break the feature, so activation is a
-- coordinated cutover, not a schema diff.
--
-- WHY DEFERRED: enabling RLS + FORCE makes every CRM query WITHOUT `app.tenant_id`
-- return ZERO rows. Per R-P2b's rule a table may only be RLS-enabled once ALL its
-- accesses set the GUC. The app-level scoping (crmService/crmAccess run every DB op
-- inside withTenantRLS()) carries isolation meanwhile (DoD 1 hard path).
--
-- CODE-SIDE PRECONDITIONS — DONE (R-P6, 2026-06-29):
-- 1. [x] All CRM web services run every DB op inside withTenantRLS()
-- (apps/web/app/utils/integrations/crm/*.server.ts). The polymorphic
-- custom-field / tag / activity writes are tenant-scoped by construction.
-- 2. [ ] Worker maintenance crons (DSGVO archive sweeps) set the tenant GUC per
-- tenant — wired when P7/P8 add Lead/Projekt retention (no CRM cron yet).
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser.
-- The GRANTs below already cover that role for the CRM tables.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all tenant-scoped CRM tables --------------------------
-- Pattern: "tenantId" = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet)
-- set — the policy then matches nothing (fail-closed), and server-side scoping
-- stays the hard path until the cutover.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'Kontakt', 'KontaktRelation', 'KontaktEmail', 'KontaktTelefon', 'Adresse',
'CustomFieldDefinition', 'CustomFieldValue', 'Tag', 'TagAssignment'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,52 @@
-- R-P5 · per-tenant encryption keys — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to prisma/rls/tenant-isolation.sql (R-P2b) and the per-module RLS
-- blocks (file/task/hr). The TenantEncryptionKey table ships in the tracked merge
-- migration (created at main-merge per AD-21); the Row-Level-Security block lives
-- HERE, deliberately out of the auto-migration path: enabling RLS before every
-- access sets the GUC would break reads, so activation is a coordinated cutover.
--
-- WHY DEFERRED: with RLS + FORCE on, any query WITHOUT `app.tenant_id` returns
-- ZERO rows. The orchestration in packages/db/src/crypto/tenant-envelope.server.ts
-- always scopes by `where: { tenantId }`, so app-level scoping carries isolation
-- until the P5 cutover (R-P2b switches the runtime role to hivegrid_app,
-- NOSUPERUSER NOBYPASSRLS).
--
-- NOTE: the wrapped DEK is useless without the app master key, so even a full
-- table leak exposes no plaintext. RLS here is defence-in-depth + symmetry with
-- the other tenant tables, not the primary control.
--
-- Forward-only (DoD 28). Inverse SQL as comment. Idempotent, DO-guarded (P3018).
--
-- Inverse:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "TenantEncryptionKey" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "TenantEncryptionKey_tenant_isolation" ON "TenantEncryptionKey";
-- ALTER TABLE "TenantEncryptionKey" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "TenantEncryptionKey" DISABLE ROW LEVEL SECURITY;
-- =============================================================================
DO $$
BEGIN
ALTER TABLE "TenantEncryptionKey" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "TenantEncryptionKey" FORCE ROW LEVEL SECURITY;
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = 'TenantEncryptionKey'
AND policyname = 'TenantEncryptionKey_tenant_isolation'
) THEN
CREATE POLICY "TenantEncryptionKey_tenant_isolation" ON "TenantEncryptionKey"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
END IF;
GRANT SELECT, INSERT, UPDATE, DELETE ON "TenantEncryptionKey" TO hivegrid_app;
END
$$;
-- =============================================================================
-- Verify before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate · pnpm prisma migrate status
-- CI: prisma migrate deploy against an EMPTY DB (reproducible from scratch).
-- =============================================================================
@@ -0,0 +1,30 @@
-- R-P11b Dashboard isolation artifact.
-- Companion to prisma/rls/tenant-isolation.sql. Enable during the merge
-- migration once the schema lands and the dashboard service has shipped.
--
-- Verification:
-- psql "$DIRECT_URL" -f prisma/rls/dashboard-isolation.sql
ALTER TABLE "Dashboard" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "Dashboard" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_dashboard" ON "Dashboard";
CREATE POLICY "tenant_isolation_dashboard" ON "Dashboard"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "DashboardLayout" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "DashboardLayout" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_dashboard_layout" ON "DashboardLayout";
CREATE POLICY "tenant_isolation_dashboard_layout" ON "DashboardLayout"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
ALTER TABLE "WidgetInstance" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "WidgetInstance" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_widget_instance" ON "WidgetInstance";
CREATE POLICY "tenant_isolation_widget_instance" ON "WidgetInstance"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
@@ -0,0 +1,93 @@
-- VA-P23 · P23 Postfach-Sync (Gmail/Outlook) — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to calendar-isolation.sql / email-isolation.sql. The VA-P23 tables +
-- enums + indexes ship in the tracked merge migration (prisma/migrations/<ts>_
-- p23_email_inbox, created at main-merge per AD-21). What lives in THIS file is
-- the Row-Level-Security block, DELIBERATELY kept out of the auto-migration path:
-- enabling RLS + FORCE before every access sets the GUC would make queries return
-- ZERO rows, so activation is a coordinated cutover (R-P2b's org-wide P5 RLS
-- cutover), not a schema diff.
--
-- SCOPE: every VA-P23 table is ALWAYS tenant-scoped, so all get policies here:
-- EmailIntegrationMailbox, EmailIntegrationMessage, EmailIntegrationSyncCursor,
-- EmailIntegrationWebhookEvent.
-- NOTE on per-user visibility (M09 Block I): RLS isolates by TENANT. The stronger
-- per-USER rule (email.read_own sees only mailboxes with ownerUserId = self) is
-- enforced in the service layer (emailInboxAccess.server.ts + where clauses).
-- The webhook-ingest lookups (mailbox by subscription id / email address) run
-- WITHOUT a tenant GUC by design (provider pushes carry no tenant) — same
-- documented exception as the calendar webhook route.
--
-- CODE-SIDE PRECONDITIONS — DONE (VA-P23):
-- 1. [x] Every VA-P23 web/worker service runs each DB op for these tables
-- inside withTenantRLS() (sync/match/list/send paths), except the two
-- documented global webhook lookups above.
-- The app-level scoping (where: { tenantId, ownerUserId }) carries isolation
-- until cutover.
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser and
-- an empty-read trap for a non-superuser owner. The GRANTs below cover it.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all VA-P23 tenant-scoped email-inbox tables ------------
-- Pattern: "tenantId" = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet) set
-- — the policy then matches nothing (fail-closed).
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'EmailIntegrationMailbox',
'EmailIntegrationMessage',
'EmailIntegrationSyncCursor',
'EmailIntegrationWebhookEvent'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,94 @@
-- AK-P14a · P14 Email foundation — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to hr-isolation.sql / crypto-isolation.sql / task-isolation.sql. The
-- AK-P14a tables + enums + indexes ship in the tracked merge migration
-- (prisma/migrations/<ts>_p14a_email_foundation, created at main-merge per AD-21).
-- What lives in THIS file is the Row-Level-Security block, DELIBERATELY kept out
-- of the auto-migration path: enabling RLS + FORCE before every access sets the
-- GUC would make queries return ZERO rows, so activation is a coordinated cutover
-- (R-P2b's org-wide P5 RLS cutover), not a schema diff.
--
-- SCOPE: only the genuinely new, ALWAYS-tenant tables get policies here:
-- AK-P14a: TenantSendingDomain, EmailSuppressionList, EmailTemplate.
-- AK-P14b: RecipientSegment, SegmentSnapshotMember, CampaignVariant,
-- KontaktMarketingConsent, Unsubscribe.
-- The pre-existing boilerplate email tables (EmailSender / Campaign /
-- OutboundEmail) carry a NULLABLE tenantId (global/operator sender) and predate
-- this ticket; retrofitting RLS onto them is out of AK-P14a scope.
--
-- CODE-SIDE PRECONDITIONS — DONE (AK-P14a):
-- 1. [x] Every AK-P14a web/worker service runs every DB op for these tables
-- inside withTenantRLS() (emailDomainService / suppression paths).
-- The app-level scoping (where: { tenantId }) carries isolation until cutover.
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser and
-- an empty-read trap for a non-superuser owner. The GRANTs below cover it.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all AK-P14a tenant-scoped email tables ----------------
-- Pattern: "tenantId" = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet) set
-- — the policy then matches nothing (fail-closed).
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'TenantSendingDomain',
'EmailSuppressionList',
'EmailTemplate',
-- AK-P14b — email marketing tables (always tenant-scoped).
'RecipientSegment',
'SegmentSnapshotMember',
'CampaignVariant',
'KontaktMarketingConsent',
'Unsubscribe'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,35 @@
-- AK-P16c · Forms — RLS ROLLOUT ARTIFACT (deferred, NOT in auto-migration)
-- Code-side access runs through formsAccess + tenant scoped Prisma filters.
-- Enabling FORCE RLS is coordinated with the restricted runtime role cutover.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY['Form', 'FormField', 'FormSubmission', 'FormFile', 'FormAction', 'FormActionLog']
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,47 @@
-- AK-P21 · Privacy/GDPR — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- The AK-P21 GDPR tables ship in the phase merge migration per AD-21. This file
-- carries the coordinated RLS cutover block only. It is intentionally outside the
-- auto-migration path because FORCE RLS before every code path sets app.tenant_id
-- would make reads fail closed.
--
-- SCOPE:
-- Tenant-scoped: GdprExportJob, TenantDeletionRequest, AvvAcceptance.
-- Global catalog: Subprocessor (no tenantId), so no RLS policy here.
--
-- Forward-only. Inverse SQL:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
-- =============================================================================
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'GdprExportJob',
'TenantDeletionRequest',
'AvvAcceptance'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,115 @@
-- AK-P17a · P17 HR-Hub core — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to R-P2b's prisma/rls/tenant-isolation.sql, AK-P4a's
-- prisma/rls/file-isolation.sql and AK-P4b's prisma/rls/task-isolation.sql. The
-- HR tables + enums + indexes ship in the tracked merge migration
-- (prisma/migrations/<ts>_p17a_hr_core, created at main-merge per AD-21). What
-- lives in THIS file is the Row-Level-Security block, DELIBERATELY kept out of
-- the auto-migration path (same stance as task-isolation.sql): turning RLS on
-- before every access sets the GUC would break the feature, so activation is a
-- coordinated cutover, not a schema diff.
--
-- WHY DEFERRED: enabling RLS + FORCE makes every HR query WITHOUT `app.tenant_id`
-- return ZERO rows. Per R-P2b's rule a table may only be RLS-enabled once ALL its
-- accesses set the GUC. The app-level scoping (where: { tenantId }) carries
-- isolation meanwhile.
--
-- CODE-SIDE PRECONDITIONS — DONE (AK-P17a):
-- 1. [x] Every HR web service runs every DB op inside withTenantRLS()
-- (apps/web/app/utils/integrations/hr*Service.server.ts). Internal
-- composition reuses the active transaction client via *WithTx helpers;
-- functions never nest withTenantRLS(). The only unwrapped access is the
-- GLOBAL User lookup (display-name resolution): User is not
-- tenant-scoped, so it stays on the db singleton.
-- Proven by apps/web/app/utils/db/.server/rls-hr-isolation.integration.test.ts
-- (own-tenant only, 0 cross-tenant, 0 without context, WITH CHECK blocks
-- foreign insert).
--
-- WHAT REMAINS — "Teil B" = the org-wide P5 RLS cutover (Raffael / R-P2b):
-- a. Ship this block as its own forward-only migration.
-- b. Switch the runtime DB connection to the restricted role `hivegrid_app`
-- (NOSUPERUSER, NOBYPASSRLS); otherwise FORCE is a no-op for a superuser and
-- an empty-read trap for a non-superuser owner. The GRANTs below already
-- cover that role for the HR tables.
-- c. Staging cutover + live cross-tenant 404 verification.
--
-- Forward-only (DoD 28). Inverse SQL as comment per block. Order-dependent DDL is
-- DO-guarded (P3018 protection: reproducible from an empty DB). Idempotent.
-- =============================================================================
-- Row-level security on all tenant-scoped HR tables ---------------------------
-- Pattern: tenant_id = current_setting('app.tenant_id', true). The second
-- argument `true` returns NULL instead of erroring when the GUC is not (yet) set
-- — the policy then matches nothing (fail-closed), and server-side scoping stays
-- the hard path until the cutover.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'HrEmployeeProfile',
'HrLocation',
'HrEmployeeDocument',
'HrResource',
'HrQuickLink',
'EmployeePasswordSafeVault',
'EmployeePasswordSafeEntry',
'EmployeePasswordSafeAccess',
-- AK-P17b workflow tables
'EmployeeVacationRequest',
'EmployeeSickLeaveReport',
'HrAnnouncement',
'HrAnnouncementRead',
'HrAnnouncementReaction',
'HrAnnouncementComment',
'EmployeePayslip',
'EmployeeUploadReminder',
'EmployeeUploadReminderDispatch',
'HrRequestTemplate',
'HrRequest',
'HrSurvey',
'HrSurveyItem',
'HrSurveySubmission'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
-- FORCE so the table owner is subject to the policies too (otherwise the
-- owner silently bypasses RLS).
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
-- The restricted app role (R-P2b's hivegrid_app, NOBYPASSRLS) needs table
-- privileges to reach the rows the policy then filters.
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
-- =============================================================================
-- Verify green before the cutover migration (AGENTS.md §Prisma):
-- pnpm prisma validate
-- pnpm prisma migrate status
-- CI: `prisma migrate deploy` against an EMPTY DB (reproducible from scratch,
-- no order dependency on Raffael's P2 migration).
-- Coordination: align ordering with R-P2b — P2 ships withTenantRLS()
-- (SET LOCAL app.tenant_id); without a tenant context the policies match nothing
-- (no data leak, just empty results) until the runtime role is hivegrid_app.
-- =============================================================================
@@ -0,0 +1,36 @@
-- R-P7 · Lead-Inbox — RLS ROLLOUT ARTIFACT (deferred, NOT in auto-migration)
-- Mirrors the CRM/task/file isolation artifacts. Code-side access already runs
-- inside withTenantRLS(); enabling FORCE RLS is coordinated with the restricted
-- runtime role cutover.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY['InboxLead', 'LeadSource', 'LeadAntiSpamConfig']
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,48 @@
-- R-P8a · Projekt/Pipeline core — RLS ROLLOUT ARTIFACT (deferred)
--
-- Code-side access runs through withTenantRLS(); this block is applied during
-- the coordinated restricted-role cutover, not as an automatic schema diff.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'HiveNumberSeq',
'Pipeline',
'PipelineStage',
'PipelineAccess',
'PipelineFieldConfig',
'PipelineFieldVisibility',
'LostReason',
'Projekt',
'ProjektStageChange',
'PipelineAggregateSnapshot',
'ProjektKontakt'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,40 @@
-- VR-P22b · Public API/Webhooks — RLS ROLLOUT ARTIFACT (deferred, NOT in auto-migration)
-- Runtime code scopes by tenantId today; enabling FORCE RLS is coordinated with
-- the restricted runtime role cutover.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'PublicIncomingWebhookEndpoint',
'PublicWebhookIngestionLog',
'PublicWebhookSubscription',
'PublicWebhookDeliveryLog'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;
@@ -0,0 +1,23 @@
-- R-P11a Global Search isolation artifact.
-- Companion to prisma/rls/tenant-isolation.sql. These tables are tenant-scoped
-- metadata around Meilisearch documents and recent searches. Enable during the
-- merge migration once the schema lands.
--
-- Verification:
-- psql "$DIRECT_URL" -f prisma/rls/search-isolation.sql
ALTER TABLE "SearchIndexEntry" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "SearchIndexEntry" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_search_index_entry" ON "SearchIndexEntry";
CREATE POLICY "tenant_isolation_search_index_entry" ON "SearchIndexEntry"
USING ("tenantId" = current_setting('app.current_tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.current_tenant_id', true));
ALTER TABLE "RecentSearch" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "RecentSearch" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "tenant_isolation_recent_search" ON "RecentSearch";
CREATE POLICY "tenant_isolation_recent_search" ON "RecentSearch"
USING ("tenantId" = current_setting('app.current_tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.current_tenant_id', true));
@@ -0,0 +1,28 @@
-- AK-P16d signature tenant isolation. Activated in the merge migration together
-- with the other module RLS blocks; feature branches only ship the policy source
-- per AD-21.
ALTER TABLE "SignatureProviderConnection" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "ProjektSignatureDocument" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "ProjektSignatureSigner" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "SignatureEvent" ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS signature_provider_connection_tenant_isolation ON "SignatureProviderConnection";
CREATE POLICY signature_provider_connection_tenant_isolation ON "SignatureProviderConnection"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
DROP POLICY IF EXISTS projekt_signature_document_tenant_isolation ON "ProjektSignatureDocument";
CREATE POLICY projekt_signature_document_tenant_isolation ON "ProjektSignatureDocument"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
DROP POLICY IF EXISTS projekt_signature_signer_tenant_isolation ON "ProjektSignatureSigner";
CREATE POLICY projekt_signature_signer_tenant_isolation ON "ProjektSignatureSigner"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
DROP POLICY IF EXISTS signature_event_tenant_isolation ON "SignatureEvent";
CREATE POLICY signature_event_tenant_isolation ON "SignatureEvent"
USING ("tenantId" = current_setting('app.tenant_id', true))
WITH CHECK ("tenantId" = current_setting('app.tenant_id', true));
@@ -0,0 +1,47 @@
-- AK-P20 · Billing + Onboarding — RLS ROLLOUT ARTIFACT (deferred, NOT in the auto-migration)
-- =============================================================================
-- Companion to R-P2b's prisma/rls/tenant-isolation.sql. This file documents the
-- RLS block for the tenant-scoped tables introduced or tightened by AK-P20.
-- Activation is deferred until all runtime paths set app.tenant_id via
-- withTenantRLS(), matching the existing module rollout pattern.
--
-- Inverse per table:
-- REVOKE SELECT, INSERT, UPDATE, DELETE ON "<tbl>" FROM hivegrid_app;
-- DROP POLICY IF EXISTS "<tbl>_tenant_isolation" ON "<tbl>";
-- ALTER TABLE "<tbl>" NO FORCE ROW LEVEL SECURITY;
-- ALTER TABLE "<tbl>" DISABLE ROW LEVEL SECURITY;
DO $$
DECLARE
tbl text;
BEGIN
FOREACH tbl IN ARRAY ARRAY[
'TenantSubscription',
'TenantSubscriptionUsageRecord',
'TenantFeatureOverride',
'TenantProductConfiguration',
'Credit',
'OnboardingSession',
'OnboardingDemoProvisioning'
]
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
IF NOT EXISTS (
SELECT 1 FROM pg_policies
WHERE schemaname = current_schema()
AND tablename = tbl
AND policyname = tbl || '_tenant_isolation'
) THEN
EXECUTE format(
'CREATE POLICY %I ON %I USING ("tenantId" = current_setting(''app.tenant_id'', true)) WITH CHECK ("tenantId" = current_setting(''app.tenant_id'', true));',
tbl || '_tenant_isolation', tbl
);
END IF;
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I TO hivegrid_app;', tbl);
END LOOP;
END
$$;