161 lines
6.9 KiB
TypeScript
161 lines
6.9 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import pg from "pg";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { SEEDED_TABLES, seedHousehold, seedIngredient } from "./fixture";
|
|
|
|
// Der Test mit zwei Haushalten (CLAUDE.md, Regel 3; Konzept „Datenschutz“):
|
|
// Er legt zwei Haushalte mit Zeilen in **jeder** Tabelle an und liest jede
|
|
// Tabelle gegen. Läuft als Eigentümerin der Tabellen — genau wie die App auf
|
|
// der Box. Ohne FORCE sähe diese Rolle alles, und der Test bräche.
|
|
const url = process.env.TEST_DATABASE_URL;
|
|
|
|
// Tabellen ohne household_id, je mit Grund.
|
|
const GLOBAL = {
|
|
households: "ist selbst der Haushalt (id)",
|
|
instance: "die Box, eine Zeile",
|
|
ingredients: "kanonische Zutaten für alle, schreibbar nur in Migrationen",
|
|
auth_challenges: "vor der Anmeldung",
|
|
auth_attempts: "vor der Anmeldung",
|
|
schema_migrations: "gehört zur Datenbank",
|
|
starter_dishes: "Vorlage für alle (db/seed), Haushalte übernehmen eine Kopie",
|
|
starter_dish_ingredients: "Vorlage für alle",
|
|
starter_dish_steps: "Vorlage für alle",
|
|
store_chains: "Vorlage für alle",
|
|
chain_aisles: "Vorlage für alle",
|
|
default_prices: "Richtpreise für alle, nur lesbar",
|
|
};
|
|
|
|
describe.skipIf(!url)("row level security", () => {
|
|
const client = new pg.Client({ connectionString: url });
|
|
const a = randomUUID();
|
|
const b = randomUUID();
|
|
let dishOfA = "";
|
|
let tables: string[] = [];
|
|
|
|
async function as<T>(household: string | null, fn: () => Promise<T>): Promise<T> {
|
|
await client.query("begin");
|
|
try {
|
|
if (household) await client.query("select set_config('app.household_id', $1, true)", [household]);
|
|
return await fn();
|
|
} finally {
|
|
await client.query("rollback");
|
|
}
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
await client.connect();
|
|
const ingredient = await seedIngredient(client);
|
|
dishOfA = (await seedHousehold(client, a, ingredient)).dish;
|
|
await seedHousehold(client, b, ingredient);
|
|
tables = (
|
|
await client.query<{ table_name: string }>(
|
|
`select table_name from information_schema.columns
|
|
where table_schema = 'public' and column_name = 'household_id'
|
|
and table_name in (select tablename from pg_tables where schemaname = 'public')
|
|
order by 1`,
|
|
)
|
|
).rows.map((r) => r.table_name);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await client.end();
|
|
});
|
|
|
|
it("every table forces RLS", async () => {
|
|
const { rows } = await client.query(`
|
|
select c.relname, c.relrowsecurity, c.relforcerowsecurity
|
|
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
where n.nspname = 'public' and c.relkind = 'r' and c.relname <> 'schema_migrations'`);
|
|
expect(rows.length).toBeGreaterThan(20);
|
|
for (const r of rows) expect([r.relname, r.relrowsecurity, r.relforcerowsecurity]).toEqual([r.relname, true, true]);
|
|
});
|
|
|
|
it("every table except the global ones carries household_id", async () => {
|
|
const all = (await client.query<{ tablename: string }>("select tablename from pg_tables where schemaname = 'public'")).rows.map(
|
|
(r) => r.tablename,
|
|
);
|
|
expect(all.filter((t) => !tables.includes(t) && !(t in GLOBAL)).sort()).toEqual([]);
|
|
});
|
|
|
|
it("the fixture fills every household table", () => {
|
|
expect([...tables].sort()).toEqual(SEEDED_TABLES.filter((t) => t !== "households").sort());
|
|
});
|
|
|
|
it("each household sees only its own rows, in every table", async () => {
|
|
for (const own of [a, b]) {
|
|
for (const table of tables) {
|
|
const { rows } = await as(own, () =>
|
|
client.query(
|
|
`select count(*) filter (where household_id = $1)::int as own, count(*) filter (where household_id <> $1)::int as other from ${table}`,
|
|
[own],
|
|
),
|
|
);
|
|
expect([table, rows[0].other]).toEqual([table, 0]);
|
|
expect([table, rows[0].own > 0]).toEqual([table, true]);
|
|
}
|
|
const h = await as(own, () => client.query("select id from households"));
|
|
expect(h.rows.map((r) => r.id)).toEqual([own]);
|
|
}
|
|
});
|
|
|
|
it("without a household nothing is visible", async () => {
|
|
for (const table of [...tables, "households"]) {
|
|
// ingredients mischt globale Zeilen (für alle sichtbar) und eigene je Haushalt (26.11.38).
|
|
const where = table === "ingredients" ? "where household_id is not null" : "";
|
|
const { rows } = await as(null, () => client.query(`select count(*)::int as n from ${table} ${where}`));
|
|
expect([table, rows[0].n]).toEqual([table, 0]);
|
|
}
|
|
});
|
|
|
|
it("a household cannot change or delete another's rows", async () => {
|
|
for (const table of tables) {
|
|
const removed = await as(a, () => client.query(`delete from ${table} where household_id = $1`, [b]));
|
|
expect([table, removed.rowCount]).toEqual([table, 0]);
|
|
}
|
|
await expect(as(a, () => client.query("insert into dishes (household_id, title) values ($1, 'X')", [b]))).rejects.toThrow(
|
|
/row-level security/,
|
|
);
|
|
await expect(as(a, () => client.query("insert into households (id, name) values ($1, 'C')", [randomUUID()]))).rejects.toThrow(
|
|
/row-level security/,
|
|
);
|
|
});
|
|
|
|
it("a row cannot point at another household's dish (paired foreign key)", async () => {
|
|
const { rows } = await as(b, () => client.query("select id from ingredients limit 1"));
|
|
await expect(
|
|
as(b, () =>
|
|
client.query(
|
|
"insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit) values ($1, $2, $3, 1, 'g')",
|
|
[b, dishOfA, rows[0].id],
|
|
),
|
|
),
|
|
).rejects.toThrow(/foreign key/);
|
|
});
|
|
|
|
it("global ingredients are readable, but writable only in migrations", async () => {
|
|
const { rows } = await as(a, () => client.query("select count(*)::int as n from ingredients"));
|
|
expect(rows[0].n).toBeGreaterThan(0);
|
|
await expect(
|
|
as(a, () => client.query(`insert into ingredients (key, category, default_unit) values ('x_${Date.now()}', 'x', 'g')`)),
|
|
).rejects.toThrow(/row-level security/);
|
|
});
|
|
|
|
it("popularity view respects the household", async () => {
|
|
const { rows } = await as(a, () => client.query("select household_id, share_up from dish_popularity"));
|
|
expect(rows.every((r) => r.household_id === a)).toBe(true);
|
|
expect(rows.find((r) => Number(r.share_up) === 1)).toBeTruthy();
|
|
});
|
|
|
|
it("the sign-in bypass (app.auth) is limited to the sign-in tables", async () => {
|
|
// Nur diese Tabellen darf withAuth() über Haushalte hinweg lesen. Eine
|
|
// neue Fachtabelle mit app_auth() in der Policy wäre ein Leck.
|
|
const { rows } = await client.query(
|
|
"select distinct tablename from pg_policies where schemaname = 'public' and qual like '%app_auth()%' order by 1",
|
|
);
|
|
expect(rows.map((r) => r.tablename)).toEqual([
|
|
// mail_tokens seit 26.11.40: der Mail-Link findet den Haushalt erst über die Adresse.
|
|
"auth_attempts", "auth_challenges", "households", "instance", "invitations", "kid_devices", "mail_tokens", "members", "passkeys", "sessions",
|
|
]);
|
|
});
|
|
});
|