mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-17 19:59:33 +01:00
Merge pull request #661: feat(config): timestamped config backups with a configurable folder and retention
Conflicts in CLAUDE.md, README.md, docs/api-reference.md and src/web/server.ts were additions beside #662's Copilot quota read and #666's keep-warm sections; both sides kept. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
3b6818449e
27 files changed
+3299
-6
No files matched your search
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* @fileoverview A backup pass reads the backup folder once: one directory listing and one read per
|
||||
* manifest, shared by the recorded-retention fallback, the change check and the prune. Each used to
|
||||
* list the folder itself, which on a network folder meant every manifest read three times every five
|
||||
* minutes (found in review of #661).
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME. Port: N/A (no server).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const rec = vi.hoisted(() => ({ dir: '', calls: [] as string[] }));
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>();
|
||||
const record = <F extends (...a: never[]) => unknown>(name: string, real: F): F =>
|
||||
((path: unknown, ...rest: unknown[]) => {
|
||||
if (rec.dir && String(path).startsWith(rec.dir)) rec.calls.push(`${name} ${String(path)}`);
|
||||
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
|
||||
}) as unknown as F;
|
||||
const wrapped = {
|
||||
...actual,
|
||||
readdirSync: record('readdirSync', actual.readdirSync),
|
||||
readFileSync: record('readFileSync', actual.readFileSync),
|
||||
};
|
||||
return { ...wrapped, default: wrapped };
|
||||
});
|
||||
|
||||
import { runConfigBackup } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { createConfigBackup, defaultConfigBackupDir, listConfigBackups } from '../../src/config-backup.js';
|
||||
|
||||
const dir = () => defaultConfigBackupDir(getDataDir());
|
||||
const DAY = 86_400_000;
|
||||
const BASE = Date.UTC(2025, 0, 1);
|
||||
|
||||
beforeEach(() => {
|
||||
rec.dir = '';
|
||||
rec.calls.length = 0;
|
||||
rmSync(dir(), { recursive: true, force: true });
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
rec.dir = '';
|
||||
rmSync(dir(), { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('one backup pass', () => {
|
||||
it('lists the folder once and reads each manifest once', async () => {
|
||||
// Only the OLDEST snapshot recorded a retention, so the fallback has to look through every one.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: `v${i}` }));
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: dir(),
|
||||
reason: 'auto',
|
||||
now: BASE + i * DAY,
|
||||
...(i === 0 && { keepCount: 100, keepDays: 0 }),
|
||||
});
|
||||
}
|
||||
// A change (so the pass writes a snapshot and then prunes) and no retention keys (the fallback reads).
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'changed' }));
|
||||
rec.dir = dir();
|
||||
const out = await runConfigBackup('auto');
|
||||
rec.dir = '';
|
||||
|
||||
expect(out?.result.status).toBe('created');
|
||||
expect(out?.removed).toEqual([]); // the recorded 100 / no age limit, not the defaults
|
||||
expect(rec.calls.filter((c) => c.startsWith('readdirSync'))).toHaveLength(1);
|
||||
const manifestReads = rec.calls.filter((c) => c.startsWith('readFileSync') && c.endsWith('manifest.json'));
|
||||
expect(manifestReads).toHaveLength(6);
|
||||
expect(new Set(manifestReads).size).toBe(6);
|
||||
expect(listConfigBackups(dir())).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('counts the snapshot it just made when it prunes', async () => {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: 0 }));
|
||||
for (let i = 0; i < 3; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: i }));
|
||||
createConfigBackup({ dataDir: getDataDir(), backupDir: dir(), reason: 'auto', now: BASE + i * DAY });
|
||||
}
|
||||
const before = listConfigBackups(dir()).map((b) => b.id);
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: 9 }));
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
const kept = listConfigBackups(dir()).map((b) => b.id);
|
||||
// keep 2: the new one and the newest before it; the two older ones go
|
||||
expect(kept).toEqual([(out?.result as { id: string }).id, before[0]]);
|
||||
expect(out?.removed.sort()).toEqual([before[1], before[2]].sort());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* @fileoverview /api/config-backups: list, back up now, restore. Settings are read fresh from
|
||||
* settings.json, so a folder or retention change applies on the next request.
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME (and so one data dir). Port: N/A (inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerConfigBackupRoutes, runConfigBackup } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { createConfigBackup, defaultConfigBackupDir, listConfigBackups } from '../../src/config-backup.js';
|
||||
import { intentStore } from '../../src/intent-store.js';
|
||||
|
||||
let custom: string;
|
||||
const settings = (extra: Record<string, unknown> = {}) => {
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'before', ...extra }));
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
custom = mkdtempSync(join(tmpdir(), 'cfg-backup-route-'));
|
||||
rmSync(defaultConfigBackupDir(getDataDir()), { recursive: true, force: true });
|
||||
settings();
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
rmSync(custom, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
rmSync(defaultConfigBackupDir(getDataDir()), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('/api/config-backups', () => {
|
||||
it('lists the effective settings, the default folder and the tracked files', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'GET', url: '/api/config-backups' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.settings).toEqual({ enabled: true, dir: null, keepCount: 20, keepDays: 30 });
|
||||
expect(d.dir).toBe(defaultConfigBackupDir(getDataDir()));
|
||||
expect(d.tracked).toContain('settings.json');
|
||||
expect(d.backups).toEqual([]);
|
||||
});
|
||||
|
||||
it('backs up now into the default folder and lists it', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const made = await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
expect(made.statusCode).toBe(200);
|
||||
expect(made.json().data.status).toBe('created');
|
||||
const list = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data;
|
||||
expect(list.backups).toHaveLength(1);
|
||||
expect(list.backups[0].reason).toBe('manual');
|
||||
expect(list.backups[0].files.map((f: { name: string }) => f.name)).toContain('settings.json');
|
||||
// Names and sizes only, never content.
|
||||
expect(JSON.stringify(list)).not.toContain('before');
|
||||
});
|
||||
|
||||
it('follows a custom folder and retention from settings on the next request', async () => {
|
||||
const dir = join(custom, 'snap');
|
||||
settings({ configBackupDir: dir, configBackupKeepCount: 2, configBackupKeepDays: 0 });
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: dir, configBackupKeepCount: 2, i }));
|
||||
await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
const d = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data;
|
||||
expect(d.dir).toBe(dir);
|
||||
expect(d.backups).toHaveLength(2);
|
||||
expect(existsSync(defaultConfigBackupDir(getDataDir()))).toBe(false);
|
||||
});
|
||||
|
||||
it('restores a backup, reports what needs a restart and keeps a pre-restore copy', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'clis.json'), '{"schemaVersion":1,"clis":{}}', { mode: 0o600 });
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'polluted' }));
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'clis.json'), '{"clis":{"evil":{}}}');
|
||||
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.restored).toEqual(expect.arrayContaining(['settings.json', 'clis.json']));
|
||||
expect(d.restartRequired).not.toContain('clis.json'); // reloaded by the restore itself
|
||||
expect(d.restartRequired).toContain('settings.json'); // its watcher toggles are not re-run by a restore
|
||||
expect(d.safetySnapshot).toBeTruthy();
|
||||
expect(JSON.parse(readFileSync(SETTINGS_PATH, 'utf8')).displayName).toBe('before');
|
||||
});
|
||||
|
||||
it('a restore that fails partway names what it restored, what failed and the pre-restore copy', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const clis = join(dirname(SETTINGS_PATH), 'clis.json');
|
||||
writeFileSync(clis, '{"schemaVersion":1,"clis":{}}', { mode: 0o600 });
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'polluted' }));
|
||||
// A file the server cannot replace: settings.json (first in the list) goes back, clis.json cannot.
|
||||
rmSync(clis);
|
||||
mkdirSync(clis);
|
||||
try {
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode).toBe(500);
|
||||
const body = res.json();
|
||||
expect(body).toMatchObject({ success: false, errorCode: 'OPERATION_FAILED' });
|
||||
expect(body.error).toContain('clis.json');
|
||||
expect(body.data.restored).toContain('settings.json');
|
||||
expect(body.data.failed.map((f: { name: string }) => f.name)).toEqual(['clis.json']);
|
||||
expect(body.data.restartRequired).toContain('settings.json');
|
||||
expect(JSON.parse(readFileSync(SETTINGS_PATH, 'utf8')).displayName).toBe('before');
|
||||
// The undo copy exists, holds the state the restore replaced, and is the one named.
|
||||
const safety = body.data.safetySnapshot;
|
||||
expect(safety).toBeTruthy();
|
||||
expect(body.error).toContain(safety);
|
||||
const listed = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.backups;
|
||||
expect(listed.find((b: { id: string }) => b.id === safety)?.reason).toBe('pre-restore');
|
||||
} finally {
|
||||
rmSync(clis, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('a restored intents.json is not reverted by the next captured prompt', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const dir = mkdtempSync(join(tmpdir(), 'cfg-backup-intent-'));
|
||||
try {
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'first prompt about the build pipeline');
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'second prompt about the build pipeline');
|
||||
await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'third prompt about the build pipeline');
|
||||
expect(intentStore.getProfile(undefined, dir).recentPrompts).toHaveLength(2);
|
||||
} finally {
|
||||
intentStore.deleteProfile(undefined, dir);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a custom folder whose parent is missing instead of creating it', async () => {
|
||||
settings({ configBackupDir: join(custom, 'no', 'such', 'dir') });
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(existsSync(join(custom, 'no'))).toBe(false);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown backup and 404 for a traversal attempt', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
for (const id of ['cfg-19990101-000000', '..%2F..%2Fetc', 'photos']) {
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode, id).toBe(404);
|
||||
}
|
||||
});
|
||||
|
||||
it('is admin only in multi-user mode: a non-admin is refused on every verb', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'bob', role: 'user' },
|
||||
});
|
||||
for (const [method, url] of [
|
||||
['GET', '/api/config-backups'],
|
||||
['POST', '/api/config-backups'],
|
||||
['POST', '/api/config-backups/cfg-20261001-120000/restore'],
|
||||
['GET', '/api/config-backups/diff?from=cfg-20261001-120000'],
|
||||
] as const) {
|
||||
expect((await app.inject({ method, url })).statusCode, `${method} ${url}`).toBe(403);
|
||||
}
|
||||
});
|
||||
|
||||
it('multi-user: a restore is written to the admin audit log', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
const auditPath = join(getDataDir(), 'admin-audit.jsonl');
|
||||
const written = () => existsSync(auditPath) && readFileSync(auditPath, 'utf8').includes('config_backup_restore');
|
||||
for (let i = 0; i < 40 && !written(); i++) await new Promise((r) => setTimeout(r, 25));
|
||||
const last = JSON.parse(readFileSync(auditPath, 'utf8').trim().split('\n').pop()!);
|
||||
expect(last).toMatchObject({ admin: 'root', action: 'config_backup_restore', target: id });
|
||||
expect(last.detail.restored).toContain('settings.json');
|
||||
rmSync(auditPath, { force: true });
|
||||
});
|
||||
|
||||
it('multi-user: an admin is allowed', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups' })).json().success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/config-backups/diff', () => {
|
||||
it('compares a backup with the running config, defaulting `to` to current', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const made = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data;
|
||||
settings({ displayName: 'after' });
|
||||
const res = await app.inject({ method: 'GET', url: `/api/config-backups/diff?from=${made.id}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.to).toBe('current');
|
||||
expect(d.files.find((f: { name: string }) => f.name === 'settings.json').changes).toEqual([
|
||||
{ path: 'displayName', kind: 'changed', before: '"before"', after: '"after"' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('400 without `from`, 404 for an unknown backup', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups/diff' })).statusCode).toBe(400);
|
||||
const missing = await app.inject({ method: 'GET', url: '/api/config-backups/diff?from=cfg-20200101-000000' });
|
||||
expect(missing.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retention survives an unreadable or reset settings.json', () => {
|
||||
const DAY = 86_400_000;
|
||||
const BASE = Date.UTC(2025, 0, 1);
|
||||
const dir = () => defaultConfigBackupDir(getDataDir());
|
||||
/** 30 snapshots a day apart, made under a long-history retention (100 copies, no age limit). */
|
||||
function seed(withKeys = true) {
|
||||
settings({ configBackupKeepCount: 100, configBackupKeepDays: 0 });
|
||||
for (let i = 0; i < 30; i++) {
|
||||
writeFileSync(
|
||||
SETTINGS_PATH,
|
||||
JSON.stringify(
|
||||
withKeys
|
||||
? { displayName: `v${i}`, configBackupKeepCount: 100, configBackupKeepDays: 0 }
|
||||
: { displayName: `v${i}` }
|
||||
)
|
||||
);
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: dir(),
|
||||
reason: 'auto',
|
||||
now: BASE + i * DAY,
|
||||
keepCount: 100,
|
||||
keepDays: 0,
|
||||
});
|
||||
}
|
||||
expect(listConfigBackups(dir())).toHaveLength(30);
|
||||
}
|
||||
|
||||
it('a settings.json that does not parse still gets a snapshot but prunes nothing', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, '{ "displayName": "half-written", }');
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(dir())).toHaveLength(31);
|
||||
});
|
||||
|
||||
it('a reset settings.json prunes with the retention the newest snapshot recorded, not the defaults', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, '{}');
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
// aged manifests (a year old) and keepDays 0: the defaults (20 copies, 30 days) would leave 20
|
||||
expect(listConfigBackups(dir())).toHaveLength(31);
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'a restore after a reset keeps the retention (the backup %s the four keys)',
|
||||
async (withKeys) => {
|
||||
seed(withKeys);
|
||||
const oldest = listConfigBackups(dir()).at(-1)!.id;
|
||||
writeFileSync(SETTINGS_PATH, '{}'); // the reset
|
||||
expect((await runConfigBackup('auto'))?.removed).toEqual([]);
|
||||
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${oldest}/restore` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
// the restored file carries the retention, or the recorded one still applies via the pre-restore copy
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(dir()).length).toBeGreaterThanOrEqual(32);
|
||||
const status = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.settings;
|
||||
expect(status).toMatchObject({ keepCount: 100, keepDays: 0 }); // what the form shows is what the pass uses
|
||||
}
|
||||
);
|
||||
|
||||
it("re-entering a custom folder after a reset finds that folder's recorded retention", async () => {
|
||||
const folder = join(custom, 'kept');
|
||||
settings({ configBackupDir: folder, configBackupKeepCount: 100, configBackupKeepDays: 0 });
|
||||
for (let i = 0; i < 30; i++) {
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: folder,
|
||||
reason: 'auto',
|
||||
force: true,
|
||||
now: BASE + i * DAY,
|
||||
keepCount: 100,
|
||||
keepDays: 0,
|
||||
});
|
||||
}
|
||||
writeFileSync(SETTINGS_PATH, '{}'); // the reset drops the folder too
|
||||
await runConfigBackup('auto'); // goes to the default folder, which holds none of those manifests
|
||||
// the user enters the folder again and saves; the form no longer sends retention it only displayed
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: folder, configBackupEnabled: true }));
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const reported = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.settings;
|
||||
expect(reported).toMatchObject({ keepCount: 100, keepDays: 0 });
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(folder).length).toBeGreaterThanOrEqual(30);
|
||||
});
|
||||
|
||||
it('only the retention key the file lacks falls back to the recorded one', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepDays: 3650 }));
|
||||
await runConfigBackup('auto');
|
||||
expect(listConfigBackups(dir())).toHaveLength(31); // keepCount 100 from the manifests, not the default 20
|
||||
});
|
||||
|
||||
it('a settings.json that sets the retention still wins', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 5, configBackupKeepDays: 0 }));
|
||||
await runConfigBackup('auto');
|
||||
expect(listConfigBackups(dir())).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('listing never creates config-backup-id', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const idFile = join(getDataDir(), 'config-backup-id');
|
||||
rmSync(idFile, { force: true });
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.backups).toEqual([]);
|
||||
expect(existsSync(idFile)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* @fileoverview A custom backup folder that stops answering (a network mount) must never be listed or
|
||||
* read before the bounded probe says it is there: GET, Back up now, diff and restore answer 503 without
|
||||
* touching it.
|
||||
* With only `configBackupDir` in settings.json the recorded-retention fallback would otherwise
|
||||
* `readdirSync` the folder first (found in review of #661).
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME. Port: N/A (inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const dead = vi.hoisted(() => ({ dir: '', touched: [] as string[] }));
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>();
|
||||
const record = <F extends (...a: never[]) => unknown>(name: string, real: F): F =>
|
||||
((path: unknown, ...rest: unknown[]) => {
|
||||
if (dead.dir && String(path).startsWith(dead.dir)) dead.touched.push(`${name} ${String(path)}`);
|
||||
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
|
||||
}) as unknown as F;
|
||||
const wrapped = {
|
||||
...actual,
|
||||
readdirSync: record('readdirSync', actual.readdirSync),
|
||||
readFileSync: record('readFileSync', actual.readFileSync),
|
||||
statSync: record('statSync', actual.statSync),
|
||||
lstatSync: record('lstatSync', actual.lstatSync),
|
||||
existsSync: record('existsSync', actual.existsSync),
|
||||
};
|
||||
return { ...wrapped, default: wrapped };
|
||||
});
|
||||
|
||||
vi.mock('../../src/utils/bounded-path-probe.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/bounded-path-probe.js')>();
|
||||
return {
|
||||
...actual,
|
||||
probePathKind: async (path: string, options?: { pastCap?: boolean }) =>
|
||||
dead.dir && path.startsWith(dead.dir) ? 'unknown' : actual.probePathKind(path, options),
|
||||
};
|
||||
});
|
||||
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerConfigBackupRoutes } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { configBackupOrigin } from '../../src/config-backup.js';
|
||||
|
||||
let root: string;
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'cfg-backup-dead-'));
|
||||
dead.dir = join(root, 'mount');
|
||||
dead.touched.length = 0;
|
||||
configBackupOrigin(getDataDir()); // an instance that already has an id: the fallback has something to look for
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
// Only the folder: no retention keys, the shape that makes the recorded-retention fallback want to read it.
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: dead.dir }));
|
||||
});
|
||||
afterEach(() => {
|
||||
dead.dir = '';
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('a custom backup folder that does not answer', () => {
|
||||
it.each([
|
||||
['GET', '/api/config-backups'],
|
||||
['POST', '/api/config-backups'],
|
||||
['GET', '/api/config-backups/diff?from=cfg-20261001-120000'],
|
||||
['POST', '/api/config-backups/cfg-20261001-120000/restore'],
|
||||
] as const)('%s %s answers 503 without reading the folder', async (method, url) => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method, url });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(dead.touched).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user