143 lines
5.6 KiB
TypeScript
143 lines
5.6 KiB
TypeScript
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);
|
|
});
|
|
});
|