Write PostgreSQL Migration for RLS Policies
epic-bufdir-data-aggregation-foundation-task-002 — Implement the PostgreSQL migration file that creates and enables Row Level Security policies on all relevant tables (activities, user_stories, components, etc.). Include USING and WITH CHECK clauses tied to app.current_org_id, grant policies per role (peer_mentor, coordinator, admin), and include a rollback strategy. Validate that no SELECT, INSERT, UPDATE, or DELETE can cross organization boundaries.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 1 - 540 tasks
Can start after Tier 0 completes
Implementation Notes
Structure the migration in sections: (1) Index creation for org_id columns, (2) Enable RLS per table, (3) Create policies per table per operation per role. Use a DO $$ BEGIN ... END $$ block with IF NOT EXISTS checks for idempotency. Prefer explicit policy names following a convention: {table}_{operation}_{role}_policy (e.g., activities_select_peer_mentor_policy).
For tables that legitimately need cross-org reads (e.g., a global configuration table), explicitly document the exception with a comment explaining why RLS is not applied or uses a permissive policy. Do not attempt to add RLS to Supabase internal tables (auth.users, storage.objects) — only to public schema tables. The rollback file should be a DROP POLICY IF EXISTS for each policy plus DISABLE ROW LEVEL SECURITY per table. Coordinate with the Edge Functions team to ensure SET LOCAL app.current_org_id is called before any service-role queries that touch these tables.
Testing Requirements
SQL-level verification tests (run via psql against staging): (1) Apply migration, log in as peer_mentor JWT for org_A, SELECT from activities — confirm only org_A rows returned, (2) Attempt INSERT into activities with org_id = org_B UUID as peer_mentor of org_A — confirm permission denied, (3) Attempt UPDATE on a contact row belonging to org_B as coordinator of org_A — confirm 0 rows affected (RLS silently filters), (4) Log in as admin of org_A — confirm full CRUD access to org_A rows and zero access to org_B rows, (5) Apply rollback, confirm RLS disabled (SELECT across all orgs succeeds), (6) Re-apply migration, confirm policies re-created correctly. All tests documented in a test script file alongside the migration.
Supabase RLS policies may not propagate correctly into RPC function execution context, causing org-scoping predicates to be silently ignored when the function is invoked with service_role key. This could lead to cross-org data exposure in production without any obvious error.
Mitigation & Contingency
Mitigation: Invoke all RPCs using the anon/authenticated key rather than service_role, write explicit WHERE org_id = auth.uid()::org_id predicates inside the RPC body as a secondary control, and include automated cross-org leakage tests in the CI pipeline from day one.
Contingency: If RLS bypass is discovered post-deployment, immediately revoke service_role usage in all aggregation paths and hotfix with explicit org_id parameters passed as function arguments validated server-side.
Bufdir may update its official reporting category taxonomy between the mapping configuration being defined and the annual submission deadline. If the ActivityCategoryMappingConfig is compiled as a static Dart constant, it cannot be updated without an app release, potentially causing mapping failures that block submission.
Mitigation & Contingency
Mitigation: Store the mapping as a remote-configurable table (bufdir_category_mappings) in Supabase with a version field rather than as a hardcoded Dart constant. Fetch the current mapping at aggregation time so updates can be pushed without a new app release.
Contingency: If a mapping mismatch is detected during an active reporting cycle, coordinators can be temporarily directed to the manual Excel fallback while an emergency mapping update is pushed to the Supabase table.
For large organisations like NHF with 1,400 local chapters and potentially tens of thousands of activity records per reporting period, the Supabase RPC aggregation query may exceed the default PostgREST statement timeout, causing the aggregation to fail with a 503 error.
Mitigation & Contingency
Mitigation: Add partial indexes on (organization_id, created_at) and (organization_id, activity_type_id) to the activities table before writing the RPC. Profile the query plan against a realistic fixture of 50,000 records during development and increase the statement_timeout setting for the RPC role if needed.
Contingency: Implement chunked aggregation fallback: split the period into monthly sub-ranges and aggregate each chunk client-side, merging results with UNION-style Dart logic before assembling the final payload.