"""Live PostgreSQL Row-Level Security (RLS) & Immutability Integration Test. Validates FR-TENANTSECURITYAUDIT-001 (UC-017) and FR-TENANTSECURITYAUDIT-003 (UC-017) directly against a running PostgreSQL 17 database instance with active RLS policies and append-only rules. """ import os import unittest import uuid import psycopg2 from psycopg2 import errors DB_URL = os.getenv( "DATABASE_URL", "postgresql://atb:atb-local-only-change-me@atb-local-postgres-1:5432/atb" ) class TestPostgreSQLLiveRLS(unittest.TestCase): """Integration test suite executing real DDL/DML against live PostgreSQL.""" @classmethod def setUpClass(cls): # Create non-superuser role 'atb_app_user' to verify strict RLS enforcement # (PostgreSQL superusers / table owners bypass RLS unless FORCE ROW LEVEL SECURITY is set) admin_conn = psycopg2.connect(DB_URL) admin_conn.autocommit = True cur = admin_conn.cursor() cur.execute(""" DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'atb_app_user') THEN CREATE ROLE atb_app_user WITH LOGIN PASSWORD 'atb_app_password'; END IF; END $$; """) cur.execute("GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO atb_app_user;") cur.execute("GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO atb_app_user;") # Seed test tenants cur.execute(""" INSERT INTO tenants (tenant_id, business_name, legal_identifier, contact_email, primary_mandi, status) VALUES ('tenant-alpha-live', 'Alpha Live Agro', '27AAACA1234A1Z5', 'ops@alpha.com', 'APMC-PUN-01', 'ACTIVE'), ('tenant-beta-live', 'Beta Live Agro', '27BBBCB5678B1Z6', 'ops@beta.com', 'APMC-NSK-01', 'ACTIVE') ON CONFLICT (tenant_id) DO NOTHING; """) admin_conn.close() def get_app_connection(self): """Returns connection authenticated as the application role 'atb_app_user'.""" # Parse connection details and substitute user/password base_url = DB_URL.split("@")[-1] app_url = f"postgresql://atb_app_user:atb_app_password@{base_url}" return psycopg2.connect(app_url) def setUp(self): # Clean up test rows admin_conn = psycopg2.connect(DB_URL) admin_conn.autocommit = True cur = admin_conn.cursor() cur.execute("DELETE FROM tenant_memberships WHERE tenant_id IN ('tenant-alpha-live', 'tenant-beta-live');") admin_conn.close() def test_live_rls_query_without_context_returns_zero_rows(self): """TC-TENANT-017-01: Live RLS - Querying without SET LOCAL yields 0 rows.""" # Seed memberships via admin connection admin_conn = psycopg2.connect(DB_URL) admin_conn.autocommit = True cur = admin_conn.cursor() cur.execute(""" INSERT INTO tenant_memberships (membership_id, tenant_id, user_id, email, role, status) VALUES ('mem_live_a1', 'tenant-alpha-live', 'usr_a1', 'a1@alpha.com', 'Mandi Buyer', 'ACTIVE'); """) admin_conn.close() # Connect as application user app_conn = self.get_app_connection() with app_conn.cursor() as cur: cur.execute("SELECT * FROM tenant_memberships;") rows = cur.fetchall() self.assertEqual(len(rows), 0, "Query without tenant context must return zero rows under live RLS.") app_conn.close() def test_live_rls_scoped_query_sees_only_active_tenant(self): """TC-TENANT-017-01: Live RLS - Context 'tenant-alpha-live' sees only Alpha rows.""" admin_conn = psycopg2.connect(DB_URL) admin_conn.autocommit = True cur = admin_conn.cursor() cur.execute(""" INSERT INTO tenant_memberships (membership_id, tenant_id, user_id, email, role, status) VALUES ('mem_live_a2', 'tenant-alpha-live', 'usr_a2', 'a2@alpha.com', 'Mandi Buyer', 'ACTIVE'), ('mem_live_b1', 'tenant-beta-live', 'usr_b1', 'b1@beta.com', 'Quality Officer', 'ACTIVE'); """) admin_conn.close() app_conn = self.get_app_connection() with app_conn: with app_conn.cursor() as cur: # Set transaction-local tenant context cur.execute("SELECT set_config('app.current_tenant_id', 'tenant-alpha-live', true);") cur.execute("SELECT membership_id, tenant_id FROM tenant_memberships;") rows = cur.fetchall() self.assertEqual(len(rows), 1) self.assertEqual(rows[0][0], "mem_live_a2") self.assertEqual(rows[0][1], "tenant-alpha-live") app_conn.close() def test_live_rls_with_check_blocks_cross_tenant_insert(self): """TC-TENANT-017-02: Live RLS - Inserting Beta row under Alpha context raises InsufficientPrivilege.""" app_conn = self.get_app_connection() with app_conn: with app_conn.cursor() as cur: cur.execute("SELECT set_config('app.current_tenant_id', 'tenant-alpha-live', true);") with self.assertRaises(errors.InsufficientPrivilege): cur.execute(""" INSERT INTO tenant_memberships (membership_id, tenant_id, user_id, email, role, status) VALUES ('mem_illicit', 'tenant-beta-live', 'usr_bad', 'bad@beta.com', 'Partner / MD', 'ACTIVE'); """) app_conn.close() def test_live_audit_immutability_blocks_updates_and_deletes(self): """TC-TENANT-017-04: Live Immutability - UPDATE and DELETE on audit logs do nothing.""" app_conn = self.get_app_connection() audit_id = f"aud_live_{uuid.uuid4().hex[:8]}" with app_conn: with app_conn.cursor() as cur: cur.execute("SELECT set_config('app.current_tenant_id', 'tenant-alpha-live', true);") # Insert audit row cur.execute(f""" INSERT INTO transaction_audit_logs (audit_id, tenant_id, actor_id, entity_type, entity_id, action) VALUES ('{audit_id}', 'tenant-alpha-live', 'usr_a', 'Contract', 'cnt_01', 'CREATE'); """) # Attempt UPDATE -> intercepted by DO INSTEAD NOTHING rule cur.execute(f""" UPDATE transaction_audit_logs SET action = 'TAMPERED' WHERE audit_id = '{audit_id}'; """) # Verify action was NOT modified cur.execute(f"SELECT action FROM transaction_audit_logs WHERE audit_id = '{audit_id}';") row = cur.fetchone() self.assertEqual(row[0], "CREATE", "Audit row must be immutable (UPDATE prohibited).") # Attempt DELETE -> intercepted by DO INSTEAD NOTHING rule cur.execute(f"DELETE FROM transaction_audit_logs WHERE audit_id = '{audit_id}';") # Verify row still exists cur.execute(f"SELECT COUNT(*) FROM transaction_audit_logs WHERE audit_id = '{audit_id}';") count = cur.fetchone()[0] self.assertEqual(count, 1, "Audit row must be immutable (DELETE prohibited).") app_conn.close() if __name__ == "__main__": unittest.main()