feat: Admin Area System: Database Backup/Restore and Danger Zone

This commit is contained in:
OpenVelo Agent
2026-07-23 12:10:37 +00:00
parent 785d56c02d
commit 7b9be24013
34 changed files with 3378 additions and 53 deletions
+215
View File
@@ -0,0 +1,215 @@
// Resolve a stable per-suite upload directory BEFORE AppModule is imported so
// the @nestjs/config validator picks it up at module-decoration time. We
// don't care about the exact path for the test runner — the absolute path
// just needs to be writable and consistent for the lifetime of this worker.
const TEST_UPLOAD_DIR = `/tmp/hipctf-danger-zone-${process.pid}-${Date.now()}`;
try {
fs.mkdirSync(TEST_UPLOAD_DIR, { recursive: true });
} catch {
// ignore
}
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
process.env.UPLOAD_SIZE_LIMIT = '5mb';
process.env.UPLOAD_DIR = TEST_UPLOAD_DIR;
process.env.NODE_ENV = 'test';
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { getDataSourceToken } from '@nestjs/typeorm';
import cookieParser from 'cookie-parser';
import * as express from 'express';
import * as fs from 'fs';
import * as path from 'path';
import request from 'supertest';
import { CookieAccessInfo } from 'cookiejar';
import { AppModule } from '../../backend/src/app.module';
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
import { CsrfMiddleware } from '../../backend/src/common/middleware/csrf.middleware';
import { ConfigService } from '@nestjs/config';
import { DangerZoneService } from '../../backend/src/modules/admin/system/danger-zone.service';
import { initDb } from './db-helper';
async function csrfHeader(agent: any): Promise<string> {
const cookies = agent.jar.getCookies(CookieAccessInfo.All);
return (cookies as any[]).find((c: any) => c.name === 'csrf').value as string;
}
async function loginAgent(
app: INestApplication,
username: string,
password: string,
): Promise<{ agent: any; token: string }> {
const agent = request.agent(app.getHttpServer());
await agent.get('/api/v1/auth/csrf');
const csrf = await csrfHeader(agent);
const res = await agent
.post('/api/v1/auth/login')
.set('X-CSRF-Token', csrf)
.send({ username, password })
.expect(201);
return { agent, token: res.body.accessToken };
}
describe('Job 871: Danger zone preservation rules', () => {
let app: INestApplication;
let admin: { agent: any; token: string };
let csrf: string;
const uploadDir = TEST_UPLOAD_DIR;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.use(express.json({ limit: '10mb' }));
const csrfMw = new CsrfMiddleware(app.get(ConfigService));
app.use((req: any, res: any, next: any) => csrfMw.use(req, res, next));
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
await initDb(app);
await request(app.getHttpServer())
.post('/api/v1/auth/register-first-admin')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
admin = await loginAgent(app, 'admin', 'Sup3rSecret!Pass');
csrf = await csrfHeader(admin.agent);
// Add a player + a solve by inserting a row directly (so we don't depend on challenges being provisioned).
const directSql = async (sql: string) => {
const ds = app.get('DatabaseModule') ;
const dataSource = app.get('DataSource' as any);
void ds;
await dataSource.query(sql);
};
const dataSource = app.get(getDataSourceToken());
const playerId = 'p-1';
const catId = 'cat-1';
const chId = 'ch-1';
await dataSource.query(
`INSERT INTO user (id,username,password_hash,role,status,created_at) VALUES (?,?,?,?,?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
[playerId, 'player1', 'X', 'player', 'enabled'],
);
await dataSource.query(
`INSERT INTO category (id,system_key,name,abbreviation,description,icon_path,created_at,updated_at) VALUES (?,NULL,'Custom','CUS','','',strftime('%Y-%m-%dT%H:%M:%fZ','now'),strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
[catId],
);
await dataSource.query(
`INSERT INTO challenge (id,name,description_md,category_id,difficulty,initial_points,minimum_points,decay_solves,flag,protocol,port,ip_address,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,strftime('%Y-%m-%dT%H:%M:%fZ','now'),strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
[chId, 'Test', '', catId, 'LOW', 100, 50, 10, 'flag{}', 'WEB', null, '', 1],
);
await dataSource.query(
`INSERT INTO solve (id,challenge_id,user_id,solved_at,points_awarded,base_points,rank_bonus,is_first,is_second,is_third) VALUES (?,?,?,strftime('%Y-%m-%dT%H:%M:%fZ','now'),?,?,?,?,?,?)`,
['s-1', chId, playerId, 100, 100, 0, 1, 0, 0],
);
void directSql;
});
afterAll(async () => {
await app.close();
if (uploadDir && fs.existsSync(uploadDir)) {
try {
fs.rmSync(uploadDir, { recursive: true, force: true });
} catch {
// ignore
}
}
});
it('reset-scores deletes every solve while preserving users + categories + challenges', async () => {
const dataSource = app.get(getDataSourceToken());
const before = await dataSource.query('SELECT COUNT(*) AS c FROM solve');
expect(Number((before as any[])[0].c)).toBeGreaterThanOrEqual(1);
const issued = await admin.agent
.post('/api/v1/admin/system/confirmations')
.set('Authorization', `Bearer ${admin.token}`)
.set('X-CSRF-Token', csrf)
.send({ operation: 'reset-scores', password: 'Sup3rSecret!Pass' })
.expect(200);
const res = await admin.agent
.post('/api/v1/admin/system/scores/reset')
.set('Authorization', `Bearer ${admin.token}`)
.set('X-CSRF-Token', csrf)
.send({ operation: 'reset-scores', token: issued.body.token })
.expect(200);
expect(res.body.ok).toBe(true);
expect(res.body.solvesRemoved).toBeGreaterThanOrEqual(1);
const afterSolves = await dataSource.query('SELECT COUNT(*) AS c FROM solve');
expect(Number((afterSolves as any[])[0].c)).toBe(0);
const users = await dataSource.query('SELECT COUNT(*) AS c FROM user');
expect(Number((users as any[])[0].c)).toBeGreaterThanOrEqual(2);
const cats = await dataSource.query('SELECT COUNT(*) AS c FROM category');
expect(Number((cats as any[])[0].c)).toBeGreaterThanOrEqual(1);
const chs = await dataSource.query('SELECT COUNT(*) AS c FROM challenge');
expect(Number((chs as any[])[0].c)).toBeGreaterThanOrEqual(1);
});
it('wipe-challenges removes every challenge + solve + file but keeps users + categories', async () => {
const dataSource = app.get(getDataSourceToken());
// seed a challenge file row so we can confirm preserves rule
await dataSource.query(
`INSERT INTO challenge_file (id,challenge_id,original_filename,stored_filename,mime_type,size_bytes,created_at) VALUES (?,?,?,?,?,?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
['cf-1', 'ch-1', 'readme.txt', 'cf-1.bin', 'text/plain', 0],
);
// Pre-create a real challenge file on disk so the physical-delete
// step actually has something to remove.
const challengesDir = path.join(uploadDir, 'challenges');
fs.mkdirSync(challengesDir, { recursive: true });
fs.writeFileSync(path.join(challengesDir, 'cf-1.bin'), Buffer.from('LIVE-CHALLENGE-BYTES'));
// Sanity: confirm the DangerZoneService resolved to our temp dir.
const danger = app.get(DangerZoneService);
expect((danger as any).uploadDir).toBe(uploadDir);
void danger;
const issued = await admin.agent
.post('/api/v1/admin/system/confirmations')
.set('Authorization', `Bearer ${admin.token}`)
.set('X-CSRF-Token', csrf)
.send({ operation: 'wipe-challenges', password: 'Sup3rSecret!Pass' })
.expect(200);
const res = await admin.agent
.post('/api/v1/admin/system/challenges/wipe')
.set('Authorization', `Bearer ${admin.token}`)
.set('X-CSRF-Token', csrf)
.send({ operation: 'wipe-challenges', token: issued.body.token })
.expect(200);
expect(res.body.ok).toBe(true);
expect(res.body.challengesRemoved).toBeGreaterThanOrEqual(1);
const challenges = await dataSource.query('SELECT COUNT(*) AS c FROM challenge');
expect(Number((challenges as any[])[0].c)).toBe(0);
const files = await dataSource.query('SELECT COUNT(*) AS c FROM challenge_file');
expect(Number((files as any[])[0].c)).toBe(0);
const solves = await dataSource.query('SELECT COUNT(*) AS c FROM solve');
expect(Number((solves as any[])[0].c)).toBe(0);
const users = await dataSource.query('SELECT COUNT(*) AS c FROM user');
expect(Number((users as any[])[0].c)).toBeGreaterThanOrEqual(2);
const cats = await dataSource.query('SELECT COUNT(*) AS c FROM category');
expect(Number((cats as any[])[0].c)).toBeGreaterThanOrEqual(1);
// Live challenge-files directory must be physically empty/absent.
if (fs.existsSync(challengesDir)) {
const remaining = fs.readdirSync(challengesDir);
expect(remaining).toEqual([]);
}
// Staging snapshot must have been cleaned up after the disk delete.
const snapshotLeftover = fs
.readdirSync(uploadDir)
.some((entry) => entry.startsWith('challenges.wipe-stage-'));
expect(snapshotLeftover).toBe(false);
});
});