AI Implementation feature(871): Admin Area System: Database Backup/Restore and Danger Zone (#61)
This commit was merged in pull request #61.
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_SIZE_LIMIT = '5mb';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import * as express from 'express';
|
||||
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 { initDb } from './db-helper';
|
||||
|
||||
async function buildAgent(
|
||||
app: INestApplication,
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<{ agent: any; token: string }> {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
await agent.get('/api/v1/auth/csrf');
|
||||
const csrf = (agent.jar.getCookies(CookieAccessInfo.All) as any).find((c: any) => c.name === 'csrf');
|
||||
const res = await agent
|
||||
.post('/api/v1/auth/login')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.send({ username, password })
|
||||
.expect(201);
|
||||
(agent as any).accessToken = res.body.accessToken as string;
|
||||
return { agent, token: res.body.accessToken as string };
|
||||
}
|
||||
|
||||
async function csrfHeaderFor(agent: any): Promise<string> {
|
||||
const cookies = agent.jar.getCookies(CookieAccessInfo.All);
|
||||
return (cookies as any[]).find((c: any) => c.name === 'csrf').value as string;
|
||||
}
|
||||
|
||||
describe('Job 871: System endpoint authorization', () => {
|
||||
let app: INestApplication;
|
||||
let adminAgent: any;
|
||||
let adminToken: string;
|
||||
let playerAgent: any;
|
||||
let playerToken: string;
|
||||
|
||||
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);
|
||||
|
||||
adminAgent = request.agent(app.getHttpServer());
|
||||
await adminAgent.get('/api/v1/auth/csrf');
|
||||
const csrfAdmin = (adminAgent.jar.getCookies(CookieAccessInfo.All) as any).find((c: any) => c.name === 'csrf');
|
||||
const adminLogin = await adminAgent
|
||||
.post('/api/v1/auth/login')
|
||||
.set('X-CSRF-Token', csrfAdmin.value)
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = adminLogin.body.accessToken;
|
||||
(adminAgent as any).accessToken = adminToken;
|
||||
|
||||
await adminAgent
|
||||
.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrfAdmin.value)
|
||||
.send({ username: 'player1', password: 'Sup3rSecret!Pass', role: 'player' })
|
||||
.expect(201);
|
||||
|
||||
const playerLogin = await adminAgent
|
||||
.post('/api/v1/auth/login')
|
||||
.set('X-CSRF-Token', csrfAdmin.value)
|
||||
.send({ username: 'player1', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
playerToken = playerLogin.body.accessToken;
|
||||
|
||||
playerAgent = request.agent(app.getHttpServer());
|
||||
await playerAgent.get('/api/v1/auth/csrf');
|
||||
const csrfPlayer = (playerAgent.jar.getCookies(CookieAccessInfo.All) as any).find((c: any) => c.name === 'csrf');
|
||||
await playerAgent
|
||||
.post('/api/v1/auth/login')
|
||||
.set('X-CSRF-Token', csrfPlayer.value)
|
||||
.send({ username: 'player1', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
(playerAgent as any).accessToken = playerToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /admin/system/backup without token returns 401', async () => {
|
||||
await request(app.getHttpServer()).get('/api/v1/admin/system/backup').expect(401);
|
||||
});
|
||||
|
||||
it('GET /admin/system/backup with player JWT returns 403', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/system/backup')
|
||||
.set('Authorization', `Bearer ${playerToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('GET /admin/system/backup with admin JWT returns 200 application/json', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/system/backup')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.expect(200);
|
||||
expect(res.headers['content-type']).toMatch(/application\/json/);
|
||||
expect(typeof res.text).toBe('string');
|
||||
const parsed = JSON.parse(res.text);
|
||||
expect(parsed.format).toBe('hipctf-system-backup');
|
||||
expect(parsed.tables).toBeDefined();
|
||||
expect(Array.isArray(parsed.uploads)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { TypeOrmModule, getDataSourceToken } from '@nestjs/typeorm';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { validateEnv } from '../../backend/src/config/env.schema';
|
||||
import { BackupService } from '../../backend/src/modules/admin/system/backup.service';
|
||||
import { UserEntity } from '../../backend/src/database/entities/user.entity';
|
||||
import { SettingEntity } from '../../backend/src/database/entities/setting.entity';
|
||||
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
|
||||
import { ChallengeEntity } from '../../backend/src/database/entities/challenge.entity';
|
||||
import { ChallengeFileEntity } from '../../backend/src/database/entities/challenge-file.entity';
|
||||
import { SolveEntity } from '../../backend/src/database/entities/solve.entity';
|
||||
import { RefreshTokenEntity } from '../../backend/src/database/entities/refresh-token.entity';
|
||||
import { BlogPostEntity } from '../../backend/src/database/entities/blog-post.entity';
|
||||
import { AdminOperationTokenEntity } from '../../backend/src/database/entities/admin-operation-token.entity';
|
||||
import { InitSchema1700000000000 } from '../../backend/src/database/migrations/1700000000000-InitSchema';
|
||||
import { SeedSystemData1700000000100 } from '../../backend/src/database/migrations/1700000000100-SeedSystemData';
|
||||
import { AddCategoryTimestampsAndUniqueAbbrev1700000000200 } from '../../backend/src/database/migrations/1700000000200-AddCategoryTimestampsAndUniqueAbbrev';
|
||||
import { UpdateSystemCategoryKeys1700000000300 } from '../../backend/src/database/migrations/1700000000300-UpdateSystemCategoryKeys';
|
||||
import { RepairCategorySchemaAndSystemCategories1700000000400 } from '../../backend/src/database/migrations/1700000000400-RepairCategorySchemaAndSystemCategories';
|
||||
import { UpgradeChallengeAdminSchema1700000000500 } from '../../backend/src/database/migrations/1700000000500-UpgradeChallengeAdminSchema';
|
||||
import { AddAdminOperationTokens1700000000900 } from '../../backend/src/database/migrations/1700000000900-AddAdminOperationTokens';
|
||||
|
||||
describe('Job 871: BackupService captures + filters', () => {
|
||||
let moduleRef: any;
|
||||
let backup: BackupService;
|
||||
let uploadDir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hipctf-sys-backup-'));
|
||||
process.env.UPLOAD_DIR = uploadDir;
|
||||
fs.writeFileSync(path.join(uploadDir, 'logo.bin'), Buffer.from('LOGO-BYTES'));
|
||||
fs.mkdirSync(path.join(uploadDir, 'icons'), { recursive: true });
|
||||
fs.writeFileSync(path.join(uploadDir, 'icons', 'icon.png'), Buffer.from('ICON'));
|
||||
|
||||
moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
|
||||
TypeOrmModule.forRoot({
|
||||
type: 'better-sqlite3',
|
||||
database: ':memory:',
|
||||
entities: [
|
||||
UserEntity, SettingEntity, CategoryEntity, ChallengeEntity,
|
||||
ChallengeFileEntity, SolveEntity, RefreshTokenEntity, BlogPostEntity,
|
||||
AdminOperationTokenEntity,
|
||||
],
|
||||
migrations: [
|
||||
InitSchema1700000000000,
|
||||
SeedSystemData1700000000100,
|
||||
AddCategoryTimestampsAndUniqueAbbrev1700000000200,
|
||||
UpdateSystemCategoryKeys1700000000300,
|
||||
RepairCategorySchemaAndSystemCategories1700000000400,
|
||||
UpgradeChallengeAdminSchema1700000000500,
|
||||
AddAdminOperationTokens1700000000900,
|
||||
],
|
||||
migrationsRun: true,
|
||||
synchronize: false,
|
||||
}),
|
||||
],
|
||||
providers: [BackupService],
|
||||
}).compile();
|
||||
backup = moduleRef.get(BackupService);
|
||||
const dataSource = moduleRef.get(getDataSourceToken());
|
||||
await dataSource.query(
|
||||
`INSERT INTO user (id,username,password_hash,role,status,created_at) VALUES (?,?,?,?,?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
|
||||
['u-1', 'alice', 'HASH', 'player', 'enabled'],
|
||||
);
|
||||
await dataSource.query(`INSERT INTO setting (key,value) VALUES (?,?)`, ['testCustomKey', 'HIPCTF']);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await moduleRef?.close();
|
||||
if (uploadDir && fs.existsSync(uploadDir)) {
|
||||
try {
|
||||
fs.rmSync(uploadDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('captures every application table and base64-encoded uploads', async () => {
|
||||
const obj = await backup.build();
|
||||
expect(obj.format).toBe('hipctf-system-backup');
|
||||
expect(obj.tables.user.length).toBeGreaterThanOrEqual(1);
|
||||
expect(obj.tables.setting.length).toBeGreaterThanOrEqual(1);
|
||||
expect(obj.uploads.length).toBeGreaterThanOrEqual(1);
|
||||
const logo = obj.uploads.find((u) => u.path.includes('logo.bin'));
|
||||
expect(logo).toBeDefined();
|
||||
expect(Buffer.from(logo!.dataBase64, 'base64').toString()).toBe('LOGO-BYTES');
|
||||
});
|
||||
|
||||
it('never includes operational or sqlite-internal tables', async () => {
|
||||
const obj = await backup.build();
|
||||
expect(Object.keys(obj.tables)).not.toContain('admin_operation_token');
|
||||
expect(Object.keys(obj.tables)).not.toContain('migrations');
|
||||
expect(Object.keys(obj.tables)).not.toContain('sqlite_master');
|
||||
expect(obj.tableCounts['admin_operation_token']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_SIZE_LIMIT = '5mb';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import * as express from 'express';
|
||||
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 { 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);
|
||||
(agent as any).accessToken = res.body.accessToken;
|
||||
return { agent, token: res.body.accessToken };
|
||||
}
|
||||
|
||||
describe('Job 871: Confirmation-token binding + replay rejection', () => {
|
||||
let app: INestApplication;
|
||||
let admin: { agent: any; token: string };
|
||||
let csrf: string;
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('issues a confirmation token for reset-scores', async () => {
|
||||
const res = 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);
|
||||
expect(res.body.token).toEqual(expect.any(String));
|
||||
expect(res.body.operation).toBe('reset-scores');
|
||||
expect(res.body.expiresAt).toEqual(expect.any(String));
|
||||
});
|
||||
|
||||
it('rejects confirmation requests with the wrong password', async () => {
|
||||
const res = await admin.agent
|
||||
.post('/api/v1/admin/system/confirmations')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ operation: 'reset-scores', password: 'WrongPassword!1' });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe('SYSTEM_INVALID_CREDENTIALS');
|
||||
});
|
||||
|
||||
it('rejects token requests without authentication', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/v1/admin/system/confirmations')
|
||||
.send({ operation: 'reset-scores', password: 'Sup3rSecret!Pass' });
|
||||
expect([401, 403]).toContain(res.status);
|
||||
});
|
||||
|
||||
it('rejects token reuse on the reset-scores endpoint', async () => {
|
||||
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 first = 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(first.body.ok).toBe(true);
|
||||
const second = 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([400, 409]).toContain(second.status);
|
||||
expect(['SYSTEM_TOKEN_REUSED', 'SYSTEM_TOKEN_INVALID']).toContain(second.body.code);
|
||||
});
|
||||
|
||||
it('rejects tokens issued for a different operation', async () => {
|
||||
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/challenges/wipe')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ operation: 'wipe-challenges', token: issued.body.token });
|
||||
expect(res.status).toBe(400);
|
||||
expect(['SYSTEM_TOKEN_MISMATCH', 'SYSTEM_TOKEN_INVALID']).toContain(res.body.code);
|
||||
});
|
||||
|
||||
it('rejects tokens with a fabricated value', async () => {
|
||||
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: 'not-a-real-token' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.code).toBe('SYSTEM_TOKEN_INVALID');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_SIZE_LIMIT = '5mb';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { getDataSourceToken } from '@nestjs/typeorm';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { validateEnv } from '../../backend/src/config/env.schema';
|
||||
import { RestoreService } from '../../backend/src/modules/admin/system/restore.service';
|
||||
import { FilesystemTransactionService } from '../../backend/src/modules/admin/system/filesystem-transaction.service';
|
||||
import { UserEntity } from '../../backend/src/database/entities/user.entity';
|
||||
import { SettingEntity } from '../../backend/src/database/entities/setting.entity';
|
||||
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
|
||||
import { ChallengeEntity } from '../../backend/src/database/entities/challenge.entity';
|
||||
import { ChallengeFileEntity } from '../../backend/src/database/entities/challenge-file.entity';
|
||||
import { SolveEntity } from '../../backend/src/database/entities/solve.entity';
|
||||
import { RefreshTokenEntity } from '../../backend/src/database/entities/refresh-token.entity';
|
||||
import { BlogPostEntity } from '../../backend/src/database/entities/blog-post.entity';
|
||||
import { AdminOperationTokenEntity } from '../../backend/src/database/entities/admin-operation-token.entity';
|
||||
|
||||
describe('Job 871: RestoreService validation rejects malformed archives before mutation', () => {
|
||||
let moduleRef: any;
|
||||
let restore: RestoreService;
|
||||
let dataSource: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.UPLOAD_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'hipctf-restore-uploads-'));
|
||||
moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
|
||||
TypeOrmModule.forRoot({
|
||||
type: 'better-sqlite3',
|
||||
database: ':memory:',
|
||||
entities: [
|
||||
UserEntity, SettingEntity, CategoryEntity, ChallengeEntity,
|
||||
ChallengeFileEntity, SolveEntity, RefreshTokenEntity, BlogPostEntity,
|
||||
AdminOperationTokenEntity,
|
||||
],
|
||||
synchronize: true,
|
||||
}),
|
||||
],
|
||||
providers: [RestoreService, FilesystemTransactionService],
|
||||
}).compile();
|
||||
moduleRef.init();
|
||||
dataSource = moduleRef.get(getDataSourceToken());
|
||||
restore = moduleRef.get(RestoreService);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
const dir = process.env.UPLOAD_DIR!;
|
||||
if (fs.existsSync(dir)) {
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
await moduleRef?.close();
|
||||
});
|
||||
|
||||
it('rejects empty JSON', async () => {
|
||||
await expect(restore.stageArchive('', 'admin-1')).rejects.toMatchObject({
|
||||
code: 'SYSTEM_RESTORE_VALIDATION_FAILED',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects wrong format', async () => {
|
||||
const bad = JSON.stringify({ format: 'wrong', version: 1, exportedAt: 'x', tables: {}, uploads: [] });
|
||||
await expect(restore.stageArchive(bad, 'admin-1')).rejects.toMatchObject({
|
||||
code: 'SYSTEM_RESTORE_VALIDATION_FAILED',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects base64 size mismatch', async () => {
|
||||
const bad = {
|
||||
format: 'hipctf-system-backup',
|
||||
version: 1,
|
||||
exportedAt: 'x',
|
||||
tables: {},
|
||||
uploads: [
|
||||
{
|
||||
path: 'icons/mismatch.png',
|
||||
originalFilename: 'm.png',
|
||||
mimeType: 'image/png',
|
||||
sizeBytes: 100,
|
||||
dataBase64: Buffer.from('short').toString('base64'),
|
||||
},
|
||||
],
|
||||
};
|
||||
await expect(restore.stageArchive(JSON.stringify(bad), 'admin-1')).rejects.toMatchObject({
|
||||
code: 'SYSTEM_RESTORE_VALIDATION_FAILED',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects path traversal', async () => {
|
||||
const data = Buffer.alloc(0).toString('base64');
|
||||
const bad = {
|
||||
format: 'hipctf-system-backup',
|
||||
version: 1,
|
||||
exportedAt: 'x',
|
||||
tables: {},
|
||||
uploads: [
|
||||
{
|
||||
path: '../../../etc/passwd',
|
||||
originalFilename: 'x',
|
||||
mimeType: 'application/octet-stream',
|
||||
sizeBytes: 0,
|
||||
dataBase64: data,
|
||||
},
|
||||
],
|
||||
};
|
||||
await expect(restore.stageArchive(JSON.stringify(bad), 'admin-1')).rejects.toMatchObject({
|
||||
code: 'SYSTEM_RESTORE_VALIDATION_FAILED',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not mutate live data after rejected validation', async () => {
|
||||
const users = await dataSource.query('SELECT COUNT(*) AS c FROM user');
|
||||
expect(Number((users as any[])[0]?.c ?? 0)).toBeGreaterThanOrEqual(0);
|
||||
const stagedCount = (restore as any).stages?.size ?? 0;
|
||||
expect(stagedCount).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
import {
|
||||
coerceSystemError,
|
||||
destructiveCopy,
|
||||
deriveBackupFilename,
|
||||
friendlySystemErrorMessage,
|
||||
} from '../../frontend/src/app/features/admin/system/system.pure';
|
||||
|
||||
describe('Job 871: friendlySystemErrorMessage mapping', () => {
|
||||
it('returns the friendly token-expired message for SYSTEM_TOKEN_EXPIRED', () => {
|
||||
const err = { status: 400, code: 'SYSTEM_TOKEN_EXPIRED', message: 'expired' };
|
||||
expect(friendlySystemErrorMessage('restore-backup', err)).toContain('expired');
|
||||
expect(friendlySystemErrorMessage('restore-backup', err)).toMatch(/Re-authenticate/i);
|
||||
});
|
||||
|
||||
it('returns a specific message for SYSTEM_RESTORE_ROLLED_BACK', () => {
|
||||
expect(friendlySystemErrorMessage('restore-backup', { status: 500, code: 'SYSTEM_RESTORE_ROLLED_BACK', message: 'rb' }))
|
||||
.toContain('rolled back');
|
||||
});
|
||||
|
||||
it('falls back to operation message when code is unknown', () => {
|
||||
expect(friendlySystemErrorMessage('wipe-challenges', { status: 500, code: 'WEIRD', message: 'broken' }))
|
||||
.toBe('broken');
|
||||
});
|
||||
|
||||
it('falls back to the operation default when message is empty', () => {
|
||||
expect(friendlySystemErrorMessage('reset-scores', { status: 500, code: 'WEIRD', message: '' }))
|
||||
.toContain('Reset scores failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Job 871: destructiveCopy', () => {
|
||||
it('reset-scores confirms with RESET SCORES', () => {
|
||||
expect(destructiveCopy('reset-scores').confirmation).toBe('RESET SCORES');
|
||||
});
|
||||
it('wipe-challenges confirms with WIPE CHALLENGES', () => {
|
||||
expect(destructiveCopy('wipe-challenges').confirmation).toBe('WIPE CHALLENGES');
|
||||
});
|
||||
it('restore-backup confirms with RESTORE BACKUP', () => {
|
||||
expect(destructiveCopy('restore-backup').confirmation).toBe('RESTORE BACKUP');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Job 871: deriveBackupFilename', () => {
|
||||
it('contains today date and .json', () => {
|
||||
const name = deriveBackupFilename();
|
||||
expect(name).toMatch(/^hipctf-backup-\d{4}-\d{2}-\d{2}\.json$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Job 871: coerceSystemError', () => {
|
||||
it('reads body from HttpErrorResponse shape', () => {
|
||||
const out = coerceSystemError(
|
||||
{ status: 400, error: { code: 'X', message: 'Y' } },
|
||||
'fallback',
|
||||
);
|
||||
expect(out.code).toBe('X');
|
||||
expect(out.message).toBe('Y');
|
||||
expect(out.status).toBe(400);
|
||||
});
|
||||
|
||||
it('falls back when no envelope is present', () => {
|
||||
const out = coerceSystemError(new Error('boom'), 'fallback');
|
||||
expect(out.code).toBe('INTERNAL');
|
||||
expect(out.message).toBe('boom');
|
||||
});
|
||||
|
||||
it('falls back for null', () => {
|
||||
const out = coerceSystemError(null, 'fallback');
|
||||
expect(out.code).toBe('INTERNAL');
|
||||
expect(out.message).toBe('fallback');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user