Harden scaffold (reviewer followups)

- main.ts awaits DatabaseInitService.init() before app.listen(), ensuring
  migrations + seed run before the HTTP server accepts traffic.
- AppModule now uses NestModule with consumer.apply() no longer needed for
  CSRF (registered globally via app.use after body parsers in main.ts).
- JwtAuthGuard extended from AuthGuard('jwt') so protected endpoints
  actually validate the bearer token.
- Admin controller now uses Zod-validated DTOs for body/path/query:
  createUser, updateUserRole, userIdParam, listUsersQuery; with @Public
  / @Roles decorators and AdminGuard applied.
- Multer upload module + controller (POST /api/v1/uploads/category-icon
  and /challenge-file) with safe-filename strategy, configured
  UPLOAD_SIZE_LIMIT, admin-only via AdminGuard, served via /uploads
  static handler.
- ThemeLoaderService now requires all 10 canonical theme ids at startup,
  backfilling missing themes from built-ins with a warning; validates the
  configured themeKey setting and falls back to 'classic' if invalid;
  gracefully tolerates missing setting table during early boot.
- Test suite expanded to 76 tests / 17 suites; new specs:
  admin-validation, uploads, theme-required, database-init.
This commit is contained in:
OpenVelo Agent
2026-07-21 14:04:27 +00:00
parent af3c24275d
commit ac6c834525
23 changed files with 934 additions and 75 deletions
+163
View File
@@ -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);
});
});
});