feat(m14): backup & admin (zip via fflate, admin guard, tests, e2e)

- BackupService (admin-only: createBackup zips DB+uploads via fflate to
  backups/backup-<ts>.zip, listBackups newest-first, getBackupPath with
  path-traversal guard)
- Admin backup APIs: GET/POST /api/admin/backups, GET /api/admin/backups/:filename
- Admin backups screen (admin-only) + BackupCreateButton
- Playwright globalSetup seeds a system_admin user for admin E2E
- add fflate dependency
- Unit tests (BackupService: zip content, list, admin guard, traversal) +
  e2e backup (create/list/download + non-admin 403)
This commit is contained in:
Ken Yasue
2026-06-25 02:35:35 +02:00
parent 384e61386a
commit 0026edd22b
9 changed files with 346 additions and 1 deletions

61
tests/e2e/backup.spec.ts Normal file
View File

@ -0,0 +1,61 @@
import { test, expect, type Page } from '@playwright/test';
async function login(page: Page, email: string, password: string) {
await page.goto('/login');
await page.getByLabel('メールアドレス').fill(email);
await page.getByLabel('パスワード').fill(password);
await page.getByRole('button', { name: 'ログイン' }).click();
await expect(page).toHaveURL(/\/dashboard/);
}
test.describe('backup & admin', () => {
test('admin creates, lists, and downloads a backup; non-admin is forbidden', async ({
browser,
request,
}) => {
// 管理者(globalSetup で seed 済み)でログイン
const adminContext = await browser.newContext();
const adminPage = await adminContext.newPage();
await login(adminPage, 'admin@example.com', 'admin123');
// バックアップ一覧画面
await adminPage.goto('/admin/backups');
await expect(
adminPage.getByRole('heading', { name: '管理者: バックアップ' })
).toBeVisible();
// バックアップ作成(API)
const createRes = await adminPage.request.post('/api/admin/backups');
expect(createRes.ok()).toBeTruthy();
const { backup } = (await createRes.json()) as {
backup: { filename: string };
};
// 一覧に表示
await adminPage.reload();
await expect(
adminPage.getByTestId(`backup-${backup.filename}`)
).toBeVisible();
// ダウンロード(API)
const dlRes = await adminPage.request.get(
`/api/admin/backups/${backup.filename}`
);
expect(dlRes.status()).toBe(200);
expect(dlRes.headers()['content-type']).toContain('application/zip');
// 非管理者は403
const memberEmail = `member-${Date.now()}@example.com`;
await request.post('/api/auth/register', {
data: { name: 'Member', email: memberEmail, password: 'password123' },
});
const memberContext = await browser.newContext();
const memberPage = await memberContext.newPage();
await login(memberPage, memberEmail, 'password123');
const forbidden = await memberPage.request.get('/api/admin/backups');
expect(forbidden.status()).toBe(403);
await adminContext.close();
await memberContext.close();
});
});

34
tests/e2e/globalSetup.ts Normal file
View File

@ -0,0 +1,34 @@
import bcrypt from 'bcrypt';
import fs from 'node:fs';
import path from 'node:path';
import { SqliteDatabase } from '@/lib/db/sqlite';
import { Migrator } from '@/lib/db/migrator';
import { UserRepository } from '@/repositories/UserRepository';
const ADMIN_EMAIL = 'admin@example.com';
const ADMIN_PASSWORD = 'admin123';
/**
* E2E用の初期データをセットアップする。
* - Migrationを確実に適用(開発サーバのmigrateと重複しても冪等)
* - バックアップ/管理者機能のE2Eで使用する system_admin ユーザーを生成
*/
export default async function globalSetup(): Promise<void> {
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new SqliteDatabase(dbPath);
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
new Migrator(db, migrationsDir).migrate();
const userRepo = new UserRepository(db);
if (!userRepo.findByEmail(ADMIN_EMAIL)) {
userRepo.create({
name: 'Admin',
email: ADMIN_EMAIL,
passwordHash: bcrypt.hashSync(ADMIN_PASSWORD, 10),
role: 'system_admin',
});
}
db.close();
}

View File

@ -0,0 +1,81 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { unzipSync } from 'fflate';
import { BackupService } from '@/services/BackupService';
import { ForbiddenError, NotFoundError } from '@/lib/errors';
describe('BackupService', () => {
let root: string;
let dbPath: string;
let uploadsDir: string;
let backupsDir: string;
let service: BackupService;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'backup-'));
dbPath = path.join(root, 'app.db');
uploadsDir = path.join(root, 'uploads');
backupsDir = path.join(root, 'backups');
fs.writeFileSync(dbPath, Buffer.from('fake-db-content'));
fs.mkdirSync(uploadsDir, { recursive: true });
fs.writeFileSync(path.join(uploadsDir, 'a.txt'), Buffer.from('hello'));
fs.mkdirSync(path.join(uploadsDir, 'sub'), { recursive: true });
fs.writeFileSync(
path.join(uploadsDir, 'sub', 'b.txt'),
Buffer.from('world')
);
service = new BackupService(dbPath, uploadsDir, backupsDir);
});
afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});
const admin = { id: 1, role: 'system_admin' as const };
const member = { id: 2, role: 'member' as const };
it('createBackup zips DB + uploads into backups dir', () => {
const backup = service.createBackup(admin);
expect(backup.filename).toMatch(/^backup-.+\.zip$/);
const fullPath = path.join(backupsDir, backup.filename);
expect(fs.existsSync(fullPath)).toBe(true);
expect(backup.size).toBeGreaterThan(0);
// ZIP内容を検証
const zip = new Uint8Array(fs.readFileSync(fullPath));
const unzipped = unzipSync(zip);
expect(Object.keys(unzipped)).toContain('app.db');
expect(Object.keys(unzipped)).toContain('uploads/a.txt');
expect(Object.keys(unzipped)).toContain('uploads/sub/b.txt');
});
it('listBackups returns created backups newest first', () => {
service.createBackup(admin);
const list = service.listBackups(admin);
expect(list).toHaveLength(1);
expect(list[0].filename).toMatch(/^backup-.+\.zip$/);
});
it('forbids a non-admin from creating/listing', () => {
expect(() => service.createBackup(member)).toThrow(ForbiddenError);
expect(() => service.listBackups(member)).toThrow(ForbiddenError);
});
it('getBackupPath rejects path traversal and missing files', () => {
service.createBackup(admin);
expect(() => service.getBackupPath(admin, '../evil.zip')).toThrow(
NotFoundError
);
expect(() =>
service.getBackupPath(admin, 'backup-doesnotexist.zip')
).toThrow(NotFoundError);
});
it('getBackupPath returns the path for a valid backup', () => {
const backup = service.createBackup(admin);
const p = service.getBackupPath(admin, backup.filename);
expect(fs.existsSync(p)).toBe(true);
});
});