Files
HIPCTF2/tests/backend/challenges-status-rest.spec.ts
T

95 lines
4.1 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-status-rest-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 { 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';
import { SettingsService } from '../../backend/src/modules/settings/settings.module';
import { SETTINGS_KEYS } from '../../backend/src/config/env.schema';
describe('GET /api/v1/challenges/status (REST snapshot)', () => {
let app: INestApplication;
let settings: SettingsService;
let adminToken: string;
let adminCsrf: string;
beforeAll(async () => {
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 ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
await initDb(app);
settings = app.get(SettingsService);
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='));
adminCsrf = csrfCookie ? decodeURIComponent(csrfCookie.split(';')[0].split('=')[1]) : '';
const login = await request(server).post('/api/v1/auth/login')
.set('Cookie', `csrf=${adminCsrf}`)
.set('X-CSRF-Token', adminCsrf)
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
adminToken = login.body.accessToken;
});
afterAll(async () => {
await app.close();
});
it('rejects unauthenticated requests with 401', async () => {
await request(app.getHttpServer()).get('/api/v1/challenges/status').expect(401);
});
it('returns the running window snapshot for an authenticated user', async () => {
const start = new Date(Date.now() - 60_000).toISOString();
const end = new Date(Date.now() + 3600_000).toISOString();
await settings.set(SETTINGS_KEYS.EVENT_START_UTC, start);
await settings.set(SETTINGS_KEYS.EVENT_END_UTC, end);
const res = await request(app.getHttpServer())
.get('/api/v1/challenges/status')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(res.body.state).toBe('running');
expect(typeof res.body.serverNowUtc).toBe('string');
expect(res.body.eventStartUtc).toBe(start);
expect(res.body.eventEndUtc).toBe(end);
expect(res.body.secondsToStart).toBeNull();
expect(res.body.secondsToEnd).toBeGreaterThan(3500);
});
it('returns countdown state when the event has not started yet', async () => {
const start = new Date(Date.now() + 3600_000).toISOString();
const end = new Date(Date.now() + 7200_000).toISOString();
await settings.set(SETTINGS_KEYS.EVENT_START_UTC, start);
await settings.set(SETTINGS_KEYS.EVENT_END_UTC, end);
const res = await request(app.getHttpServer())
.get('/api/v1/challenges/status')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(res.body.state).toBe('countdown');
expect(res.body.secondsToStart).toBeGreaterThan(3500);
});
});