test(sync): read-only production probe after each companion deploy #194

Merged
maximus merged 2 commits from issue-176-prod-probe into master 2026-11-08 15:35:59 +00:00
3 changed files with 404 additions and 0 deletions

View file

@ -161,6 +161,17 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Le site se déploie à la main (rsync des sources puis `docker compose up --build` sur le VPS) : le merge ne déploie pas, et la PR qui exige un déploiement le dit, avec ses étapes. — `STATE.md` (« Companion web »)
- Les secrets (`LOGTO_APP_SECRET`, `LOGTO_COOKIE_SECRET`, `DATABASE_URL`) vivent dans l'environnement du conteneur, jamais dans le dépôt ; `web/.env.template` ne porte que des noms et des valeurs publiques. — `web/.env.template`, `CLAUDE.md` global « Securite »
- L'image tourne sous l'utilisateur `nextjs` (uid 1001) et embarque `src/db/migrations`, lues au démarrage. — `web/Dockerfile`, `web/server.ts`
- Chaque déploiement du companion est suivi de la sonde `web/scripts/probe.sql`, en lecture seule sur la base de prod : elle compte les dérives que les versions passées ont laissées dans les données (Inbox en double, liens vers une ligne supprimée, sous-tâches orphelines, lignes rattachées à un autre compte). Le nom du conteneur PostgreSQL, l'utilisateur et la base se lisent dans `/data/simpl-liste-web/docker-compose.yml` sur le VPS, sans jamais être affichés ni copiés dans une issue ou une PR. La connexion passe par le socket local du conteneur : ni `DATABASE_URL` ni mot de passe en argument. — #176
```bash
ssh ubuntu@vps-b0826277.tail3c811f.ts.net \
"docker exec -i -e PGOPTIONS='-c default_transaction_read_only=on -c statement_timeout=10s' <conteneur postgres> psql -v ON_ERROR_STOP=1 -X -At -U <utilisateur> -d <base>" \
< web/scripts/probe.sql
```
- Lecture du résultat : une ligne `controle|nombre` par contrôle, dix lignes, des noms et des nombres seulement ; les lignes `BEGIN` et `ROLLBACK` que psql affiche autour ne sont pas des contrôles. L'en-tête de `probe.sql` décrit chaque contrôle et sa gravité : `tache_liste_autre_compte`, `sous_tache_parent_autre_compte` et `lien_etiquette_autre_compte` sont critiques (fuite possible entre comptes), les autres sont des anomalies. `lien_tache_supprimee` n'est pas nul en temps normal : la suppression d'une tâche garde ses liens, il se lit par rapport à la base de départ postée en commentaire de #176. Une erreur, ou moins de dix lignes, veut dire que la sonde n'a pas tourné, pas que la base est saine.
- Suite d'une anomalie : la session explique à Max chaque compteur non nul (ce qu'il mesure, la cause probable, la gravité), puis un échange de questions et réponses décide s'il faut ouvrir une issue. Pas d'issue automatique, pas de retour arrière du déploiement.
- Une PR qui modifie `probe.sql` garde le contrat que vérifie `web/src/test/probe.test.ts` : une transaction `READ ONLY` ouverte en premier, `ROLLBACK` en dernière instruction, aucune méta-commande psql, aucun `COMMIT`, `END` ni `READ WRITE`, et une sortie limitée à `controle` et `nombre`.
### i18n

111
web/scripts/probe.sql Normal file
View file

@ -0,0 +1,111 @@
-- Read-only production probe of the companion database (#176).
--
-- Run after each companion deploy (see REVIEW.md, "Déploiement web"). Each
-- control returns one row `controle|nombre`: a control name and a count, never
-- an account id, a title, a name or any content. "Active" means
-- `deleted_at IS NULL` (lists, tasks and tags are soft-deleted).
--
-- The whole script runs in a READ ONLY transaction and ends with ROLLBACK.
-- Keep it that way: no psql meta-command, no transaction end other than the
-- final ROLLBACK, no switch back to read-write. web/src/test/probe.test.ts
-- checks this file's text and runs it against the companion migrations.
--
-- Integrity:
-- 1. inbox_doublon accounts with more than one active Inbox. anomaly
-- 2. lien_etiquette_supprimee sl_task_tags links from an active task to a
-- deleted tag. anomaly
-- 3. lien_tache_supprimee sl_task_tags links from a deleted task. anomaly
-- GET /api/sync does not filter them: it returns the links of every task
-- updated since `since`, soft-deleted tasks included, and a task delete
-- does not remove its links. So the count grows with every deleted tagged
-- task; read it against the previous run's baseline.
-- 4. tache_liste_supprimee active tasks whose list is deleted. anomaly
-- 5. sous_tache_parent_absent active tasks whose parent_id matches no row
-- (parent_id has no foreign key). anomaly
-- 6. sous_tache_parent_supprime active tasks whose parent is deleted. anomaly
--
-- Isolation and consistency:
-- 7. tache_liste_autre_compte tasks whose list belongs to another user_id. CRITICAL
-- 8. sous_tache_parent_autre_compte tasks whose parent belongs to another user_id. CRITICAL
-- 9. lien_etiquette_autre_compte sl_task_tags links whose task and tag have
-- different user_id values. CRITICAL
-- 10. compte_sans_inbox accounts with active tasks and no active Inbox. anomaly
--
-- Foreign keys with ON DELETE CASCADE make a link to a missing list, task or
-- tag impossible; only parent_id can point to a missing row.
BEGIN TRANSACTION READ ONLY;
SELECT controle, nombre FROM (
SELECT 1 AS rang, 'inbox_doublon' AS controle, count(*)::int AS nombre
FROM (
SELECT l.user_id
FROM sl_lists l
WHERE l.is_inbox AND l.deleted_at IS NULL
GROUP BY l.user_id
HAVING count(*) > 1
) d
UNION ALL
SELECT 2, 'lien_etiquette_supprimee', count(*)::int
FROM sl_task_tags tt
JOIN sl_tasks t ON t.id = tt.task_id
JOIN sl_tags g ON g.id = tt.tag_id
WHERE t.deleted_at IS NULL AND g.deleted_at IS NOT NULL
UNION ALL
SELECT 3, 'lien_tache_supprimee', count(*)::int
FROM sl_task_tags tt
JOIN sl_tasks t ON t.id = tt.task_id
WHERE t.deleted_at IS NOT NULL
UNION ALL
SELECT 4, 'tache_liste_supprimee', count(*)::int
FROM sl_tasks t
JOIN sl_lists l ON l.id = t.list_id
WHERE t.deleted_at IS NULL AND l.deleted_at IS NOT NULL
UNION ALL
SELECT 5, 'sous_tache_parent_absent', count(*)::int
FROM sl_tasks t
WHERE t.deleted_at IS NULL
AND t.parent_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM sl_tasks p WHERE p.id = t.parent_id)
UNION ALL
SELECT 6, 'sous_tache_parent_supprime', count(*)::int
FROM sl_tasks t
JOIN sl_tasks p ON p.id = t.parent_id
WHERE t.deleted_at IS NULL AND p.deleted_at IS NOT NULL
UNION ALL
SELECT 7, 'tache_liste_autre_compte', count(*)::int
FROM sl_tasks t
JOIN sl_lists l ON l.id = t.list_id
WHERE l.user_id <> t.user_id
UNION ALL
SELECT 8, 'sous_tache_parent_autre_compte', count(*)::int
FROM sl_tasks t
JOIN sl_tasks p ON p.id = t.parent_id
WHERE p.user_id <> t.user_id
UNION ALL
SELECT 9, 'lien_etiquette_autre_compte', count(*)::int
FROM sl_task_tags tt
JOIN sl_tasks t ON t.id = tt.task_id
JOIN sl_tags g ON g.id = tt.tag_id
WHERE g.user_id <> t.user_id
UNION ALL
SELECT 10, 'compte_sans_inbox', count(DISTINCT t.user_id)::int
FROM sl_tasks t
WHERE t.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1 FROM sl_lists l
WHERE l.user_id = t.user_id AND l.is_inbox AND l.deleted_at IS NULL
)
) controles
ORDER BY rang;
ROLLBACK;

282
web/src/test/probe.test.ts Normal file
View file

@ -0,0 +1,282 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
import { PGlite } from 'electric-sql-pglite';
// Production probe (#176): web/scripts/probe.sql runs, as written on disk,
// against an in-memory Postgres (PGlite) with the companion migrations.
// Each test starts from empty tables, seeds a healthy base for two accounts,
// adds at most one anomaly and compares the whole set of counters.
const PROBE_PATH = path.join(__dirname, '../../scripts/probe.sql');
const probe = fs.readFileSync(PROBE_PATH, 'utf8');
const CONTROLS = [
'inbox_doublon',
'lien_etiquette_supprimee',
'lien_tache_supprimee',
'tache_liste_supprimee',
'sous_tache_parent_absent',
'sous_tache_parent_supprime',
'tache_liste_autre_compte',
'sous_tache_parent_autre_compte',
'lien_etiquette_autre_compte',
'compte_sans_inbox',
] as const;
type Control = (typeof CONTROLS)[number];
type Counts = Record<Control, number>;
const pg = new PGlite();
const DELETED = '2026-11-01T12:00:00.000Z';
beforeAll(async () => {
const dir = path.join(__dirname, '../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await pg.exec(stmt);
}
}
});
beforeEach(async () => {
await pg.exec('TRUNCATE sl_task_tags, sl_tasks, sl_tags, sl_lists');
});
function expected(overrides: Partial<Counts> = {}): Counts {
return { ...Object.fromEntries(CONTROLS.map((c) => [c, 0])), ...overrides } as Counts;
}
async function runProbe(sql = probe) {
const results = await pg.exec(sql);
const selects = results.filter((r) => r.fields.length > 0);
expect(selects).toHaveLength(1);
return selects[0];
}
async function counts(): Promise<Counts> {
const { rows } = await runProbe();
return Object.fromEntries(
(rows as { controle: string; nombre: number }[]).map((r) => [r.controle, r.nombre]),
) as Counts;
}
async function list(userId: string, opts: { inbox?: boolean; deleted?: boolean } = {}) {
const id = u();
await pg.query(
'insert into sl_lists (id, user_id, name, is_inbox, deleted_at) values ($1, $2, $3, $4, $5)',
[id, userId, 'list', opts.inbox ?? false, opts.deleted ? DELETED : null],
);
return id;
}
async function task(userId: string, listId: string, opts: { parentId?: string; deleted?: boolean } = {}) {
const id = u();
await pg.query(
'insert into sl_tasks (id, user_id, title, notes, list_id, parent_id, deleted_at) values ($1, $2, $3, $4, $5, $6, $7)',
[id, userId, 'title', 'notes', listId, opts.parentId ?? null, opts.deleted ? DELETED : null],
);
return id;
}
async function tag(userId: string, opts: { deleted?: boolean } = {}) {
const id = u();
await pg.query(
'insert into sl_tags (id, user_id, name, deleted_at) values ($1, $2, $3, $4)',
[id, userId, 'tag', opts.deleted ? DELETED : null],
);
return id;
}
async function link(taskId: string, tagId: string) {
await pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [taskId, tagId]);
}
type Account = { userId: string; inbox: string; list: string; task: string; tag: string };
// A healthy account, with the soft-deleted rows that must not count:
// a deleted Inbox next to the active one, a deleted list holding a deleted
// task, a deleted subtask of a deleted parent, a deleted subtask whose parent
// is missing, and a deleted tag without links.
async function healthyAccount(): Promise<Account> {
const userId = `user-${u()}`;
const inbox = await list(userId, { inbox: true });
await list(userId, { inbox: true, deleted: true });
const l = await list(userId);
const t = await task(userId, inbox);
await task(userId, l, { parentId: t });
const g = await tag(userId);
await link(t, g);
const gone = await list(userId, { deleted: true });
const goneTask = await task(userId, gone, { deleted: true });
await task(userId, l, { parentId: goneTask, deleted: true });
await task(userId, l, { parentId: u(), deleted: true });
await tag(userId, { deleted: true });
return { userId, inbox, list: l, task: t, tag: g };
}
async function healthyBase() {
const A = await healthyAccount();
const B = await healthyAccount();
// An account whose only tasks are deleted, without any active Inbox.
const C = `user-${u()}`;
const cList = await list(C, { inbox: true, deleted: true });
await task(C, cList, { deleted: true });
return { A, B };
}
describe('web/scripts/probe.sql: text', () => {
// Comments stripped, so a header that names a forbidden keyword stays allowed.
const code = probe.replace(/--[^\n]*/g, '');
const statements = code.split(';').map((s) => s.trim().replace(/\s+/g, ' ')).filter(Boolean);
it('has no psql meta-command (no backslash anywhere in the file)', () => {
expect(probe).not.toContain('\\');
});
it('never ends the transaction other than by the final ROLLBACK, never goes read-write', () => {
expect(code).not.toMatch(/\bCOMMIT\b/i);
expect(code).not.toMatch(/\bEND\b/i);
expect(code).not.toMatch(/\bREAD\s+WRITE\b/i);
expect(code).not.toMatch(/\bdefault_transaction_read_only\b/i);
});
it('opens a READ ONLY transaction first and ends with ROLLBACK', () => {
expect(statements[0].toUpperCase()).toBe('BEGIN TRANSACTION READ ONLY');
expect(statements.at(-1)?.toUpperCase()).toBe('ROLLBACK');
expect(statements.filter((s) => /^ROLLBACK$/i.test(s))).toHaveLength(1);
expect(statements.filter((s) => /^BEGIN\b/i.test(s))).toHaveLength(1);
});
});
describe('web/scripts/probe.sql: output', () => {
it('returns only control names and counts, one row per control, in order', async () => {
await healthyBase();
const { fields, rows } = await runProbe();
expect(fields.map((f) => f.name)).toEqual(['controle', 'nombre']);
for (const col of ['user_id', 'title', 'name', 'notes']) {
expect(fields.map((f) => f.name)).not.toContain(col);
}
expect((rows as { controle: string }[]).map((r) => r.controle)).toEqual([...CONTROLS]);
for (const r of rows as { nombre: unknown }[]) expect(Number.isInteger(r.nombre)).toBe(true);
});
it('counts 0 everywhere on a healthy base', async () => {
await healthyBase();
expect(await counts()).toEqual(expected());
});
it('leaves no transaction open: a write after the probe succeeds', async () => {
await runProbe();
await expect(pg.query('insert into sl_lists (user_id, name) values ($1, $2)', ['u', 'n'])).resolves.toBeDefined();
});
});
describe('web/scripts/probe.sql: read-only', () => {
it('refuses a write slipped into its transaction', async () => {
const { A } = await healthyBase();
const before = (await pg.query<{ n: number }>('select count(*)::int n from sl_lists')).rows[0].n;
const i = probe.lastIndexOf('ROLLBACK;');
const tampered = `${probe.slice(0, i)}INSERT INTO sl_lists (user_id, name) VALUES ('${A.userId}', 'x');\n${probe.slice(i)}`;
await expect(pg.exec(tampered)).rejects.toThrow(/read-only transaction/);
await pg.exec('ROLLBACK');
const after = (await pg.query<{ n: number }>('select count(*)::int n from sl_lists')).rows[0].n;
expect(after).toBe(before);
});
});
describe('web/scripts/probe.sql: each control detects its seeded anomaly', () => {
it('inbox_doublon: a second active Inbox', async () => {
const { A } = await healthyBase();
await list(A.userId, { inbox: true });
expect(await counts()).toEqual(expected({ inbox_doublon: 1 }));
});
it('lien_etiquette_supprimee: an active task linked to a deleted tag', async () => {
const { A } = await healthyBase();
await link(A.task, await tag(A.userId, { deleted: true }));
expect(await counts()).toEqual(expected({ lien_etiquette_supprimee: 1 }));
});
it('lien_etiquette_supprimee does not count a deleted task linked to a deleted tag', async () => {
const { A } = await healthyBase();
const t = await task(A.userId, A.list, { deleted: true });
await link(t, await tag(A.userId, { deleted: true }));
expect(await counts()).toEqual(expected({ lien_tache_supprimee: 1 }));
});
it('lien_tache_supprimee: a deleted task still linked to a tag', async () => {
const { A } = await healthyBase();
await link(await task(A.userId, A.list, { deleted: true }), A.tag);
expect(await counts()).toEqual(expected({ lien_tache_supprimee: 1 }));
});
it('tache_liste_supprimee: an active task in a deleted list', async () => {
const { A } = await healthyBase();
await task(A.userId, await list(A.userId, { deleted: true }));
expect(await counts()).toEqual(expected({ tache_liste_supprimee: 1 }));
});
it('sous_tache_parent_absent: an active subtask whose parent row is missing', async () => {
const { A } = await healthyBase();
await task(A.userId, A.list, { parentId: u() });
expect(await counts()).toEqual(expected({ sous_tache_parent_absent: 1 }));
});
it('sous_tache_parent_supprime: an active subtask of a deleted parent', async () => {
const { A } = await healthyBase();
await task(A.userId, A.list, { parentId: await task(A.userId, A.list, { deleted: true }) });
expect(await counts()).toEqual(expected({ sous_tache_parent_supprime: 1 }));
});
it('tache_liste_autre_compte: a task of B in a list of A', async () => {
const { A, B } = await healthyBase();
await task(B.userId, A.list);
expect(await counts()).toEqual(expected({ tache_liste_autre_compte: 1 }));
});
it('sous_tache_parent_autre_compte: a subtask of B under a task of A', async () => {
const { A, B } = await healthyBase();
await task(B.userId, B.list, { parentId: A.task });
expect(await counts()).toEqual(expected({ sous_tache_parent_autre_compte: 1 }));
});
it('lien_etiquette_autre_compte: a task of A linked to a tag of B', async () => {
const { A, B } = await healthyBase();
await link(A.task, B.tag);
expect(await counts()).toEqual(expected({ lien_etiquette_autre_compte: 1 }));
});
it('compte_sans_inbox: an account with active tasks and only a deleted Inbox counts once', async () => {
await healthyBase();
const C = `user-${u()}`;
await list(C, { inbox: true, deleted: true });
const cList = await list(C);
await task(C, cList);
await task(C, cList);
expect(await counts()).toEqual(expected({ compte_sans_inbox: 1 }));
});
});
// Controls 7 to 9 are isolation checks: a cross-account row is a leak even
// once soft-deleted, so they count deleted rows too.
describe('web/scripts/probe.sql: isolation controls count deleted rows', () => {
it('tache_liste_autre_compte: a deleted task of B in a list of A', async () => {
const { A, B } = await healthyBase();
await task(B.userId, A.list, { deleted: true });
expect(await counts()).toEqual(expected({ tache_liste_autre_compte: 1 }));
});
it('sous_tache_parent_autre_compte: a deleted subtask of B under a task of A', async () => {
const { A, B } = await healthyBase();
await task(B.userId, B.list, { parentId: A.task, deleted: true });
expect(await counts()).toEqual(expected({ sous_tache_parent_autre_compte: 1 }));
});
it('lien_etiquette_autre_compte: a deleted tag of B linked to a task of A', async () => {
const { A, B } = await healthyBase();
await link(A.task, await tag(B.userId, { deleted: true }));
expect(await counts()).toEqual(expected({ lien_etiquette_autre_compte: 1, lien_etiquette_supprimee: 1 }));
});
});