// 1.4.0: database backups (Settings → Backups) and the background jobs (Settings → Background // jobs), as Accounts and Cross Events; the heartbeat reports both to the Hub. 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, runUploadsBackup, UPLOADS_SNAPSHOT } from '../src/backups/uploads.js'; import { health } from '../src/hub/client.js'; import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js'; import { hashToken } from '../src/lib/crypto.js'; import { harness, SITE } from './support/harness.js'; type Role = 'owner' | 'admin' | 'editor'; 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(() => { useEnvForTest(process.env); useDumperForTest(null); }); async function site() { const h = await harness({ linked: false }); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-backups-')); h.ctx.config.backupDir = dir; h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/website_test'; const as = async (role: Role) => { const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor'].indexOf(role) + 1}`; await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role } }); await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } }); const cookie = `ccw_session=token-${role}`; return { get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie), put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body), post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body), }; }; return { ...h, dir, as }; } describe('backups (1.4.0)', () => { it('a backup is the gzipped dump, named as the crosscode script names them', async () => { const h = await site(); const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Page" ();\n')); assert.match(b.filename, BACKUP_FILE); assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(h.dir, b.filename))).toString(), 'CREATE TABLE "Page" ();\n'); assert.equal(backupName(new Date(2026, 10, 27, 2, 20, 5)), 'website-20261127-022005.sql.gz'); const again = await runBackup(h.ctx, dumpOf('-- again\n')); assert.notEqual(again.filename, b.filename, 'a second one in the same second gets its own name'); }); it('a dump that fails part-way leaves no file, and says why', async () => { const h = await site(); 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 runBackup(h.ctx, dumpOf('-- fine\n')); assert.equal(await h.ctx.settings.get('backup_last_error'), null); }); it('only the newest are kept; a download only by a backup\'s own name', async () => { const h = await site(); await h.ctx.settings.set('backup_retain_count', '2'); for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`)); const left = await listBackups(h.ctx); assert.equal(left.length, 2); assert.ok(backupPath(h.ctx, left[0]!.filename)); assert.equal(backupPath(h.ctx, '../.env'), null); assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null); }); it('the nightly backup is skipped while it\'s turned off', async () => { const h = await site(); await h.ctx.settings.set('backup_nightly', 'false'); assert.deepEqual(await runBackupJob(h.ctx), { skipped: true }); }); it('admins see, change and download them; editors can\'t', async () => { const h = await site(); await runBackup(h.ctx, dumpOf('-- a backup\n')); const editor = await h.as('editor'); assert.equal((await editor.get('/backups')).status, 403); assert.equal((await editor.post('/backups/run')).status, 403); assert.equal((await editor.get('/pages')).status, 200, 'the admin-only routes don\'t stop the others'); const admin = await h.as('admin'); const list = await admin.get('/backups'); assert.equal(list.status, 200, JSON.stringify(list.body)); assert.equal(list.body.nightly, true); assert.equal(list.body.retain, 14); const file = await admin.get(`/backups/${list.body.items[0].filename}/download`).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(file.headers['cache-control'], 'no-store'); assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- a backup\n'); assert.equal((await admin.get('/backups/nope.sql.gz/download')).status, 404); assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1); assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400); const saved = await admin.put('/backups/settings', { retain: 30, nightly: false }); assert.deepEqual(saved.body, { retain: 30, nightly: false, uploads: true, deleted: 0 }); assert.equal(await h.ctx.settings.bool('backup_nightly', true), false); }); it('the heartbeat reports the newest backup and the real job mode (before: null, so the Hub warned)', async () => { const h = await site(); assert.equal((await health(h.ctx)).lastBackupAt, null); await runBackup(h.ctx, dumpOf('-- x\n')); const report = await health(h.ctx); assert.ok(report.lastBackupAt && Date.parse(report.lastBackupAt) > Date.now() - 60e3); assert.deepEqual(report.jobs, await jobsHealth(h.ctx)); assert.equal(report.jobs.mode, 'off', 'no job system started in the tests'); }); }); describe('background jobs (1.4.0)', () => { const backup = JOBS.find((j) => j.name === 'backup')!; it('the heartbeat, the event feed, YouTube and the backup are jobs', () => { assert.deepEqual(JOBS.map((j) => j.name).sort(), ['backup', 'event-feed', 'hub-heartbeat', 'youtube']); }); it('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => { const h = await site(); useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' }); h.ctx.config.jobsEnabled = true; // nothing is started here either way const admin = await h.as('admin'); type Row = { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }; let job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!; assert.equal(job.enabled, false); assert.equal(job.cron, '30 1 * * *'); assert.deepEqual(job.override, { enabled: null, cron: null }); const on = await admin.put('/jobs/backup', { enabled: true, cron: '0 3 * * *' }); assert.equal(on.status, 200, JSON.stringify(on.body)); assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' }); assert.equal(isEnabled(h.ctx, backup), true); assert.equal(cronFor(h.ctx, backup), '0 3 * * *'); job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!; assert.equal(job.enabled, true); assert.equal(job.envEnabled, false); const back = await admin.put('/jobs/backup', { enabled: null, cron: null }); assert.deepEqual(back.body.override, { enabled: null, cron: null }); assert.equal(isEnabled(h.ctx, backup), false); assert.equal(await h.db.auditLog.count({ where: { action: 'job_settings_changed' } }), 2); useEnvForTest(process.env); }); it('a bad schedule, a bad switch and an unknown job are refused; editors can\'t change jobs', async () => { const h = await site(); const admin = await h.as('admin'); assert.equal((await admin.put('/jobs/backup', { cron: 'every night' })).status, 400); assert.equal((await admin.put('/jobs/backup', { enabled: 'yes' })).status, 400); assert.equal((await admin.put('/jobs/nope', { enabled: true })).status, 404); const editor = await h.as('editor'); assert.equal((await editor.get('/jobs')).status, 403); assert.equal((await editor.put('/jobs/backup', { enabled: false })).status, 403); }); it('running one now runs it here (no queue in the tests) and remembers the run', async () => { const h = await site(); h.ctx.config.databaseUrl = null; await assert.rejects(runNow(h.ctx, 'backup'), /DATABASE_URL/); const admin = await h.as('admin'); const ran = await admin.post('/jobs/youtube/run'); assert.equal(ran.status, 200, JSON.stringify(ran.body)); assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } }); }); }); describe('backups of the photos and files (1.5.0)', () => { useDumperForTest(dumpOf('-- the database\n')); async function withUploads() { const h = await site(); const up = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-up-')); h.ctx.config.uploadDir = up; fs.mkdirSync(path.join(up, 'demo')); fs.mkdirSync(path.join(up, '.thumbnails')); fs.writeFileSync(path.join(up, 'a.jpg'), 'photo a'); fs.writeFileSync(path.join(up, 'demo', 'b.svg'), ''); fs.writeFileSync(path.join(up, '.thumbnails', 't.jpg'), 'made again on demand'); return { ...h, up }; } const ino = (p: string) => fs.statSync(p).ino; it('a snapshot is a real copy of the uploads, without .thumbnails', async () => { const h = await withUploads(); const s = await runUploadsBackup(h.ctx); assert.match(s.name, UPLOADS_SNAPSHOT); const snap = path.join(h.dir, s.name); assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a'); assert.equal(fs.readFileSync(path.join(snap, 'demo', 'b.svg'), 'utf8'), ''); assert.ok(!fs.existsSync(path.join(snap, '.thumbnails'))); assert.deepEqual([s.files, s.newFiles], [2, 2]); assert.notEqual(ino(path.join(snap, 'a.jpg')), ino(path.join(h.up, 'a.jpg')), 'not the live file itself'); // Deleting the live file leaves the backup. fs.rmSync(path.join(h.up, 'a.jpg')); assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a'); }); it('the next one links what\'s unchanged and copies only what\'s new', async () => { const h = await withUploads(); const first = await runUploadsBackup(h.ctx); fs.writeFileSync(path.join(h.up, 'c.png'), 'new photo'); const second = await runUploadsBackup(h.ctx); assert.notEqual(second.name, first.name); assert.deepEqual([second.files, second.newFiles, second.newBytes], [3, 1, 'new photo'.length]); assert.equal(ino(path.join(h.dir, second.name, 'a.jpg')), ino(path.join(h.dir, first.name, 'a.jpg')), 'unchanged: a hard link'); assert.equal((await listUploadsSnapshots(h.ctx))[0]!.name, second.name); }); it('only the newest are kept, as the database backups; a crash leaves no half snapshot behind', async () => { const h = await withUploads(); await h.ctx.settings.set('backup_retain_count', '2'); fs.mkdirSync(path.join(h.dir, '.uploads-20200101-000000-partial')); for (let i = 0; i < 3; i++) await runUploadsBackup(h.ctx); assert.equal((await listUploadsSnapshots(h.ctx)).length, 2); assert.ok(!fs.existsSync(path.join(h.dir, '.uploads-20200101-000000-partial'))); }); it('the nightly job backs up both, and leaves the uploads out when that\'s off', async () => { const h = await withUploads(); const ran = await runNightlyBackups(h.ctx) as { database: { filename?: string }; uploads: { name?: string; skipped?: boolean } }; assert.ok(ran.database.filename && ran.uploads.name, JSON.stringify(ran)); await h.ctx.settings.set('backup_uploads', 'false'); assert.deepEqual((await runNightlyBackups(h.ctx) as { uploads: unknown }).uploads, { skipped: true }); await h.ctx.settings.set('backup_nightly', 'false'); assert.deepEqual(await runNightlyBackups(h.ctx), { database: { skipped: true } }); }); it('Back up now makes both; the page lists the snapshots; the switch is saved', async () => { const h = await withUploads(); const admin = await h.as('admin'); const made = await admin.post('/backups/run'); assert.equal(made.status, 200, JSON.stringify(made.body)); assert.equal(made.body.uploads.newFiles, 2); assert.equal(made.body.uploadsError, null); const list = await admin.get('/backups'); assert.equal(list.body.uploads.enabled, true); assert.equal(list.body.uploads.items.length, 1); assert.equal(list.body.uploads.items[0].files, 2); const off = await admin.put('/backups/settings', { retain: 14, nightly: true, uploads: false }); assert.equal(off.body.uploads, false); assert.equal(await h.ctx.settings.bool('backup_uploads', true), false); }); });