70 lines
2.7 KiB
TypeScript
70 lines
2.7 KiB
TypeScript
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 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('CSRF: login is now protected', () => {
|
|
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));
|
|
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('rejects POST /api/v1/auth/login without CSRF header', async () => {
|
|
const server = app.getHttpServer();
|
|
await request(server)
|
|
.post('/api/v1/auth/login')
|
|
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
|
.expect(403);
|
|
});
|
|
|
|
it('accepts POST /api/v1/auth/login with valid CSRF header', async () => {
|
|
const server = app.getHttpServer();
|
|
const prime = await request(server).get('/api/v1/auth/csrf').expect(200);
|
|
const csrfCookie = (prime.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
|
|
const csrfToken = csrfCookie ? decodeURIComponent(csrfCookie.split(';')[0].split('=')[1]) : '';
|
|
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);
|
|
});
|
|
|
|
it('still allows /api/v1/auth/register-first-admin without CSRF', async () => {
|
|
const server = app.getHttpServer();
|
|
await request(server)
|
|
.post('/api/v1/auth/register-first-admin')
|
|
.send({ username: 'noone', password: 'Sup3rSecret!Pass' })
|
|
.expect(409);
|
|
});
|
|
}); |