import { after, describe, it } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { Readable } from 'node:stream'; import zlib from 'node:zlib'; import request from 'supertest'; import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, useDumperForTest, type Dumper } from '../src/backups/backups.js'; import { listUploadsSnapshots, runNightlyBackups, UPLOADS_SNAPSHOT } from '../src/backups/uploads.js'; import { health } from '../src/hub/client.js'; import { cookieHeader, harness, PASTOR, signInAs, type Harness } from './support/harness.js'; const COORD = '55555555-5555-4555-8555-555555555555'; const ORIGIN = 'https://app.hope.test'; const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() }); const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) }); after(() => useDumperForTest(null)); async function setup() { const uploads = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-')); const h = await harness({ env: { UPLOAD_DIR: uploads } }) as Harness; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-backups-')); h.ctx.config.backupDir = dir; h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/app_test'; return { h, dir, uploads }; } describe('backups (ยง10)', () => { it('is the gzipped dump, named as the crosscode script names them', async () => { const { h, dir } = await setup(); const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Member" ();\n')); assert.match(b.filename, BACKUP_FILE); assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(dir, b.filename))).toString(), 'CREATE TABLE "Member" ();\n'); assert.equal(backupName(new Date(2026, 11, 1, 2, 40, 5)), 'app-20261201-024005.sql.gz'); assert.ok((await health(h.ctx)).lastBackupAt); }); it('leaves no file when the dump fails part-way, says why, and keeps only the newest', async () => { const { h } = await setup(); await assert.rejects(runBackup(h.ctx, failing), /connection refused/); assert.equal((await listBackups(h.ctx)).length, 0); assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/); await h.ctx.settings.set('backup_retain_count', '2'); for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`)); assert.equal((await listBackups(h.ctx)).length, 2); assert.equal(await h.ctx.settings.get('backup_last_error'), null); assert.equal(backupPath(h.ctx, '../.env'), null); assert.equal(backupPath(h.ctx, 'website-20200101-000000.sql.gz'), null); }); it('snapshots the uploaded images each night, linking what hasn\'t changed', async () => { const { h, uploads } = await setup(); useDumperForTest(dumpOf('-- nightly\n')); fs.mkdirSync(path.join(uploads, '2026', '12'), { recursive: true }); fs.writeFileSync(path.join(uploads, '2026', '12', 'a.jpg'), 'photo a'); const first = await runNightlyBackups(h.ctx) as { uploads: { newFiles: number } }; assert.equal(first.uploads.newFiles, 1); h.clock.add(1000); fs.writeFileSync(path.join(uploads, '2026', '12', 'b.jpg'), 'photo b'); const second = await runNightlyBackups(h.ctx) as { uploads: { newFiles: number } }; assert.equal(second.uploads.newFiles, 1, 'only the new photo is copied'); const snaps = await listUploadsSnapshots(h.ctx); assert.equal(snaps.length, 2); assert.match(snaps[0]!.name, UPLOADS_SNAPSHOT); assert.equal(snaps[0]!.files, 2); await h.ctx.settings.set('backup_nightly', 'false'); assert.deepEqual(await runBackupJob(h.ctx), { skipped: true }); }); it('in the admin: Back up now and a download, audited, for an Owner or Church admin only', async () => { const { h } = await setup(); useDumperForTest(dumpOf('-- from the admin\n')); const owner = await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner'] }, true); const coord = await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true); assert.equal((await request(h.app).get('/api/v1/admin/backups').set('Cookie', cookieHeader(coord))).status, 403); const made = await request(h.app).post('/api/v1/admin/backups/run').set('Cookie', cookieHeader(owner)).set('Origin', ORIGIN).send({}); assert.equal(made.status, 200); const list = await request(h.app).get('/api/v1/admin/backups').set('Cookie', cookieHeader(owner)); assert.equal(list.body.items[0].filename, made.body.filename); const file = await request(h.app).get(`/api/v1/admin/backups/${made.body.filename}/download`).set('Cookie', cookieHeader(owner)).buffer(true).parse((res, cb) => { const chunks: Buffer[] = []; res.on('data', (c: Buffer) => chunks.push(c)); res.on('end', () => cb(null, Buffer.concat(chunks))); }); assert.equal(file.status, 200); assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- from the admin\n'); const actions = [...h.db.tables.get('auditLog')!.values()].map((r) => r.action); assert.ok(actions.includes('backup_made') && actions.includes('backup_downloaded')); assert.equal((await request(h.app).put('/api/v1/admin/backups/settings').set('Cookie', cookieHeader(owner)).set('Origin', ORIGIN).send({ retain: 0 })).status, 400); }); });