feat: Scoreboard: Ranking, Matrix, Event Log and Score Graph
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_DIR = '/tmp/hipctf-scoreboard-controller-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 { getRepositoryToken } from '@nestjs/typeorm';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import * as argon2 from 'argon2';
|
||||
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 { ChallengeEntity } from '../../backend/src/database/entities/challenge.entity';
|
||||
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
|
||||
import { SolveEntity } from '../../backend/src/database/entities/solve.entity';
|
||||
import { UserEntity } from '../../backend/src/database/entities/user.entity';
|
||||
import { SettingsService } from '../../backend/src/modules/settings/settings.module';
|
||||
import { SETTINGS_KEYS } from '../../backend/src/config/env.schema';
|
||||
|
||||
describe('GET /api/v1/scoreboard/*', () => {
|
||||
let app: INestApplication;
|
||||
let adminToken: string;
|
||||
let solveRepo: any;
|
||||
let userRepo: any;
|
||||
let challengeRepo: any;
|
||||
let categoryRepo: any;
|
||||
let settings: SettingsService;
|
||||
let challengeA: ChallengeEntity;
|
||||
let challengeB: ChallengeEntity;
|
||||
let playerA: string;
|
||||
let playerB: string;
|
||||
|
||||
async function setRunningWindow(): Promise<void> {
|
||||
await settings.set(SETTINGS_KEYS.EVENT_START_UTC, new Date(Date.now() - 3600_000).toISOString());
|
||||
await settings.set(SETTINGS_KEYS.EVENT_END_UTC, new Date(Date.now() + 3600_000).toISOString());
|
||||
}
|
||||
|
||||
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);
|
||||
solveRepo = app.get(getRepositoryToken(SolveEntity));
|
||||
userRepo = app.get(getRepositoryToken(UserEntity));
|
||||
challengeRepo = app.get(getRepositoryToken(ChallengeEntity));
|
||||
categoryRepo = app.get(getRepositoryToken(CategoryEntity));
|
||||
|
||||
await setRunningWindow();
|
||||
|
||||
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 csrf = csrfCookie ? decodeURIComponent(csrfCookie.split(';')[0].split('=')[1]) : '';
|
||||
const login = await request(server).post('/api/v1/auth/login')
|
||||
.set('Cookie', `csrf=${csrf}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = login.body.accessToken;
|
||||
|
||||
const cry = await categoryRepo.findOne({ where: { systemKey: 'CRY' } });
|
||||
if (!cry) throw new Error('expected CRY category');
|
||||
|
||||
challengeA = await challengeRepo.save(challengeRepo.create({
|
||||
id: uuid(),
|
||||
name: 'chal-a',
|
||||
descriptionMd: '',
|
||||
categoryId: cry.id,
|
||||
difficulty: 'LOW',
|
||||
initialPoints: 500,
|
||||
minimumPoints: 100,
|
||||
decaySolves: 2,
|
||||
flag: 'flag{a}',
|
||||
protocol: 'WEB',
|
||||
port: null,
|
||||
ipAddress: '',
|
||||
enabled: true,
|
||||
}));
|
||||
challengeB = await challengeRepo.save(challengeRepo.create({
|
||||
id: uuid(),
|
||||
name: 'chal-b',
|
||||
descriptionMd: '',
|
||||
categoryId: cry.id,
|
||||
difficulty: 'LOW',
|
||||
initialPoints: 200,
|
||||
minimumPoints: 50,
|
||||
decaySolves: 5,
|
||||
flag: 'flag{b}',
|
||||
protocol: 'WEB',
|
||||
port: null,
|
||||
ipAddress: '',
|
||||
enabled: true,
|
||||
}));
|
||||
|
||||
const passwordHash = await argon2.hash('PlayerPass!1Ab', { type: argon2.argon2id });
|
||||
const a = await userRepo.save(userRepo.create({ id: uuid(), username: 'alice', passwordHash, role: 'player', status: 'enabled' }));
|
||||
const b = await userRepo.save(userRepo.create({ id: uuid(), username: 'bob', passwordHash, role: 'player', status: 'enabled' }));
|
||||
const c = await userRepo.save(userRepo.create({ id: uuid(), username: 'carol', passwordHash, role: 'player', status: 'enabled' }));
|
||||
playerA = a.id;
|
||||
playerB = b.id;
|
||||
void c;
|
||||
|
||||
await solveRepo.save(solveRepo.create({
|
||||
id: uuid(),
|
||||
challengeId: challengeA.id,
|
||||
userId: playerA,
|
||||
solvedAt: new Date(Date.now() - 1000).toISOString(),
|
||||
pointsAwarded: 515,
|
||||
basePoints: 500,
|
||||
rankBonus: 15,
|
||||
isFirst: 1,
|
||||
isSecond: 0,
|
||||
isThird: 0,
|
||||
}));
|
||||
await solveRepo.save(solveRepo.create({
|
||||
id: uuid(),
|
||||
challengeId: challengeB.id,
|
||||
userId: playerA,
|
||||
solvedAt: new Date(Date.now() - 500).toISOString(),
|
||||
pointsAwarded: 210,
|
||||
basePoints: 200,
|
||||
rankBonus: 10,
|
||||
isFirst: 1,
|
||||
isSecond: 0,
|
||||
isThird: 0,
|
||||
}));
|
||||
await solveRepo.save(solveRepo.create({
|
||||
id: uuid(),
|
||||
challengeId: challengeA.id,
|
||||
userId: playerB,
|
||||
solvedAt: new Date(Date.now() - 100).toISOString(),
|
||||
pointsAwarded: 110,
|
||||
basePoints: 100,
|
||||
rankBonus: 10,
|
||||
isFirst: 0,
|
||||
isSecond: 1,
|
||||
isThird: 0,
|
||||
}));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function authed(): any {
|
||||
const r: any = request(app.getHttpServer());
|
||||
r.set = ((h: string, v: string) => { r.headers = r.headers || {}; r.headers[h] = v; return r; });
|
||||
return r;
|
||||
}
|
||||
|
||||
it('rejects unauthenticated ranking with 401', async () => {
|
||||
await request(app.getHttpServer()).get('/api/v1/scoreboard/ranking').expect(401);
|
||||
});
|
||||
|
||||
it('returns competition-ranked ranking including zero-pt player', async () => {
|
||||
const res = await authed().get('/api/v1/scoreboard/ranking').set('Authorization', `Bearer ${adminToken}`).expect(200);
|
||||
expect(Array.isArray(res.body)).toBe(true);
|
||||
expect(res.body.length).toBe(4);
|
||||
expect(res.body[0]).toMatchObject({ rank: 1, playerName: 'alice' });
|
||||
expect(res.body[0].points).toBe(725);
|
||||
expect(res.body[1].rank).toBe(2);
|
||||
const zeroPointRows = res.body.filter((r: any) => r.points === 0);
|
||||
expect(zeroPointRows.length).toBe(2);
|
||||
expect(zeroPointRows[0].rank).toBe(3);
|
||||
});
|
||||
|
||||
it('returns matrix with players and challenges', async () => {
|
||||
const res = await authed().get('/api/v1/scoreboard/matrix').set('Authorization', `Bearer ${adminToken}`).expect(200);
|
||||
expect(res.body.players.length).toBe(4);
|
||||
expect(res.body.challenges.length).toBeGreaterThanOrEqual(2);
|
||||
const challengeIds = res.body.challenges.map((c: any) => c.id);
|
||||
expect(challengeIds).toContain(challengeA.id);
|
||||
expect(challengeIds).toContain(challengeB.id);
|
||||
const aliceCells = res.body.cells[playerA];
|
||||
expect(aliceCells[challengeA.id]).toBe(1);
|
||||
expect(aliceCells[challengeB.id]).toBe(1);
|
||||
const bobCells = res.body.cells[playerB];
|
||||
expect(bobCells[challengeA.id]).toBe(2);
|
||||
expect(bobCells[challengeB.id]).toBeNull();
|
||||
});
|
||||
|
||||
it('returns event-log in DESC order with limit', async () => {
|
||||
const res = await authed().get('/api/v1/scoreboard/event-log?limit=2').set('Authorization', `Bearer ${adminToken}`).expect(200);
|
||||
expect(res.body.length).toBe(2);
|
||||
const ts = res.body.map((r: any) => r.awardedAtUtc);
|
||||
expect(ts[0] >= ts[1]).toBe(true);
|
||||
});
|
||||
|
||||
it('returns graph with top-10 series and start/end anchors', async () => {
|
||||
const res = await authed().get('/api/v1/scoreboard/graph').set('Authorization', `Bearer ${adminToken}`).expect(200);
|
||||
expect(res.body.state).toBe('running');
|
||||
expect(res.body.startUtc).toBeTruthy();
|
||||
expect(res.body.endUtc).toBeTruthy();
|
||||
expect(res.body.series.length).toBeGreaterThan(0);
|
||||
const top = res.body.series[0];
|
||||
expect(top.points[0]).toMatchObject({ value: 0 });
|
||||
expect(top.points[top.points.length - 1].tUtc).toBe(res.body.endUtc);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user