AI Implementation feature(902): Admin Area Challenges: List, Import/Export and Add/Edit Modal 1.02 (#43)

This commit was merged in pull request #43.
This commit is contained in:
2026-07-22 21:47:52 +00:00
parent d3307c3225
commit fff0a600df
8 changed files with 351 additions and 159 deletions
@@ -0,0 +1,142 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
process.env.UPLOAD_DIR = '/tmp/hipctf-challenges-create-category-job902';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { Test } from '@nestjs/testing';
import { INestApplication } 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 { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
import { initDb } from './db-helper';
describe('Admin Challenges API - create with empty/invalid categoryId (Job 902)', () => {
let app: INestApplication;
let adminToken: string;
const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hipctf-challenges-create-cat-'));
let validCategoryId: string;
async function primeCsrf(): Promise<{ agent: any; csrf: string }> {
const server = app.getHttpServer();
const agent = request.agent(server);
await agent.get('/api/v1/auth/csrf');
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
return { agent, csrf: cookies.find((c: any) => c.name === 'csrf').value };
}
function wellFormedBody(categoryId: string): any {
return {
name: 'Missing Category Attempt',
descriptionMd: 'desc',
categoryId,
difficulty: 'MEDIUM',
initialPoints: 100,
minimumPoints: 50,
decaySolves: 10,
flag: 'flag{X}',
protocol: 'WEB',
port: null,
ipAddress: '',
enabled: true,
};
}
beforeAll(async () => {
process.env.UPLOAD_DIR = uploadDir;
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.use(express.json({ limit: '1mb' }));
const csrfMw = new CsrfMiddleware(app.get(ConfigService));
app.use((req: any, res: any, next: any) => csrfMw.use(req, res, next));
app.useGlobalPipes(new (require('@nestjs/common').ValidationPipe)({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
await initDb(app);
const catRepo: Repository<CategoryEntity> = app.get(getRepositoryToken(CategoryEntity));
const cry = await catRepo.findOne({ where: { systemKey: 'CRY' } });
if (!cry) throw new Error('expected CRY category seed');
validCategoryId = cry.id;
const server = app.getHttpServer();
await request(server).post('/api/v1/auth/register-first-admin')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
const csrfPrime = await request(server).get('/api/v1/auth/csrf');
const csrfCookie = (csrfPrime.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
const csrfToken = csrfCookie ? decodeURIComponent(csrfCookie.split(';')[0].split('=')[1]) : '';
const login = await request(server).post('/api/v1/auth/login')
.set('Cookie', `csrf=${csrfToken}`)
.set('X-CSRF-Token', csrfToken)
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
adminToken = login.body.accessToken;
});
afterAll(async () => {
await app.close();
if (fs.existsSync(uploadDir)) {
try {
fs.rmSync(uploadDir, { recursive: true, force: true });
} catch {
// ignore
}
}
});
it('rejects an empty categoryId with 400 VALIDATION_FAILED and a categoryId detail', async () => {
const { agent, csrf } = await primeCsrf();
const res = await agent
.post('/api/v1/admin/challenges')
.set('Authorization', `Bearer ${adminToken}`)
.set('X-CSRF-Token', csrf)
.send(wellFormedBody(''));
expect(res.status).toBe(400);
expect(res.body?.code).toBe('VALIDATION_FAILED');
const details = Array.isArray(res.body?.details) ? res.body.details : [];
const categoryDetail = details.find((d: any) => d.path === 'categoryId');
expect(categoryDetail).toBeDefined();
});
it('rejects a non-UUID categoryId with 400 VALIDATION_FAILED and a categoryId detail', async () => {
const { agent, csrf } = await primeCsrf();
const res = await agent
.post('/api/v1/admin/challenges')
.set('Authorization', `Bearer ${adminToken}`)
.set('X-CSRF-Token', csrf)
.send(wellFormedBody('not-a-uuid'));
expect(res.status).toBe(400);
expect(res.body?.code).toBe('VALIDATION_FAILED');
const details = Array.isArray(res.body?.details) ? res.body.details : [];
const categoryDetail = details.find((d: any) => d.path === 'categoryId');
expect(categoryDetail).toBeDefined();
});
it('accepts a valid UUID categoryId and returns 201', async () => {
const { agent, csrf } = await primeCsrf();
const res = await agent
.post('/api/v1/admin/challenges')
.set('Authorization', `Bearer ${adminToken}`)
.set('X-CSRF-Token', csrf)
.send(wellFormedBody(validCategoryId));
expect(res.status).toBe(201);
expect(res.body?.id).toBeDefined();
expect(res.body?.categoryId).toBe(validCategoryId);
});
});
@@ -0,0 +1,83 @@
import '@angular/compiler';
import { FormBuilder } from '@angular/forms';
import {
buildChallengeFormGroup,
} from '../../frontend/src/app/features/admin/challenges/challenge-form-modal.component';
import {
CATEGORY_ID_PATTERN,
ChallengeFormDefaults,
firstErrorTab,
validateChallengeForm,
} from '../../frontend/src/app/features/admin/challenges/challenge-form.pure';
function makeDefaults(overrides: Partial<ChallengeFormDefaults> = {}): ChallengeFormDefaults {
return {
name: 'Missing Category Attempt',
descriptionMd: 'desc',
categoryId: '11111111-1111-4111-8111-111111111111',
difficulty: 'MEDIUM',
initialPoints: 100,
minimumPoints: 50,
decaySolves: 10,
flag: 'flag{X}',
protocol: 'WEB',
port: null,
ipAddress: '',
enabled: true,
...overrides,
};
}
const VALID_CATEGORY_ID = '11111111-1111-4111-8111-111111111111';
describe('Job 902: challenge form Category validation', () => {
it('CATEGORY_ID_PATTERN accepts a canonical UUID v4', () => {
expect(CATEGORY_ID_PATTERN.test(VALID_CATEGORY_ID)).toBe(true);
});
it('validateChallengeForm flags empty categoryId', () => {
const errs = validateChallengeForm(makeDefaults({ categoryId: '' }));
expect(errs.categoryId).toBe('Category is required');
});
it('validateChallengeForm flags whitespace-only categoryId', () => {
const errs = validateChallengeForm(makeDefaults({ categoryId: ' ' }));
expect(errs.categoryId).toBe('Category is required');
});
it('validateChallengeForm flags non-UUID categoryId (defense in depth)', () => {
const errs = validateChallengeForm(makeDefaults({ categoryId: 'not-a-uuid' }));
expect(errs.categoryId).toBe('Category is required');
});
it('validateChallengeForm accepts a well-formed UUID categoryId', () => {
const errs = validateChallengeForm(makeDefaults());
expect(errs.categoryId).toBeUndefined();
});
it('firstErrorTab routes a categoryId error to the general tab', () => {
expect(firstErrorTab({ categoryId: 'Category is required' })).toBe('general');
});
it('buildChallengeFormGroup applies a uuid validator on categoryId', () => {
const form = buildChallengeFormGroup(new FormBuilder());
form.controls.categoryId.setValue('not-a-uuid');
form.controls.categoryId.markAsTouched();
expect(form.controls.categoryId.errors?.['uuid']).toBe(true);
expect(form.controls.categoryId.errors?.['required']).toBeUndefined();
});
it('buildChallengeFormGroup uuid validator passes for a valid UUID v4', () => {
const form = buildChallengeFormGroup(new FormBuilder());
form.controls.categoryId.setValue(VALID_CATEGORY_ID);
form.controls.categoryId.markAsTouched();
expect(form.controls.categoryId.errors?.['uuid']).toBeUndefined();
});
it('buildChallengeFormGroup categoryId control still flags required for empty value', () => {
const form = buildChallengeFormGroup(new FormBuilder());
form.controls.categoryId.setValue('');
form.controls.categoryId.markAsTouched();
expect(form.controls.categoryId.errors?.['required']).toBe(true);
});
});
+2 -2
View File
@@ -27,7 +27,7 @@ function makeDetail(overrides: Partial<AdminChallengeDetail> = {}): AdminChallen
id: 'd1',
name: 'Sample',
descriptionMd: '# hi',
categoryId: 'cat-1',
categoryId: '11111111-1111-4111-8111-111111111111',
categoryAbbreviation: 'CRY',
categoryIconPath: '/uploads/icons/CRY.png',
difficulty: 'MEDIUM',
@@ -58,7 +58,7 @@ function makeDefaults(overrides: Partial<ChallengeFormDefaults> = {}): Challenge
return {
name: 'X',
descriptionMd: 'd',
categoryId: 'cat-1',
categoryId: '11111111-1111-4111-8111-111111111111',
difficulty: 'MEDIUM',
initialPoints: 100,
minimumPoints: 50,