diff --git a/server/src/nest/backup/backup.controller.ts b/server/src/nest/backup/backup.controller.ts index 61d61d09e..9071e46a7 100644 --- a/server/src/nest/backup/backup.controller.ts +++ b/server/src/nest/backup/backup.controller.ts @@ -60,9 +60,9 @@ export class BackupController { ) {} @Get('list') - list() { + async list() { try { - return { backups: this.backup.listBackups() }; + return { backups: await this.backup.listBackups() }; } catch { throw new HttpException({ error: 'Error loading backups' }, 500); } @@ -84,11 +84,11 @@ export class BackupController { } @Get('download/:filename') - download(@Param('filename') filename: string, @Res() res: Response): void { + async download(@Param('filename') filename: string, @Res() res: Response): Promise { if (!this.backup.isValidBackupFilename(filename)) { throw new HttpException({ error: 'Invalid filename' }, 400); } - if (!this.backup.backupFileExists(filename)) { + if (!(await this.backup.backupFileExists(filename))) { throw new HttpException({ error: 'Backup not found' }, 404); } res.download(this.backup.backupFilePath(filename), filename); @@ -101,7 +101,7 @@ export class BackupController { if (!this.backup.isValidBackupFilename(filename)) { throw new HttpException({ error: 'Invalid filename' }, 400); } - if (!this.backup.backupFileExists(filename)) { + if (!(await this.backup.backupFileExists(filename))) { throw new HttpException({ error: 'Backup not found' }, 404); } try { @@ -177,14 +177,14 @@ export class BackupController { } @Delete(':filename') - remove(@CurrentUser() user: User, @Param('filename') filename: string, @Req() req: Request) { + async remove(@CurrentUser() user: User, @Param('filename') filename: string, @Req() req: Request) { if (!this.backup.isValidBackupFilename(filename)) { throw new HttpException({ error: 'Invalid filename' }, 400); } - if (!this.backup.backupFileExists(filename)) { + if (!(await this.backup.backupFileExists(filename))) { throw new HttpException({ error: 'Backup not found' }, 404); } - this.backup.deleteBackup(filename); + await this.backup.deleteBackup(filename); this.audit.writeAudit({ userId: user.id, action: 'backup.delete', resource: filename, ip: getClientIp(req) }); return { success: true }; } diff --git a/server/src/nest/backup/backup.impl.ts b/server/src/nest/backup/backup.impl.ts index c78f28ad6..c362b6009 100644 --- a/server/src/nest/backup/backup.impl.ts +++ b/server/src/nest/backup/backup.impl.ts @@ -10,6 +10,7 @@ import { invalidatePermissionsCache } from '../permissions/permissions-cache'; import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths'; import { stageExtractedPluginTrees, applyStagedRestoreNow } from '../plugins/plugin-backup'; import { snapshotAllPluginDataDbs } from '../plugins/host/plugin-data.service'; +import type { StorageService } from '../storage/storage.service'; // --------------------------------------------------------------------------- // Paths @@ -84,8 +85,8 @@ export function backupFilePath(filename: string): string { return path.join(backupsDir, filename); } -export function backupFileExists(filename: string): boolean { - return fs.existsSync(path.join(backupsDir, filename)); +export function backupFileExists(storage: StorageService, filename: string): Promise { + return storage.exists('backups', filename); } // --------------------------------------------------------------------------- @@ -122,21 +123,21 @@ export interface BackupInfo { created_at: string; } -export function listBackups(): BackupInfo[] { - ensureBackupsDir(); - return fs.readdirSync(backupsDir) - .filter(f => f.endsWith('.zip')) - .map(filename => { - const filePath = path.join(backupsDir, filename); - const stat = fs.statSync(filePath); - return { - filename, - size: stat.size, - sizeText: formatSize(stat.size), - created_at: stat.mtime.toISOString(), - }; - }) - .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); +export async function listBackups(storage: StorageService): Promise { + const backups: BackupInfo[] = []; + for await (const obj of storage.list('backups')) { + // storage.list() recurses; the legacy readdir was single-level. Nested keys + // (a restore-* staging tree when data and uploads map to the same dir) and + // non-zip files must not surface. + if (obj.key.includes('/') || !obj.key.endsWith('.zip')) continue; + backups.push({ + filename: obj.key, + size: obj.size, + sizeText: formatSize(obj.size), + created_at: new Date(obj.mtimeMs).toISOString(), + }); + } + return backups.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); } // --------------------------------------------------------------------------- @@ -482,9 +483,8 @@ export async function restoreFromZip(zipPath: string): Promise { // Delete backup // --------------------------------------------------------------------------- -export function deleteBackup(filename: string): void { - const filePath = path.join(backupsDir, filename); - fs.unlinkSync(filePath); +export function deleteBackup(storage: StorageService, filename: string): Promise { + return storage.delete('backups', filename); } // --------------------------------------------------------------------------- diff --git a/server/src/nest/backup/backup.module.ts b/server/src/nest/backup/backup.module.ts index 432430cd1..779a5cb46 100644 --- a/server/src/nest/backup/backup.module.ts +++ b/server/src/nest/backup/backup.module.ts @@ -5,9 +5,10 @@ import { AutoBackupJob } from './auto-backup.job'; import { AuditModule } from '../audit/audit.module'; import { SchedulingModule } from '../scheduling/scheduling.module'; import { AppConfigModule } from '../app-config/app-config.module'; +import { StorageModule } from '../storage/storage.module'; @Module({ - imports: [AppConfigModule, AuditModule, SchedulingModule], + imports: [AppConfigModule, AuditModule, SchedulingModule, StorageModule], controllers: [BackupController], providers: [BackupService, AutoBackupJob], }) diff --git a/server/src/nest/backup/backup.service.ts b/server/src/nest/backup/backup.service.ts index e112a85c1..95335cd7a 100644 --- a/server/src/nest/backup/backup.service.ts +++ b/server/src/nest/backup/backup.service.ts @@ -1,4 +1,5 @@ import { Injectable } from '@nestjs/common'; +import { StorageService } from '../storage/storage.service'; import * as svc from './backup.impl'; /** @@ -13,14 +14,16 @@ import * as svc from './backup.impl'; */ @Injectable() export class BackupService { - listBackups() { return svc.listBackups(); } + constructor(private readonly storage: StorageService) {} + + listBackups() { return svc.listBackups(this.storage); } createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(prefix); } restoreFromZip(zipPath: string) { return svc.restoreFromZip(zipPath); } - deleteBackup(filename: string) { return svc.deleteBackup(filename); } + deleteBackup(filename: string) { return svc.deleteBackup(this.storage, filename); } isValidBackupFilename(filename: string) { return svc.isValidBackupFilename(filename); } backupFilePath(filename: string) { return svc.backupFilePath(filename); } - backupFileExists(filename: string) { return svc.backupFileExists(filename); } + backupFileExists(filename: string) { return svc.backupFileExists(this.storage, filename); } checkRateLimit(key: string, maxAttempts: number, windowMs: number) { return svc.checkRateLimit(key, maxAttempts, windowMs); } get rateWindow() { return svc.BACKUP_RATE_WINDOW; } diff --git a/server/tests/integration/backup.test.ts b/server/tests/integration/backup.test.ts index c462e79d2..b8d1b8cda 100644 --- a/server/tests/integration/backup.test.ts +++ b/server/tests/integration/backup.test.ts @@ -334,7 +334,8 @@ describe('Backup delete', () => { expect(res.status).toBe(200); expect(res.body.success).toBe(true); - expect(vi.mocked(backupService.deleteBackup)).toHaveBeenCalledWith(filename); + // First arg is the app's real StorageService (BackupService forwards it). + expect(vi.mocked(backupService.deleteBackup)).toHaveBeenCalledWith(expect.anything(), filename); }); it('BACKUP-INT-009 — DELETE /backup/:filename returns 404 when not found', async () => { diff --git a/server/tests/unit/nest/backup.controller.test.ts b/server/tests/unit/nest/backup.controller.test.ts index 4bd65f136..1ad96a9de 100644 --- a/server/tests/unit/nest/backup.controller.test.ts +++ b/server/tests/unit/nest/backup.controller.test.ts @@ -93,9 +93,9 @@ describe('AdminGuard (used by BackupController)', () => { }); describe('BackupController', () => { - it('GET /list returns backups, 500 on error', () => { - expect(bc(svc({ listBackups: vi.fn().mockReturnValue([{ filename: 'a.zip' }]) } as Partial)).list()).toEqual({ backups: [{ filename: 'a.zip' }] }); - expect(thrown(() => bc(svc({ listBackups: vi.fn(() => { throw new Error('io'); }) } as Partial)).list())).toEqual({ status: 500, body: { error: 'Error loading backups' } }); + it('GET /list returns backups, 500 on error', async () => { + await expect(bc(svc({ listBackups: vi.fn().mockResolvedValue([{ filename: 'a.zip' }]) } as Partial)).list()).resolves.toEqual({ backups: [{ filename: 'a.zip' }] }); + expect(await thrownAsync(() => bc(svc({ listBackups: vi.fn(() => { throw new Error('io'); }) } as Partial)).list())).toEqual({ status: 500, body: { error: 'Error loading backups' } }); }); it('POST /create 429 when rate-limited, else creates + audits', async () => { @@ -106,11 +106,11 @@ describe('BackupController', () => { expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.create', resource: 'b.zip' })); }); - it('GET /download 400 invalid / 404 missing, else res.download', () => { + it('GET /download 400 invalid / 404 missing, else res.download', async () => { const res = { download: vi.fn() } as unknown as Response; - expect(thrown(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).download('x', res))).toEqual({ status: 400, body: { error: 'Invalid filename' } }); - expect(thrown(() => bc(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).download('x.zip', res))).toEqual({ status: 404, body: { error: 'Backup not found' } }); - bc(svc()).download('x.zip', res); + expect(await thrownAsync(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).download('x', res))).toEqual({ status: 400, body: { error: 'Invalid filename' } }); + expect(await thrownAsync(() => bc(svc({ backupFileExists: vi.fn().mockResolvedValue(false) })).download('x.zip', res))).toEqual({ status: 404, body: { error: 'Backup not found' } }); + await bc(svc()).download('x.zip', res); expect(res.download).toHaveBeenCalledWith('/b/x.zip', 'x.zip'); }); @@ -187,21 +187,24 @@ describe('BackupController', () => { expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.auto_settings' })); }); - it('DELETE /:filename 400/404, else deletes + audits', () => { - expect(thrown(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).remove(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } }); - expect(thrown(() => bc(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).remove(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } }); + it('DELETE /:filename 400/404, else deletes + audits', async () => { + expect(await thrownAsync(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).remove(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } }); + expect(await thrownAsync(() => bc(svc({ backupFileExists: vi.fn().mockResolvedValue(false) })).remove(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } }); const deleteBackup = vi.fn(); - expect(bc(svc({ deleteBackup } as Partial)).remove(user, 'x.zip', req)).toEqual({ success: true }); + await expect(bc(svc({ deleteBackup } as Partial)).remove(user, 'x.zip', req)).resolves.toEqual({ success: true }); expect(deleteBackup).toHaveBeenCalledWith('x.zip'); }); }); describe('BackupService (wrapper)', () => { - const wrapper = new RealBackupService(); + // The impl module is fully mocked above, so an empty sentinel stands in for + // the injected StorageService — the wrapper's job is passing it through. + const storage = { __sentinel: 'storage' } as unknown as import('../../../src/nest/storage/storage.service').StorageService; + const wrapper = new RealBackupService(storage); it('forwards every call straight to the legacy backup service', async () => { expect(wrapper.listBackups()).toEqual([{ filename: 'svc.zip' }]); - expect(backupSvc.listBackups).toHaveBeenCalled(); + expect(backupSvc.listBackups).toHaveBeenCalledWith(storage); await expect(wrapper.createBackup()).resolves.toEqual({ filename: 'svc.zip', size: 5 }); expect(backupSvc.createBackup).toHaveBeenCalled(); @@ -210,7 +213,7 @@ describe('BackupService (wrapper)', () => { expect(backupSvc.restoreFromZip).toHaveBeenCalledWith('/tmp/a.zip'); wrapper.deleteBackup('svc.zip'); - expect(backupSvc.deleteBackup).toHaveBeenCalledWith('svc.zip'); + expect(backupSvc.deleteBackup).toHaveBeenCalledWith(storage, 'svc.zip'); expect(wrapper.isValidBackupFilename('svc.zip')).toBe(true); expect(backupSvc.isValidBackupFilename).toHaveBeenCalledWith('svc.zip'); @@ -219,7 +222,7 @@ describe('BackupService (wrapper)', () => { expect(backupSvc.backupFilePath).toHaveBeenCalledWith('svc.zip'); expect(wrapper.backupFileExists('svc.zip')).toBe(true); - expect(backupSvc.backupFileExists).toHaveBeenCalledWith('svc.zip'); + expect(backupSvc.backupFileExists).toHaveBeenCalledWith(storage, 'svc.zip'); expect(wrapper.checkRateLimit('ip', 3, 1000)).toBe(true); expect(backupSvc.checkRateLimit).toHaveBeenCalledWith('ip', 3, 1000); diff --git a/server/tests/unit/nest/backup.impl.test.ts b/server/tests/unit/nest/backup.impl.test.ts index 62a8a143d..b3859209e 100644 --- a/server/tests/unit/nest/backup.impl.test.ts +++ b/server/tests/unit/nest/backup.impl.test.ts @@ -78,6 +78,36 @@ import { backupFileExists, listBackups, } from '../../../src/nest/backup/backup.impl'; +import type { StorageService } from '../../../src/nest/storage/storage.service'; + +// --------------------------------------------------------------------------- +// Storage stub — backup.impl functions receive StorageService as a parameter +// (BackupService injects it and forwards). This file mocks fs wholesale, so a +// real LocalDriver would see the mocked fs: use plain stub objects instead. +// --------------------------------------------------------------------------- + +function stubStorage(overrides: Record = {}): StorageService { + return { + // async generator; tests override with listOf(...) entries + list: vi.fn(async function* () {}), + stat: vi.fn(async () => null), + exists: vi.fn(async () => false), + delete: vi.fn(async () => {}), + put: vi.fn(async () => {}), + getStream: vi.fn(), + sendToResponse: vi.fn(async () => {}), + withLocalFile: vi.fn(async (_c: string, _k: string, fn: (p: string) => Promise) => fn('/stub/local/path')), + spoolDirFor: vi.fn(() => '/stub/spool'), + tempDir: vi.fn(() => '/stub/tmp'), + health: vi.fn(() => ({ replicaFailures: [] })), + ...overrides, + } as unknown as StorageService; +} + +const listOf = (entries: Array<{ key: string; size?: number; mtimeMs?: number }>) => + vi.fn(async function* () { + for (const e of entries) yield { size: 0, mtimeMs: 0, ...e }; + }); // --------------------------------------------------------------------------- // formatSize @@ -633,25 +663,22 @@ describe('BACKUP-037 deleteBackup', () => { vi.clearAllMocks(); }); - it('BACKUP-037a — happy path: calls unlinkSync with correct path', () => { - fsMock.unlinkSync.mockReturnValue(undefined); + it('BACKUP-037a — happy path: deletes through storage under the backups category', async () => { + const storage = stubStorage(); - deleteBackup('backup-2026-04-06T12-00-00.zip'); + await deleteBackup(storage, 'backup-2026-04-06T12-00-00.zip'); - expect(fsMock.unlinkSync).toHaveBeenCalledOnce(); - expect(fsMock.unlinkSync).toHaveBeenCalledWith( - expect.stringContaining('backup-2026-04-06T12-00-00.zip') - ); + expect(storage.delete).toHaveBeenCalledOnce(); + expect(storage.delete).toHaveBeenCalledWith('backups', 'backup-2026-04-06T12-00-00.zip'); }); - it('BACKUP-037b — throws when unlinkSync throws (file not found)', () => { - fsMock.unlinkSync.mockImplementation(() => { - const err: NodeJS.ErrnoException = new Error('ENOENT: no such file or directory'); - err.code = 'ENOENT'; - throw err; - }); + it('BACKUP-037b — propagates a storage delete failure', async () => { + // Note: storage.delete is idempotent on a MISSING object (route parity holds + // because the controller pre-checks existence and 404s); this pins that a + // real backend failure still surfaces. + const storage = stubStorage({ delete: vi.fn(async () => { throw new Error('EIO: i/o error'); }) }); - expect(() => deleteBackup('backup-missing.zip')).toThrow('ENOENT'); + await expect(deleteBackup(storage, 'backup-missing.zip')).rejects.toThrow('EIO'); }); }); @@ -894,17 +921,15 @@ describe('BACKUP-040 backupFileExists', () => { vi.clearAllMocks(); }); - it('BACKUP-040a — returns true when existsSync returns true', () => { - fsMock.existsSync.mockReturnValue(true); - expect(backupFileExists('backup-2026-01-01T00-00-00.zip')).toBe(true); - expect(fsMock.existsSync).toHaveBeenCalledWith( - expect.stringContaining('backup-2026-01-01T00-00-00.zip') - ); + it('BACKUP-040a — returns true when storage.exists resolves true', async () => { + const storage = stubStorage({ exists: vi.fn(async () => true) }); + await expect(backupFileExists(storage, 'backup-2026-01-01T00-00-00.zip')).resolves.toBe(true); + expect(storage.exists).toHaveBeenCalledWith('backups', 'backup-2026-01-01T00-00-00.zip'); }); - it('BACKUP-040b — returns false when existsSync returns false', () => { - fsMock.existsSync.mockReturnValue(false); - expect(backupFileExists('backup-missing.zip')).toBe(false); + it('BACKUP-040b — returns false when storage.exists resolves false', async () => { + const storage = stubStorage({ exists: vi.fn(async () => false) }); + await expect(backupFileExists(storage, 'backup-missing.zip')).resolves.toBe(false); }); }); @@ -915,23 +940,20 @@ describe('BACKUP-040 backupFileExists', () => { describe('BACKUP-041 listBackups', () => { beforeEach(() => { vi.clearAllMocks(); - // ensureBackupsDir: backupsDir already exists so mkdirSync is not called - fsMock.existsSync.mockReturnValue(true); }); - it('BACKUP-041a — returns empty array when no .zip files in directory', () => { - fsMock.readdirSync.mockReturnValue([]); - expect(listBackups()).toEqual([]); + it('BACKUP-041a — returns empty array when the category has no objects', async () => { + const storage = stubStorage(); + await expect(listBackups(storage)).resolves.toEqual([]); + expect(storage.list).toHaveBeenCalledWith('backups'); }); - it('BACKUP-041b — returns BackupInfo array for each .zip file', () => { - fsMock.readdirSync.mockReturnValue(['backup-2026-01-01T00-00-00.zip']); - fsMock.statSync.mockReturnValue({ - size: 1024, - mtime: new Date('2026-01-01T00:00:00Z'), + it('BACKUP-041b — returns BackupInfo for each .zip object', async () => { + const storage = stubStorage({ + list: listOf([{ key: 'backup-2026-01-01T00-00-00.zip', size: 1024, mtimeMs: Date.parse('2026-01-01T00:00:00Z') }]), }); - const result = listBackups(); + const result = await listBackups(storage); expect(result).toHaveLength(1); expect(result[0].filename).toBe('backup-2026-01-01T00-00-00.zip'); @@ -940,37 +962,47 @@ describe('BACKUP-041 listBackups', () => { expect(result[0].created_at).toBe('2026-01-01T00:00:00.000Z'); }); - it('BACKUP-041c — sorts results newest-first', () => { - fsMock.readdirSync.mockReturnValue([ - 'backup-2026-01-01T00-00-00.zip', - 'backup-2026-06-01T00-00-00.zip', - ]); - fsMock.statSync.mockImplementation((p: string) => { - if (String(p).includes('2026-01-01')) { - return { size: 512, mtime: new Date('2026-01-01T00:00:00Z') }; - } - return { size: 2048, mtime: new Date('2026-06-01T00:00:00Z') }; + it('BACKUP-041c — sorts results newest-first by mtime', async () => { + const storage = stubStorage({ + list: listOf([ + { key: 'backup-2026-01-01T00-00-00.zip', size: 512, mtimeMs: Date.parse('2026-01-01T00:00:00Z') }, + { key: 'backup-2026-06-01T00-00-00.zip', size: 2048, mtimeMs: Date.parse('2026-06-01T00:00:00Z') }, + ]), }); - const result = listBackups(); + const result = await listBackups(storage); expect(result).toHaveLength(2); expect(result[0].filename).toBe('backup-2026-06-01T00-00-00.zip'); expect(result[1].filename).toBe('backup-2026-01-01T00-00-00.zip'); }); - it('BACKUP-041d — filters out non-.zip files', () => { - fsMock.readdirSync.mockReturnValue([ - 'backup-2026-01-01T00-00-00.zip', - 'README.txt', - 'backup-partial.tar.gz', - ]); - fsMock.statSync.mockReturnValue({ - size: 1024, - mtime: new Date('2026-01-01T00:00:00Z'), + it('BACKUP-041d — filters out non-.zip objects', async () => { + const storage = stubStorage({ + list: listOf([ + { key: 'backup-2026-01-01T00-00-00.zip', size: 1024, mtimeMs: Date.parse('2026-01-01T00:00:00Z') }, + { key: 'README.txt' }, + { key: 'backup-partial.tar.gz' }, + ]), }); - const result = listBackups(); + const result = await listBackups(storage); + + expect(result).toHaveLength(1); + expect(result[0].filename).toBe('backup-2026-01-01T00-00-00.zip'); + }); + + it('BACKUP-041e — skips nested keys (storage.list recurses; the legacy readdir was single-level)', async () => { + // A restore-* staging tree only sits under the backups root when an install + // maps data and uploads to the same directory — it must not surface. + const storage = stubStorage({ + list: listOf([ + { key: 'restore-123/uploads/x.zip' }, + { key: 'backup-2026-01-01T00-00-00.zip', size: 1024, mtimeMs: Date.parse('2026-01-01T00:00:00Z') }, + ]), + }); + + const result = await listBackups(storage); expect(result).toHaveLength(1); expect(result[0].filename).toBe('backup-2026-01-01T00-00-00.zip');