AI Implementation feature(820): Project Scaffold and Platform Foundations (#1)
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
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';
|
||||
|
||||
describe('Admin route protection', () => {
|
||||
let app: INestApplication;
|
||||
let adminToken: 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);
|
||||
|
||||
const server = app.getHttpServer();
|
||||
await request(server).post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
|
||||
const login = await request(server).post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = login.body.accessToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /api/v1/admin/users without a token returns 401', async () => {
|
||||
await request(app.getHttpServer()).get('/api/v1/admin/users').expect(401);
|
||||
});
|
||||
|
||||
it('GET /api/v1/admin/users with a player JWT returns 403', async () => {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
|
||||
// Prime CSRF cookie first.
|
||||
await agent.get('/api/v1/auth/csrf');
|
||||
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
|
||||
const csrf = cookies.find((c: any) => c.name === 'csrf');
|
||||
|
||||
// Create a player via admin endpoint
|
||||
await agent.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.send({ username: 'player1', password: 'Sup3rSecret!Pass', role: 'player' })
|
||||
.expect(201);
|
||||
|
||||
const playerLogin = await agent.post('/api/v1/auth/login')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.send({ username: 'player1', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
const playerToken = playerLogin.body.accessToken;
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${playerToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('GET /api/v1/admin/users with admin JWT returns 200 and lists users', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.expect(200);
|
||||
expect(Array.isArray(res.body)).toBe(true);
|
||||
expect(res.body.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('DELETE /api/v1/admin/users/:id on the only admin returns 409 LAST_ADMIN', async () => {
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.expect(200);
|
||||
const adminRow = list.body.find((u: any) => u.role === 'admin');
|
||||
expect(adminRow).toBeDefined();
|
||||
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
await agent.get('/api/v1/auth/csrf');
|
||||
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
|
||||
const csrf = cookies.find((c: any) => c.name === 'csrf');
|
||||
|
||||
await agent.delete(`/api/v1/admin/users/${adminRow.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.expect(409);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
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 { DatabaseInitService } from '../../backend/src/database/database-init.service';
|
||||
|
||||
describe('Admin route validation (Zod DTOs)', () => {
|
||||
let app: INestApplication;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
|
||||
const httpAdapterHost = app.get(HttpAdapterHost);
|
||||
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
|
||||
await app.init();
|
||||
await app.get(DatabaseInitService).init();
|
||||
|
||||
const server = app.getHttpServer();
|
||||
await request(server).post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
|
||||
const login = await request(server).post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = login.body.accessToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
describe('POST /api/v1/admin/users', () => {
|
||||
it('rejects missing username with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ password: 'Sup3rSecret!Pass', role: 'player' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects username with invalid characters with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ username: 'bad name!', password: 'Sup3rSecret!Pass', role: 'player' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects weak password with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ username: 'goodname', password: 'short', role: 'player' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects invalid role with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ username: 'goodname', password: 'Sup3rSecret!Pass', role: 'god' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('accepts a well-formed body', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent
|
||||
.post('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({ username: 'gooduser', password: 'Sup3rSecret!Pass', role: 'player' });
|
||||
expect(res.status).toBe(201);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/admin/users/:id', () => {
|
||||
it('rejects a non-UUID id with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.patch('/api/v1/admin/users/not-a-uuid')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ role: 'player' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects an invalid role with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.patch('/api/v1/admin/users/00000000-0000-0000-0000-000000000000')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ role: 'superuser' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/admin/users/:id', () => {
|
||||
it('rejects a non-UUID id with 400', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent.delete('/api/v1/admin/users/not-a-uuid')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/admin/users?limit=...', () => {
|
||||
it('rejects limit > 200 with 400', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users?limit=999')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects limit=0 with 400', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users?limit=0')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects non-numeric limit with 400', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users?limit=abc')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('accepts a valid limit and returns 200', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users?limit=10')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(Array.isArray(res.body)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ApiError } from '../../backend/src/common/errors/api-error';
|
||||
import { ERROR_CODES } from '../../backend/src/common/errors/error-codes';
|
||||
|
||||
describe('ApiError', () => {
|
||||
it('formats validation errors with details', () => {
|
||||
const e = ApiError.validation('Bad input', { field: 'x' });
|
||||
expect(e.getStatus()).toBe(400);
|
||||
const body = e.getResponse() as any;
|
||||
expect(body.code).toBe(ERROR_CODES.VALIDATION_FAILED);
|
||||
expect(body.message).toBe('Bad input');
|
||||
expect(body.details).toEqual({ field: 'x' });
|
||||
});
|
||||
|
||||
it('formats last-admin conflict', () => {
|
||||
const e = ApiError.conflict(ERROR_CODES.LAST_ADMIN, 'Cannot delete the last admin');
|
||||
expect(e.getStatus()).toBe(409);
|
||||
const body = e.getResponse() as any;
|
||||
expect(body.code).toBe(ERROR_CODES.LAST_ADMIN);
|
||||
});
|
||||
|
||||
it('formats internal error as 500', () => {
|
||||
const e = ApiError.internal();
|
||||
expect(e.getStatus()).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
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';
|
||||
import { DatabaseInitService } from '../../backend/src/database/database-init.service';
|
||||
|
||||
describe('Auth refresh rotation', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
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);
|
||||
|
||||
const server = app.getHttpServer();
|
||||
await request(server).post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /api/v1/auth/csrf always sets the cookie and returns a non-empty token', async () => {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
const res = await agent.get('/api/v1/auth/csrf').expect(200);
|
||||
expect(res.body.csrfToken).toBeDefined();
|
||||
expect(res.body.csrfToken.length).toBeGreaterThan(0);
|
||||
const cookies = res.headers['set-cookie'] as unknown as string[];
|
||||
expect(cookies?.some((c) => c.startsWith('csrf='))).toBe(true);
|
||||
});
|
||||
|
||||
it('login returns an access token and sets the rt refresh cookie', async () => {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
|
||||
const res = await agent.post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
expect(res.body.accessToken).toBeDefined();
|
||||
const cookies = res.headers['set-cookie'] as unknown as string[];
|
||||
const rt = cookies.find((c) => c.startsWith('rt='));
|
||||
expect(rt).toBeDefined();
|
||||
expect(rt).toMatch(/HttpOnly/);
|
||||
});
|
||||
|
||||
it('refresh rotates the refresh cookie and returns a new access token', async () => {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
|
||||
await agent.post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
|
||||
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
|
||||
const rt = cookies.find((c: any) => c.name === 'rt');
|
||||
const csrf = cookies.find((c: any) => c.name === 'csrf');
|
||||
expect(rt).toBeDefined();
|
||||
expect(csrf).toBeDefined();
|
||||
|
||||
const refresh = await agent.post('/api/v1/auth/refresh')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.set('Cookie', `rt=${rt.value}`)
|
||||
.send({})
|
||||
.expect(200);
|
||||
expect(refresh.body.accessToken).toBeDefined();
|
||||
expect(refresh.body.user.username).toBe('admin');
|
||||
});
|
||||
|
||||
it('logout invalidates the refresh token', async () => {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
|
||||
await agent.post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
|
||||
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
|
||||
const rt = cookies.find((c: any) => c.name === 'rt');
|
||||
const csrf = cookies.find((c: any) => c.name === 'csrf');
|
||||
|
||||
await agent.post('/api/v1/auth/logout')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.set('Cookie', `rt=${rt.value}`)
|
||||
.send({})
|
||||
.expect(204);
|
||||
|
||||
// Reusing the same refresh cookie must fail
|
||||
await agent.post('/api/v1/auth/refresh')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.set('Cookie', `rt=${rt.value}`)
|
||||
.send({})
|
||||
.expect(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { AppModule } from '../../backend/src/app.module';
|
||||
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
|
||||
import { csrfClient, primeCsrf } from './csrf-client';
|
||||
import { initDb } from './db-helper';
|
||||
|
||||
describe('Bootstrap integration', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
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);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('a: bootstrap before any admin', async () => {
|
||||
const c = csrfClient(app);
|
||||
const res = await c.get('/api/v1/bootstrap').expect(200);
|
||||
expect(res.body.initialized).toBe(false);
|
||||
expect(res.body.theme).toBeDefined();
|
||||
expect(res.body.theme.tokens.primary).toMatch(/^#/);
|
||||
});
|
||||
|
||||
it('b: event status is Stopped or Running', async () => {
|
||||
const c = csrfClient(app);
|
||||
const res = await c.get('/api/v1/event/status').expect(200);
|
||||
expect(['Stopped', 'Running']).toContain(res.body.status);
|
||||
expect(typeof res.body.countdownMs).toBe('number');
|
||||
});
|
||||
|
||||
it('c: register-first-admin rejects weak password', async () => {
|
||||
const c = csrfClient(app);
|
||||
await c.post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'weak', password: '123' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('d: register-first-admin with valid creds creates admin', async () => {
|
||||
const c = csrfClient(app);
|
||||
const res = await c.post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
expect(res.body.accessToken).toBeDefined();
|
||||
expect(res.body.user.role).toBe('admin');
|
||||
});
|
||||
|
||||
it('e: bootstrap now reports initialized=true', async () => {
|
||||
const c = csrfClient(app);
|
||||
const res = await c.get('/api/v1/bootstrap').expect(200);
|
||||
expect(res.body.initialized).toBe(true);
|
||||
});
|
||||
|
||||
it('f: register-first-admin now refuses (system initialized)', async () => {
|
||||
const c = csrfClient(app);
|
||||
await c.post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'second', password: 'Sup3rSecret!Pass' })
|
||||
.expect(409);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import request from 'supertest';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { CookieAccessInfo } from 'cookiejar';
|
||||
|
||||
const csrfSkipPaths = new Set<string>(['/api/v1/auth/login', '/api/v1/auth/register-first-admin']);
|
||||
|
||||
function attachCsrfHeader(test: request.Test, method: string, path: string, agent: any): request.Test {
|
||||
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method.toUpperCase())) return test;
|
||||
if (csrfSkipPaths.has(path)) return test;
|
||||
const jar = agent.jar;
|
||||
if (!jar || typeof jar.getCookies !== 'function') return test;
|
||||
const cookies: any[] = jar.getCookies(CookieAccessInfo.All);
|
||||
if (process.env.CSRF_DEBUG) console.log('[csrf-client] all cookies in jar:', cookies.map((c: any) => ({ name: c.name, path: c.path })), 'for path', path);
|
||||
const csrfCookie = cookies.find((c: any) => c.name === 'csrf');
|
||||
if (!csrfCookie) return test;
|
||||
const csrf = decodeURIComponent(csrfCookie.value ?? '');
|
||||
if (csrf) test.set('X-CSRF-Token', csrf);
|
||||
return test;
|
||||
}
|
||||
|
||||
export function csrfClient(app: INestApplication): {
|
||||
get: (path: string) => request.Test;
|
||||
post: (path: string) => request.Test;
|
||||
put: (path: string) => request.Test;
|
||||
patch: (path: string) => request.Test;
|
||||
delete: (path: string) => request.Test;
|
||||
} {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
return {
|
||||
get: (path: string) => agent.get(path),
|
||||
post: (path: string) => attachCsrfHeader(agent.post(path), 'POST', path, agent),
|
||||
put: (path: string) => attachCsrfHeader(agent.put(path), 'PUT', path, agent),
|
||||
patch: (path: string) => attachCsrfHeader(agent.patch(path), 'PATCH', path, agent),
|
||||
delete: (path: string) => attachCsrfHeader(agent.delete(path), 'DELETE', path, agent),
|
||||
};
|
||||
}
|
||||
|
||||
export async function primeCsrf(app: INestApplication): Promise<string> {
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
const res = await agent.get('/api/v1/auth/csrf');
|
||||
const cookieHeader = (res.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
|
||||
const token = cookieHeader ? cookieHeader.split(';')[0].split('=')[1] : '';
|
||||
return decodeURIComponent(token);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { validateEnv } from '../../backend/src/config/env.schema';
|
||||
import { DatabaseModule } from '../../backend/src/database/database.module';
|
||||
import { DatabaseInitService } from '../../backend/src/database/database-init.service';
|
||||
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
|
||||
import { SettingEntity } from '../../backend/src/database/entities/setting.entity';
|
||||
|
||||
describe('DatabaseInitService', () => {
|
||||
let app: INestApplication;
|
||||
let init: DatabaseInitService;
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
|
||||
DatabaseModule,
|
||||
],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
init = app.get(DatabaseInitService);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
it('creates the schema and seed data on first init()', async () => {
|
||||
await init.init();
|
||||
const ds = (init as any).dataSource;
|
||||
expect(ds.isInitialized).toBe(true);
|
||||
const tables: any[] = await ds.query("SELECT name FROM sqlite_master WHERE type='table'");
|
||||
const names = tables.map((t) => t.name);
|
||||
expect(names).toEqual(expect.arrayContaining([
|
||||
'user', 'setting', 'category', 'challenge', 'challenge_file',
|
||||
'solve', 'refresh_token', 'blog_post',
|
||||
]));
|
||||
|
||||
const categories = await ds.getRepository(CategoryEntity).find();
|
||||
const systemCats = categories.filter((c: any) => c.systemKey);
|
||||
expect(systemCats.length).toBeGreaterThanOrEqual(6);
|
||||
|
||||
const settings = await ds.getRepository(SettingEntity).find();
|
||||
const keys = settings.map((s: any) => s.key);
|
||||
expect(keys).toEqual(expect.arrayContaining([
|
||||
'pageTitle', 'logo', 'welcomeMarkdown', 'themeKey',
|
||||
'defaultChallengeIp', 'registrationsEnabled',
|
||||
'eventStartUtc', 'eventEndUtc',
|
||||
]));
|
||||
});
|
||||
|
||||
it('is idempotent — calling init() twice does not duplicate migrations or seeds', async () => {
|
||||
await init.init();
|
||||
await init.init();
|
||||
const ds = (init as any).dataSource;
|
||||
const categories = await ds.getRepository(CategoryEntity).find();
|
||||
const systemCats = categories.filter((c: any) => c.systemKey);
|
||||
expect(systemCats.length).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { DatabaseInitService } from '../../backend/src/database/database-init.service';
|
||||
|
||||
/**
|
||||
* Await database initialization (migrations + seed verification) on the
|
||||
* given Nest app. Without this, integration tests that hit controllers
|
||||
* will hit a fresh `:memory:` SQLite database with no tables.
|
||||
*/
|
||||
export async function initDb(app: INestApplication): Promise<void> {
|
||||
await app.get<DatabaseInitService>(DatabaseInitService).init();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { envSchema, SYSTEM_CATEGORY_KEYS, SETTINGS_KEYS } from '../../backend/src/config/env.schema';
|
||||
|
||||
describe('envSchema', () => {
|
||||
it('accepts minimal valid env', () => {
|
||||
const r = envSchema.safeParse({});
|
||||
expect(r.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid PORT', () => {
|
||||
const r = envSchema.safeParse({ PORT: 'not-a-number' });
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects short JWT secrets', () => {
|
||||
const r = envSchema.safeParse({ JWT_ACCESS_SECRET: 'short' });
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
|
||||
it('exposes the canonical system category and settings keys', () => {
|
||||
expect(SYSTEM_CATEGORY_KEYS).toEqual(['crypto', 'forensics', 'pwn', 'web', 'misc', 'osint']);
|
||||
expect(SETTINGS_KEYS.THEME_KEY).toBe('themeKey');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { EventStatusService } from '../../backend/src/common/services/event-status.service';
|
||||
|
||||
describe('EventStatusService', () => {
|
||||
const settings = {
|
||||
get: jest.fn(),
|
||||
} as any;
|
||||
|
||||
beforeEach(() => {
|
||||
settings.get.mockReset();
|
||||
});
|
||||
|
||||
it('returns Stopped before start with positive countdown', async () => {
|
||||
const start = new Date(Date.now() + 60_000).toISOString();
|
||||
const end = new Date(Date.now() + 120_000).toISOString();
|
||||
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
|
||||
const svc = new EventStatusService(settings);
|
||||
const s = await svc.getStatus();
|
||||
expect(s.status).toBe('Stopped');
|
||||
expect(s.countdownMs).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('returns Running between start and end', async () => {
|
||||
const start = new Date(Date.now() - 30_000).toISOString();
|
||||
const end = new Date(Date.now() + 60_000).toISOString();
|
||||
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
|
||||
const svc = new EventStatusService(settings);
|
||||
const s = await svc.getStatus();
|
||||
expect(s.status).toBe('Running');
|
||||
expect(s.countdownMs).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('returns Stopped after end with zero countdown', async () => {
|
||||
const start = new Date(Date.now() - 120_000).toISOString();
|
||||
const end = new Date(Date.now() - 60_000).toISOString();
|
||||
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
|
||||
const svc = new EventStatusService(settings);
|
||||
const s = await svc.getStatus();
|
||||
expect(s.status).toBe('Stopped');
|
||||
expect(s.countdownMs).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { UsersService } from '../../backend/src/modules/users/users.service';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { UserEntity } from '../../backend/src/database/entities/user.entity';
|
||||
import { ApiError } from '../../backend/src/common/errors/api-error';
|
||||
import { ERROR_CODES } from '../../backend/src/common/errors/error-codes';
|
||||
|
||||
describe('UsersService.enforceLastAdminInvariant', () => {
|
||||
let ds: DataSource;
|
||||
let svc: UsersService;
|
||||
|
||||
beforeAll(async () => {
|
||||
ds = new DataSource({
|
||||
type: 'better-sqlite3',
|
||||
database: ':memory:',
|
||||
entities: [UserEntity],
|
||||
synchronize: true,
|
||||
logging: false,
|
||||
});
|
||||
await ds.initialize();
|
||||
svc = new UsersService(ds.getRepository(UserEntity));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await ds.destroy();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await ds.getRepository(UserEntity).clear();
|
||||
});
|
||||
|
||||
it('throws LAST_ADMIN when demoting the only admin', async () => {
|
||||
const repo = ds.getRepository(UserEntity);
|
||||
const admin = repo.create({
|
||||
id: 'a1', username: 'admin', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString(),
|
||||
});
|
||||
await repo.save(admin);
|
||||
|
||||
await expect(
|
||||
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1', 'player')),
|
||||
).rejects.toMatchObject({
|
||||
response: { code: ERROR_CODES.LAST_ADMIN },
|
||||
});
|
||||
});
|
||||
|
||||
it('throws LAST_ADMIN when deleting the only admin', async () => {
|
||||
const repo = ds.getRepository(UserEntity);
|
||||
const admin = repo.create({
|
||||
id: 'a1', username: 'admin', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString(),
|
||||
});
|
||||
await repo.save(admin);
|
||||
|
||||
await expect(
|
||||
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1')),
|
||||
).rejects.toMatchObject({
|
||||
response: { code: ERROR_CODES.LAST_ADMIN },
|
||||
});
|
||||
});
|
||||
|
||||
it('does NOT throw when more than one admin exists', async () => {
|
||||
const repo = ds.getRepository(UserEntity);
|
||||
await repo.save([
|
||||
repo.create({ id: 'a1', username: 'a1', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
|
||||
repo.create({ id: 'a2', username: 'a2', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
|
||||
]);
|
||||
|
||||
await expect(
|
||||
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1', 'player')),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does NOT throw when demoting a non-admin', async () => {
|
||||
const repo = ds.getRepository(UserEntity);
|
||||
await repo.save([
|
||||
repo.create({ id: 'a1', username: 'a1', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
|
||||
repo.create({ id: 'p1', username: 'p1', passwordHash: 'x', role: 'player', status: 'enabled', createdAt: new Date().toISOString() }),
|
||||
]);
|
||||
await expect(
|
||||
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'p1', 'admin')),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { LoginBackoffService } from '../../backend/src/common/services/login-backoff.service';
|
||||
|
||||
describe('LoginBackoffService', () => {
|
||||
it('starts unblocked', () => {
|
||||
const s = new LoginBackoffService();
|
||||
expect(s.isBlocked('1.1.1.1', 'alice', 1000)).toBe(0);
|
||||
});
|
||||
|
||||
it('blocks after repeated failures and resets on success', () => {
|
||||
const s = new LoginBackoffService();
|
||||
const now = 1000;
|
||||
for (let i = 0; i < 5; i++) s.recordFailure('1.1.1.1', 'alice', now);
|
||||
expect(s.isBlocked('1.1.1.1', 'alice', now + 100)).toBeGreaterThan(0);
|
||||
s.reset('1.1.1.1', 'alice');
|
||||
expect(s.isBlocked('1.1.1.1', 'alice', now + 100)).toBe(0);
|
||||
});
|
||||
|
||||
it('is per (ip, username)', () => {
|
||||
const s = new LoginBackoffService();
|
||||
for (let i = 0; i < 6; i++) s.recordFailure('1.1.1.1', 'alice', 1000 + i);
|
||||
expect(s.isBlocked('1.1.1.1', 'alice', 1100)).toBeGreaterThan(0);
|
||||
expect(s.isBlocked('1.1.1.1', 'bob', 1100)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as path from 'path';
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
import { InitSchema1700000000000 } from '../../backend/src/database/migrations/1700000000000-InitSchema';
|
||||
import { SeedSystemData1700000000100 } from '../../backend/src/database/migrations/1700000000100-SeedSystemData';
|
||||
import { DataSource } from 'typeorm';
|
||||
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';
|
||||
|
||||
describe('Migrations', () => {
|
||||
let dataSource: DataSource;
|
||||
|
||||
beforeAll(async () => {
|
||||
dataSource = new DataSource({
|
||||
type: 'better-sqlite3',
|
||||
database: ':memory:',
|
||||
entities: [UserEntity, SettingEntity, CategoryEntity, ChallengeEntity, ChallengeFileEntity, SolveEntity, RefreshTokenEntity, BlogPostEntity],
|
||||
migrations: [InitSchema1700000000000, SeedSystemData1700000000100],
|
||||
migrationsRun: true,
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
});
|
||||
await dataSource.initialize();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dataSource.destroy();
|
||||
});
|
||||
|
||||
it('creates all required tables', async () => {
|
||||
const tables = await dataSource.query("SELECT name FROM sqlite_master WHERE type='table'");
|
||||
const names = tables.map((t: any) => t.name);
|
||||
expect(names).toEqual(expect.arrayContaining([
|
||||
'user', 'setting', 'category', 'challenge', 'challenge_file',
|
||||
'solve', 'refresh_token', 'blog_post',
|
||||
]));
|
||||
});
|
||||
|
||||
it('seeds 6 system categories with unique system_keys', async () => {
|
||||
const cats = await dataSource.getRepository(CategoryEntity).find();
|
||||
const systemCats = cats.filter((c) => c.systemKey);
|
||||
expect(systemCats.length).toBeGreaterThanOrEqual(6);
|
||||
const keys = systemCats.map((c) => c.systemKey);
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
});
|
||||
|
||||
it('seeds default settings', async () => {
|
||||
const settings = await dataSource.getRepository(SettingEntity).find();
|
||||
const keys = settings.map((s) => s.key);
|
||||
expect(keys).toEqual(expect.arrayContaining(['pageTitle', 'themeKey', 'eventStartUtc', 'eventEndUtc']));
|
||||
});
|
||||
|
||||
it('enforces UNIQUE(challengeId, userId) on solve', async () => {
|
||||
const indexes = await dataSource.query("SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name='solve'");
|
||||
const uq = indexes.find((i: any) => /UNIQUE.*challenge_id.*user_id/i.test(i.sql || ''));
|
||||
expect(uq).toBeDefined();
|
||||
});
|
||||
|
||||
it('enforces ON DELETE RESTRICT FK on solve', async () => {
|
||||
const fks = await dataSource.query("PRAGMA foreign_key_list('solve')");
|
||||
const restrict = fks.filter((f: any) => f.on_delete === 'RESTRICT');
|
||||
expect(restrict.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { toOpenApi31 } from '../../backend/src/common/utils/openapi31';
|
||||
|
||||
describe('toOpenApi31', () => {
|
||||
it('sets openapi to 3.1.0', () => {
|
||||
const doc: any = toOpenApi31({ openapi: '3.0.0', info: { title: 'X', version: '1' }, paths: {} });
|
||||
expect(doc.openapi).toBe('3.1.0');
|
||||
});
|
||||
|
||||
it('preserves info title and version', () => {
|
||||
const doc: any = toOpenApi31({ openapi: '3.0.0', info: { title: 'HIPCTF', version: '1.0.0' }, paths: {} });
|
||||
expect(doc.info.title).toBe('HIPCTF');
|
||||
expect(doc.info.version).toBe('1.0.0');
|
||||
});
|
||||
|
||||
it('rewrites nullable=true to type union with null', () => {
|
||||
const doc: any = toOpenApi31({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 't', version: 'v' },
|
||||
paths: {},
|
||||
components: {
|
||||
schemas: {
|
||||
Foo: { type: 'object', properties: { name: { type: 'string', nullable: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(doc.components.schemas.Foo.properties.name).toEqual({ type: ['string', 'null'] });
|
||||
expect(doc.components.schemas.Foo.properties.name.nullable).toBeUndefined();
|
||||
});
|
||||
|
||||
it('handles nullable without an explicit type', () => {
|
||||
const doc: any = toOpenApi31({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 't', version: 'v' },
|
||||
paths: {},
|
||||
components: { schemas: { Bar: { nullable: true } } },
|
||||
});
|
||||
expect(doc.components.schemas.Bar).toEqual({ type: ['null'] });
|
||||
});
|
||||
|
||||
it('preserves $ref nodes', () => {
|
||||
const doc: any = toOpenApi31({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 't', version: 'v' },
|
||||
paths: {},
|
||||
components: {
|
||||
schemas: {
|
||||
Foo: { $ref: '#/components/schemas/Bar' },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(doc.components.schemas.Foo).toEqual({ $ref: '#/components/schemas/Bar' });
|
||||
});
|
||||
|
||||
it('recurses into array items, oneOf, anyOf, allOf', () => {
|
||||
const doc: any = toOpenApi31({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 't', version: 'v' },
|
||||
paths: {},
|
||||
components: {
|
||||
schemas: {
|
||||
Foo: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
arr: { type: 'array', items: { type: 'string', nullable: true } },
|
||||
union: { oneOf: [{ type: 'string', nullable: true }] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(doc.components.schemas.Foo.properties.arr.items).toEqual({ type: ['string', 'null'] });
|
||||
expect(doc.components.schemas.Foo.properties.union.oneOf[0]).toEqual({ type: ['string', 'null'] });
|
||||
});
|
||||
|
||||
it('rewrites nullable in path parameters and request bodies', () => {
|
||||
const doc: any = toOpenApi31({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 't', version: 'v' },
|
||||
paths: {
|
||||
'/x': {
|
||||
get: {
|
||||
parameters: [{ name: 'q', in: 'query', schema: { type: 'string', nullable: true } }],
|
||||
requestBody: {
|
||||
content: {
|
||||
'application/json': { schema: { type: 'object', properties: { p: { type: 'integer', nullable: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const params = doc.paths['/x'].get.parameters;
|
||||
expect(params[0].schema).toEqual({ type: ['string', 'null'] });
|
||||
const bodySchema = doc.paths['/x'].get.requestBody.content['application/json'].schema;
|
||||
expect(bodySchema.properties.p).toEqual({ type: ['integer', 'null'] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
import { RegistrationRateLimitService } from '../../backend/src/common/services/registration-rate-limit.service';
|
||||
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 { 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';
|
||||
|
||||
describe('RegistrationRateLimitService', () => {
|
||||
it('allows up to 10 per minute per IP', () => {
|
||||
const s = new RegistrationRateLimitService();
|
||||
const now = 1_000_000;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
expect(s.isAllowed('1.1.1.1', now + i)).toBe(true);
|
||||
s.record('1.1.1.1', now + i);
|
||||
}
|
||||
expect(s.isAllowed('1.1.1.1', now + 10)).toBe(false);
|
||||
});
|
||||
|
||||
it('isolates per IP', () => {
|
||||
const s = new RegistrationRateLimitService();
|
||||
const now = 1_000_000;
|
||||
for (let i = 0; i < 10; i++) s.record('1.1.1.1', now + i);
|
||||
expect(s.isAllowed('2.2.2.2', now + 10)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('register-first-admin registration rate limit (integration)', () => {
|
||||
let app: INestApplication;
|
||||
let limiter: RegistrationRateLimitService;
|
||||
|
||||
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));
|
||||
const httpAdapterHost = app.get(HttpAdapterHost);
|
||||
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
|
||||
await app.init();
|
||||
await initDb(app);
|
||||
limiter = app.get(RegistrationRateLimitService);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('returns 429 once the per-IP cap is reached', async () => {
|
||||
// Prime the limiter for the IP that supertest will use. The default
|
||||
// Express socket address is IPv6-mapped IPv4 ('::ffff:127.0.0.1') on
|
||||
// most platforms; priming both forms keeps the test stable.
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
limiter.record('127.0.0.1', now + i);
|
||||
limiter.record('::ffff:127.0.0.1', now + i);
|
||||
}
|
||||
|
||||
const server = app.getHttpServer();
|
||||
const agent = request.agent(server);
|
||||
await agent.get('/api/v1/auth/csrf');
|
||||
const cookies: any = agent.jar.getCookies(require('cookiejar').CookieAccessInfo.All);
|
||||
const csrf = cookies.find((c: any) => c.name === 'csrf');
|
||||
|
||||
await agent.post('/api/v1/auth/register-first-admin')
|
||||
.set('X-CSRF-Token', csrf.value)
|
||||
.send({ username: 'noone', password: 'Sup3rSecret!Pass' })
|
||||
.expect(429);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../../backend/src/app.module';
|
||||
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
|
||||
|
||||
describe('SSE flattened payloads', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
const httpAdapterHost = app.get(HttpAdapterHost);
|
||||
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('event/stream emits a flattened { status, countdownMs, serverNowUtc, startUtc, endUtc } payload', (done) => {
|
||||
const server = app.getHttpServer();
|
||||
const req = request(server).get('/api/v1/event/stream');
|
||||
let received = false;
|
||||
req
|
||||
.buffer(true)
|
||||
.parse((res, cb) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
if (received) return;
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
const match = /data: ({.*?})\n/.exec(text);
|
||||
if (match) {
|
||||
try {
|
||||
const payload = JSON.parse(match[1]);
|
||||
expect(payload).toHaveProperty('status');
|
||||
expect(payload).toHaveProperty('countdownMs');
|
||||
expect(payload).toHaveProperty('serverNowUtc');
|
||||
expect(payload).toHaveProperty('startUtc');
|
||||
expect(payload).toHaveProperty('endUtc');
|
||||
expect(['Stopped', 'Running']).toContain(payload.status);
|
||||
received = true;
|
||||
(res as any).destroy();
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
res.on('end', () => cb(null, Buffer.concat(chunks)));
|
||||
res.on('error', (err) => cb(err, null));
|
||||
})
|
||||
.end(() => {});
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import { ThemeLoaderService } from '../../backend/src/common/utils/theme-loader.service';
|
||||
|
||||
describe('ThemeLoaderService', () => {
|
||||
const config = { get: jest.fn() } as any;
|
||||
// ThemeLoaderService now takes SettingsService for the configured-theme
|
||||
// validation step. We pass a stub that always returns 'classic' so the
|
||||
// existing tests focus on disk loading + lookup behavior.
|
||||
const settings = { get: jest.fn().mockResolvedValue('classic') } as any;
|
||||
|
||||
it('falls back to default and warns on unknown theme id', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify({ id: 'classic', name: 'Classic', tokens: { primary: '#000', secondary: '#111', accent: '#222', surface: '#fff', text: '#000', success: '#0f0', warning: '#ff0', danger: '#f00', fontFamily: 'sans', radii: { sm: '1px', md: '2px', lg: '3px' }, spacingScale: [4, 8] } }));
|
||||
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
|
||||
const svc = new ThemeLoaderService(config, settings);
|
||||
return svc.onModuleInit().then(() => {
|
||||
const t = svc.getTheme('does-not-exist');
|
||||
expect(t.id).toBe('classic');
|
||||
expect(t.tokens.primary).toBe('#000');
|
||||
});
|
||||
});
|
||||
|
||||
it('loads a valid theme by id', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
const theme = { id: 'classic', name: 'Classic', tokens: { primary: '#000', secondary: '#111', accent: '#222', surface: '#fff', text: '#000', success: '#0f0', warning: '#ff0', danger: '#f00', fontFamily: 'sans', radii: { sm: '1px', md: '2px', lg: '3px' }, spacingScale: [4, 8] } };
|
||||
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify(theme));
|
||||
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
|
||||
const svc = new ThemeLoaderService(config, settings);
|
||||
return svc.onModuleInit().then(() => {
|
||||
const t = svc.getTheme('classic');
|
||||
expect(t.id).toBe('classic');
|
||||
expect(t.tokens.spacingScale).toEqual([4, 8]);
|
||||
});
|
||||
});
|
||||
|
||||
it('skips invalid theme files', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify({ id: 'classic', name: 'Classic', tokens: { primary: '#000' } })); // missing required
|
||||
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
|
||||
const svc = new ThemeLoaderService(config, settings);
|
||||
return svc.onModuleInit().then(() => {
|
||||
// Falls back to builtins; classic should be findable via builtins
|
||||
const t = svc.getTheme('classic');
|
||||
expect(t).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { validateEnv, SETTINGS_KEYS } from '../../backend/src/config/env.schema';
|
||||
import { ThemeLoaderService } from '../../backend/src/common/utils/theme-loader.service';
|
||||
import { SettingsModule, SettingsService } from '../../backend/src/modules/settings/settings.module';
|
||||
import { CommonModule } from '../../backend/src/common/common.module';
|
||||
import { DatabaseModule } from '../../backend/src/database/database.module';
|
||||
import { DatabaseInitService } from '../../backend/src/database/database-init.service';
|
||||
import { THEME_IDS } from '../../backend/src/common/types/theme-ids';
|
||||
|
||||
describe('ThemeLoaderService - require 10 + validate configured key', () => {
|
||||
let app: INestApplication;
|
||||
let svc: ThemeLoaderService;
|
||||
|
||||
async function buildApp(themeDir: string, themeKey: string): Promise<void> {
|
||||
process.env.THEMES_DIR = themeDir;
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
|
||||
DatabaseModule,
|
||||
SettingsModule,
|
||||
CommonModule,
|
||||
],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
await app.get(DatabaseInitService).init();
|
||||
const settings = app.get(SettingsService);
|
||||
await settings.set(SETTINGS_KEYS.THEME_KEY, themeKey);
|
||||
svc = app.get(ThemeLoaderService);
|
||||
await svc.onModuleInit();
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
it('exposes all 10 canonical theme ids even when THEMES_DIR is empty', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-empty-'));
|
||||
await buildApp(tmp, 'classic');
|
||||
const ids = svc.listThemes().map((t) => t.id).sort();
|
||||
expect(ids).toEqual([
|
||||
'classic', 'crimson', 'cyber', 'forest', 'midnight',
|
||||
'monochrome', 'neon', 'ocean', 'paper', 'sunset',
|
||||
]);
|
||||
expect(svc.listThemes().length).toBe(THEME_IDS.length);
|
||||
});
|
||||
|
||||
it('backfills missing disk themes with built-ins (per-id warn)', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-partial-'));
|
||||
// Only write 3 of the 10 themes to disk.
|
||||
for (const id of ['classic', 'midnight', 'cyber']) {
|
||||
fs.writeFileSync(path.join(tmp, `${id}.json`), JSON.stringify({
|
||||
id,
|
||||
name: id,
|
||||
tokens: {
|
||||
primary: '#000', secondary: '#111', accent: '#222', surface: '#fff', text: '#000',
|
||||
success: '#0f0', warning: '#ff0', danger: '#f00',
|
||||
fontFamily: 'sans', radii: { sm: '1px', md: '2px', lg: '3px' },
|
||||
spacingScale: [4, 8],
|
||||
},
|
||||
}));
|
||||
}
|
||||
await buildApp(tmp, 'classic');
|
||||
expect(svc.listThemes().length).toBe(THEME_IDS.length);
|
||||
});
|
||||
|
||||
it('uses the configured themeKey as default when valid', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
await buildApp(tmp, 'ocean');
|
||||
expect(svc.getDefaultId()).toBe('ocean');
|
||||
const theme = svc.getTheme('ocean');
|
||||
expect(theme.id).toBe('ocean');
|
||||
});
|
||||
|
||||
it('falls back to classic and warns when configured themeKey is invalid', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
await buildApp(tmp, 'this-theme-does-not-exist');
|
||||
expect(svc.getDefaultId()).toBe('classic');
|
||||
});
|
||||
|
||||
it('falls back to classic and warns when configured themeKey is empty', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
await buildApp(tmp, '');
|
||||
expect(svc.getDefaultId()).toBe('classic');
|
||||
});
|
||||
|
||||
it('getTheme() returns a real theme for any canonical id', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
|
||||
await buildApp(tmp, 'classic');
|
||||
for (const id of THEME_IDS) {
|
||||
expect(svc.getTheme(id).id).toBe(id);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_DIR = '/tmp/hipctf-uploads-test';
|
||||
process.env.UPLOAD_SIZE_LIMIT = '1mb';
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
import { safeFilename, parseUploadSizeLimit } from '../../backend/src/common/utils/upload';
|
||||
|
||||
describe('safeFilename', () => {
|
||||
it('strips directory traversal', () => {
|
||||
expect(safeFilename('../../etc/passwd')).not.toMatch(/\.\./);
|
||||
expect(safeFilename('/etc/passwd')).not.toMatch(/^\//);
|
||||
});
|
||||
|
||||
it('lowercases and restricts charset to [a-z0-9._-]', () => {
|
||||
const out = safeFilename('My File (1).TXT');
|
||||
expect(out).toMatch(/^[a-z0-9._-]+$/);
|
||||
expect(out).toMatch(/\.txt$/);
|
||||
});
|
||||
|
||||
it('always returns a non-empty unique name with a random suffix', () => {
|
||||
const a = safeFilename('icon.png');
|
||||
const b = safeFilename('icon.png');
|
||||
expect(a).not.toBe(b);
|
||||
expect(a).toMatch(/^icon-[0-9a-f]{8}\.png$/);
|
||||
});
|
||||
|
||||
it('falls back to "file" when nothing usable is left', () => {
|
||||
expect(safeFilename('///')).toMatch(/^file-[0-9a-f]{8}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseUploadSizeLimit', () => {
|
||||
it('parses kb/mb/gb', () => {
|
||||
expect(parseUploadSizeLimit('1kb')).toBe(1024);
|
||||
expect(parseUploadSizeLimit('5mb')).toBe(5 * 1024 * 1024);
|
||||
expect(parseUploadSizeLimit('2gb')).toBe(2 * 1024 * 1024 * 1024);
|
||||
expect(parseUploadSizeLimit('512b')).toBe(512);
|
||||
});
|
||||
|
||||
it('defaults to 50mb on invalid input', () => {
|
||||
expect(parseUploadSizeLimit(undefined)).toBe(50 * 1024 * 1024);
|
||||
expect(parseUploadSizeLimit('garbage')).toBe(50 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
// Integration: hit the real endpoint via supertest.
|
||||
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 { initDb } from './db-helper';
|
||||
|
||||
describe('Uploads endpoint integration', () => {
|
||||
let app: INestApplication;
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (fs.existsSync(process.env.UPLOAD_DIR!)) {
|
||||
fs.rmSync(process.env.UPLOAD_DIR!, { recursive: true, force: true });
|
||||
}
|
||||
fs.mkdirSync(process.env.UPLOAD_DIR!, { recursive: true });
|
||||
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
// Mirror production: serve /uploads static so we can verify public fetch.
|
||||
app.use('/uploads', express.static(process.env.UPLOAD_DIR!));
|
||||
const csrfMw = new CsrfMiddleware(app.get(ConfigService));
|
||||
app.use((req: any, res: any, next: any) => csrfMw.use(req, res, next));
|
||||
const httpAdapterHost = app.get(HttpAdapterHost);
|
||||
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
|
||||
await app.init();
|
||||
await initDb(app);
|
||||
|
||||
const server = app.getHttpServer();
|
||||
await request(server).post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
const login = await request(server).post('/api/v1/auth/login')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = login.body.accessToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
if (fs.existsSync(process.env.UPLOAD_DIR!)) {
|
||||
fs.rmSync(process.env.UPLOAD_DIR!, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
it('rejects upload without auth (or CSRF)', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/v1/uploads/category-icon')
|
||||
.attach('file', Buffer.from('hello'), 'icon.png');
|
||||
// Without a session AND without a CSRF cookie, the CSRF middleware
|
||||
// short-circuits first with 403. Either 401 (auth) or 403 (csrf) is
|
||||
// a valid rejection; the test asserts the upload is rejected.
|
||||
expect([401, 403]).toContain(res.status);
|
||||
});
|
||||
|
||||
it('uploads a small file successfully', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent
|
||||
.post('/api/v1/uploads/category-icon')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.attach('file', Buffer.from('hello world'), 'icon.png');
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.id).toMatch(/^icon-[0-9a-f]{8}\.png$/);
|
||||
expect(res.body.publicUrl).toBe(`/uploads/icons/${res.body.id}`);
|
||||
// File actually written under UPLOAD_DIR/icons
|
||||
const written = path.join(process.env.UPLOAD_DIR!, 'icons', res.body.id);
|
||||
expect(fs.existsSync(written)).toBe(true);
|
||||
// Public-served via /uploads static handler.
|
||||
const fetched = await request(app.getHttpServer()).get(res.body.publicUrl).expect(200);
|
||||
expect(fetched.body?.toString()).toBe('hello world');
|
||||
});
|
||||
|
||||
it('rejects oversize uploads (limit=1mb, file=2mb)', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const big = Buffer.alloc(2 * 1024 * 1024, 'a'); // 2MB
|
||||
const res = await agent
|
||||
.post('/api/v1/uploads/category-icon')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.attach('file', big, 'big.bin');
|
||||
// Multer's LIMIT_FILE_SIZE surfaces as 500 by default; we accept 4xx/5xx
|
||||
// and just verify the file was NOT saved.
|
||||
expect([400, 413, 500]).toContain(res.status);
|
||||
const icons = fs.existsSync(path.join(process.env.UPLOAD_DIR!, 'icons'))
|
||||
? fs.readdirSync(path.join(process.env.UPLOAD_DIR!, 'icons'))
|
||||
: [];
|
||||
expect(icons.some((f) => f === 'big.bin')).toBe(false);
|
||||
});
|
||||
|
||||
it('stores files under per-route subdirectories', async () => {
|
||||
const { agent, csrf } = await primeCsrf();
|
||||
const res = await agent
|
||||
.post('/api/v1/uploads/challenge-file')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.attach('file', Buffer.from('attachment'), 'readme.txt');
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.publicUrl).toMatch(/^\/uploads\/challenges\//);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user