krona-staff/tests/integration/tenant-isolation.test.ts

61 lines
2.5 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { Database } from '../../src/infrastructure/database.js';
import { newUlid, parseUlid } from '../../src/core/ids.js';
const connectionString = process.env.DATABASE_TEST_URL;
const describeDatabase = connectionString ? describe : describe.skip;
describeDatabase('PostgreSQL tenant isolation', () => {
const database = new Database(connectionString!);
const tenantA = parseUlid('01J0000000000000000000000A');
const tenantB = parseUlid('01J0000000000000000000000B');
const actorA = parseUlid('01J0000000000000000000001A');
const actorB = parseUlid('01J0000000000000000000001B');
const eventId = newUlid();
beforeAll(async () => {
const role = await database.pool.query(
'SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user',
);
expect(role.rows[0]).toEqual({ rolsuper: false, rolbypassrls: false });
});
afterAll(async () => {
await database.tenantTransaction(tenantA, actorA, async (client) => {
await client.query('DELETE FROM staff_outbox WHERE id = $1', [eventId]);
});
await database.close();
});
it('prevents reads and writes across two tenants', async () => {
await database.tenantTransaction(tenantA, actorA, async (client) => {
await client.query(
`INSERT INTO staff_outbox
(id, tenant_id, event_type, event_version, subject_type, subject_id, actor_type, actor_id, payload, correlation_id, occurred_at)
VALUES ($1, $2, 'staff.Test', 1, 'staff.Employee', $3, 'user', $4, '{}'::jsonb, $5, now())`,
[eventId, tenantA, newUlid(), actorA, newUlid()],
);
});
const visibleToA = await database.tenantTransaction(tenantA, actorA, (client) =>
client.query('SELECT id FROM staff_outbox WHERE id = $1', [eventId]),
);
expect(visibleToA.rowCount).toBe(1);
const visibleToB = await database.tenantTransaction(tenantB, actorB, (client) =>
client.query('SELECT id FROM staff_outbox WHERE id = $1', [eventId]),
);
expect(visibleToB.rowCount).toBe(0);
await expect(
database.tenantTransaction(tenantB, actorB, (client) =>
client.query(
`INSERT INTO staff_outbox
(id, tenant_id, event_type, event_version, subject_type, subject_id, actor_type, actor_id, payload, correlation_id, occurred_at)
VALUES ($1, $2, 'staff.Test', 1, 'staff.Employee', $3, 'user', $4, '{}'::jsonb, $5, now())`,
[newUlid(), tenantA, newUlid(), actorB, newUlid()],
),
),
).rejects.toThrow();
});
});