feat: add basic auth

This commit is contained in:
2026-10-21 10:31:23 +03:00
parent ef2bc6f8b6
commit 0563ebfb10
28 changed files with 633 additions and 176 deletions
+1
View File
@@ -55,6 +55,7 @@ services:
APP_HOST: 0.0.0.0
APP_PORT: 8080
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DATABASE_URL_FILE: /run/secrets/database_url
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
+45
View File
@@ -13,6 +13,7 @@
"@nestjs/core": "^10.4.15",
"@nestjs/platform-fastify": "^10.4.15",
"@prisma/client": "6.1.0",
"argon2": "0.41.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"reflect-metadata": "^0.2.2",
@@ -2048,6 +2049,15 @@
"@noble/hashes": "^1.1.5"
}
},
"node_modules/@phc/format": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz",
"integrity": "sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -3020,6 +3030,21 @@
"dev": true,
"license": "MIT"
},
"node_modules/argon2": {
"version": "0.41.1",
"resolved": "https://registry.npmjs.org/argon2/-/argon2-0.41.1.tgz",
"integrity": "sha512-dqCW8kJXke8Ik+McUcMDltrbuAWETPyU6iq+4AhxqKphWi7pChB/Zgd/Tp/o8xRLbg8ksMj46F/vph9wnxpTzQ==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@phc/format": "^1.0.0",
"node-addon-api": "^8.1.0",
"node-gyp-build": "^4.8.1"
},
"engines": {
"node": ">=16.17.0"
}
},
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
@@ -7127,6 +7152,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/node-addon-api": {
"version": "8.9.2",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
"integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
"license": "MIT",
"engines": {
"node": "^18 || ^20 || >= 21"
}
},
"node_modules/node-emoji": {
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz",
@@ -7157,6 +7191,17 @@
}
}
},
"node_modules/node-gyp-build": {
"version": "4.8.4",
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
"integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
"license": "MIT",
"bin": {
"node-gyp-build": "bin.js",
"node-gyp-build-optional": "optional.js",
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/node-int64": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
+1
View File
@@ -17,6 +17,7 @@
"@nestjs/core": "^10.4.15",
"@nestjs/platform-fastify": "^10.4.15",
"@prisma/client": "6.1.0",
"argon2": "0.41.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"reflect-metadata": "^0.2.2",
@@ -0,0 +1,14 @@
ALTER TABLE "users" ADD COLUMN "password_hash" TEXT NOT NULL;
CREATE TABLE "sessions" (
"token_hash" CHAR(64) NOT NULL,
"user_id" UUID NOT NULL,
"expires_at" TIMESTAMPTZ(3) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "sessions_pkey" PRIMARY KEY ("token_hash")
);
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+19 -6
View File
@@ -8,16 +8,29 @@ datasource db {
}
model User {
id String @id @default(uuid()) @db.Uuid
username String @unique @db.VarChar(32)
displayName String @map("display_name") @db.VarChar(100)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
memberships ChatMember[]
messages Message[]
id String @id @default(uuid()) @db.Uuid
username String @unique @db.VarChar(32)
displayName String @map("display_name") @db.VarChar(100)
passwordHash String @map("password_hash")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
memberships ChatMember[]
messages Message[]
sessions Session[]
@@map("users")
}
model Session {
tokenHash String @id @map("token_hash") @db.Char(64)
userId String @map("user_id") @db.Uuid
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@map("sessions")
}
model Chat {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(100)
+2 -2
View File
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { ChatsModule } from './chats/chats.module';
import { CommonModule } from './common/common.module';
import { DbModule } from './db/db.module';
import { HealthModule } from './health/health.module';
import { MessagesModule } from './messages/messages.module';
@@ -9,7 +9,7 @@ import { UsersModule } from './users/users.module';
@Module({
imports: [
DbModule,
CommonModule,
AuthModule,
HealthModule,
UsersModule,
ChatsModule,
+46
View File
@@ -0,0 +1,46 @@
import {
Controller,
Delete,
Headers,
HttpCode,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { toUserResponse, UserResponse } from '../users/dto/user.response';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
interface SessionResponse {
token: string;
token_type: 'Bearer';
expires_at: string;
user: UserResponse;
}
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
@HttpCode(201)
async create(
@Headers('authorization') authorization: string | undefined,
): Promise<SessionResponse> {
const session = await this.auth.login(authorization);
return {
token: session.token,
token_type: 'Bearer',
expires_at: session.expiresAt.toISOString(),
user: toUserResponse(session.user),
};
}
@Delete('current')
@HttpCode(204)
@UseGuards(AuthGuard)
async revoke(@Req() request: FastifyRequest): Promise<void> {
await this.auth.revoke(request.sessionTokenHash!);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { ApiError } from '../common/filters/api-error';
import { AuthService } from './auth.service';
const BEARER_CHALLENGE = 'Bearer realm="messenger"';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly auth: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? '');
const session = match ? await this.auth.resolve(match[1]) : null;
if (!session) {
throw new ApiError('unauthorized', 'missing or invalid session', {
'WWW-Authenticate': BEARER_CHALLENGE,
});
}
request.currentUser = session.user;
request.sessionTokenHash = session.tokenHash;
return true;
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Global, Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
@Global()
@Module({
controllers: [AuthController],
providers: [AuthService, AuthGuard],
exports: [AuthService, AuthGuard],
})
export class AuthModule {}
+107
View File
@@ -0,0 +1,107 @@
import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { User } from '../common/domain';
import { ApiError } from '../common/filters/api-error';
import { PrismaService } from '../db/prisma.service';
import { toUser } from '../users/users.service';
import { verifyPassword } from './password';
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/;
export interface CreatedSession {
token: string;
expiresAt: Date;
user: User;
}
export interface ResolvedSession {
tokenHash: string;
user: User;
}
@Injectable()
export class AuthService {
private readonly ttlSeconds = readSessionTtl();
constructor(private readonly prisma: PrismaService) {}
async login(authorization: string | undefined): Promise<CreatedSession> {
const credentials = parseBasic(authorization);
if (!credentials) {
throw invalidCredentials();
}
const row = await this.prisma.user.findUnique({
where: { username: credentials.username },
});
const valid = await verifyPassword(
row?.passwordHash ?? null,
credentials.password,
);
if (!row || !valid) {
throw invalidCredentials();
}
const token = randomBytes(32).toString('base64url');
const expiresAt = new Date(Date.now() + this.ttlSeconds * 1000);
await this.prisma.session.create({
data: { tokenHash: hashToken(token), userId: row.id, expiresAt },
});
return { token, expiresAt, user: toUser(row) };
}
async resolve(token: string): Promise<ResolvedSession | null> {
const tokenHash = hashToken(token);
const session = await this.prisma.session.findUnique({
where: { tokenHash },
include: { user: true },
});
if (!session || session.expiresAt.getTime() <= Date.now()) {
return null;
}
return { tokenHash, user: toUser(session.user) };
}
async revoke(tokenHash: string): Promise<void> {
await this.prisma.session.deleteMany({ where: { tokenHash } });
}
}
function parseBasic(
header: string | undefined,
): { username: string; password: string } | null {
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? '');
if (!match) {
return null;
}
const decoded = Buffer.from(match[1], 'base64').toString('utf8');
const separator = decoded.indexOf(':');
if (separator < 0) {
return null;
}
const username = decoded.slice(0, separator);
const password = decoded.slice(separator + 1);
const length = codePointLength(password);
if (!USERNAME_PATTERN.test(username) || length < 12 || length > 128) {
return null;
}
return { username, password };
}
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
function invalidCredentials(): ApiError {
return new ApiError('unauthorized', 'invalid credentials', {
'WWW-Authenticate': BASIC_CHALLENGE,
});
}
function readSessionTtl(): number {
const ttl = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
if (!Number.isInteger(ttl) || ttl <= 0) {
throw new Error('SESSION_TTL_SECONDS must be a positive integer');
}
return ttl;
}
@@ -1,10 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { User } from '../domain';
import { User } from '../common/domain';
declare module 'fastify' {
interface FastifyRequest {
currentUser?: User;
sessionTokenHash?: string;
}
}
+17
View File
@@ -0,0 +1,17 @@
import { argon2id, hash, verify } from 'argon2';
const OPTIONS = { type: argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const dummyHash = hash('timing-equalizer-password', OPTIONS);
export function hashPassword(password: string): Promise<string> {
return hash(password, OPTIONS);
}
export async function verifyPassword(
passwordHash: string | null,
password: string,
): Promise<boolean> {
const valid = await verify(passwordHash ?? (await dummyHash), password);
return passwordHash !== null && valid;
}
+2 -2
View File
@@ -8,8 +8,8 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../common/auth/auth.guard';
import { CurrentUser } from '../common/auth/current-user.decorator';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
import { User } from '../common/domain';
import { ChatsService } from './chats.service';
-2
View File
@@ -1,10 +1,8 @@
import { Module } from '@nestjs/common';
import { CommonModule } from '../common/common.module';
import { ChatsController } from './chats.controller';
import { ChatsService } from './chats.service';
@Module({
imports: [CommonModule],
controllers: [ChatsController],
providers: [ChatsService],
exports: [ChatsService],
-26
View File
@@ -1,26 +0,0 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { PrismaService } from '../../db/prisma.service';
import { toUser } from '../../users/users.service';
import { ApiError } from '../filters/api-error';
import { validate as isUuid } from '../uuid';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly prisma: PrismaService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const header = request.headers['x-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !isUuid(userId)) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
const row = await this.prisma.user.findUnique({ where: { id: userId } });
if (!row) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
request.currentUser = toUser(row);
return true;
}
}
-9
View File
@@ -1,9 +0,0 @@
import { Global, Module } from '@nestjs/common';
import { AuthGuard } from './auth/auth.guard';
@Global()
@Module({
providers: [AuthGuard],
exports: [AuthGuard],
})
export class CommonModule {}
+1
View File
@@ -27,6 +27,7 @@ export class ApiError extends HttpException {
constructor(
public readonly code: ErrorCode,
message: string,
public readonly headers: Record<string, string> = {},
) {
super(message, STATUS_BY_CODE[code]);
}
@@ -44,6 +44,9 @@ export class HttpExceptionFilter implements ExceptionFilter {
);
}
if (exception instanceof ApiError) {
reply.headers(exception.headers);
}
reply
.code(status)
.header('x-request-id', requestId)
+2 -2
View File
@@ -8,8 +8,8 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../common/auth/auth.guard';
import { CurrentUser } from '../common/auth/current-user.decorator';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
import { User } from '../common/domain';
import { CreateMessageDto } from './dto/create-message.dto';
-2
View File
@@ -1,10 +1,8 @@
import { Module } from '@nestjs/common';
import { CommonModule } from '../common/common.module';
import { MessagesController } from './messages.controller';
import { MessagesService } from './messages.service';
@Module({
imports: [CommonModule],
controllers: [MessagesController],
providers: [MessagesService],
})
+4
View File
@@ -11,4 +11,8 @@ export class CreateUserDto {
@NotBlank()
@CodePointLength(1, 100)
display_name!: string;
@NotBlank()
@CodePointLength(12, 128)
password!: string;
}
+7 -3
View File
@@ -6,8 +6,8 @@ import {
Post,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../common/auth/auth.guard';
import { CurrentUser } from '../common/auth/current-user.decorator';
import { AuthGuard } from '../auth/auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { User } from '../common/domain';
import { CreateUserDto } from './dto/create-user.dto';
import { toUserResponse, UserResponse } from './dto/user.response';
@@ -20,7 +20,11 @@ export class UsersController {
@Post()
@HttpCode(201)
async create(@Body() dto: CreateUserDto): Promise<UserResponse> {
const user = await this.users.register(dto.username, dto.display_name);
const user = await this.users.register(
dto.username,
dto.display_name,
dto.password,
);
return toUserResponse(user);
}
-2
View File
@@ -1,10 +1,8 @@
import { Module } from '@nestjs/common';
import { CommonModule } from '../common/common.module';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
imports: [CommonModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
+8 -2
View File
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { hashPassword } from '../auth/password';
import { ApiError } from '../common/filters/api-error';
import { User } from '../common/domain';
import { PrismaService, isUniqueViolation } from '../db/prisma.service';
@@ -7,10 +8,15 @@ import { PrismaService, isUniqueViolation } from '../db/prisma.service';
export class UsersService {
constructor(private readonly prisma: PrismaService) {}
async register(username: string, displayName: string): Promise<User> {
async register(
username: string,
displayName: string,
password: string,
): Promise<User> {
const passwordHash = await hashPassword(password);
try {
const row = await this.prisma.user.create({
data: { username, displayName: displayName.trim() },
data: { username, displayName: displayName.trim(), passwordHash },
});
return toUser(row);
} catch (error) {
+63 -74
View File
@@ -1,45 +1,28 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import request from 'supertest';
import { randomUUID } from 'crypto';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
import {
bearer,
createTestApp,
PASSWORD,
registerUser,
TestUser,
} from './helpers';
describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const fastifyApp =
moduleRef.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
app = fastifyApp;
configureApp(fastifyApp);
await fastifyApp.listen(0, '127.0.0.1');
server = fastifyApp.getHttpServer();
({ app, server } = await createTestApp());
});
afterAll(async () => {
await app.close();
});
async function createUser(label: string) {
const res = await request(server)
.post('/api/v1/users')
.send({
username: `u_${label}_${randomUUID().slice(0, 8)}`,
display_name: `User ${label}`,
})
.expect(201);
return res.body as { id: string; username: string };
function createUser(label: string): Promise<TestUser> {
return registerUser(server, label);
}
describe('POST /api/v1/users', () => {
@@ -59,6 +42,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: 'validname1',
display_name: 'Valid',
password: PASSWORD,
extra: 'nope',
})
.expect(400);
@@ -68,14 +52,14 @@ describe('API мессенджера (e2e) — граничные случаи
it('отклоняет username с заглавными буквами', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'InvalidName', display_name: 'X' })
.send({ username: 'InvalidName', display_name: 'X', password: PASSWORD })
.expect(400);
});
it('отклоняет display_name из одних пробелов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'wsonlyname1', display_name: ' ' })
.send({ username: 'wsonlyname1', display_name: ' ', password: PASSWORD })
.expect(400);
});
@@ -83,7 +67,7 @@ describe('API мессенджера (e2e) — граничные случаи
const user = await createUser('dup');
const res = await request(server)
.post('/api/v1/users')
.send({ username: user.username, display_name: 'Someone else' })
.send({ username: user.username, display_name: 'Someone else', password: PASSWORD })
.expect(409);
expect(res.body.error.code).toBe('conflict');
});
@@ -94,6 +78,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `nopass_${randomUUID().slice(0, 8)}`,
display_name: 'X',
password: PASSWORD,
})
.expect(201);
expect(res.body).not.toHaveProperty('password');
@@ -103,21 +88,21 @@ describe('API мессенджера (e2e) — граничные случаи
it('отклоняет username короче 3 символов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'ab', display_name: 'X' })
.send({ username: 'ab', display_name: 'X', password: PASSWORD })
.expect(400);
});
it('отклоняет username длиннее 32 символов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'a'.repeat(33), display_name: 'X' })
.send({ username: 'a'.repeat(33), display_name: 'X', password: PASSWORD })
.expect(400);
});
it('отклоняет username с недопустимыми символами (дефис)', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'has-hyphen', display_name: 'X' })
.send({ username: 'has-hyphen', display_name: 'X', password: PASSWORD })
.expect(400);
});
@@ -127,12 +112,13 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `a${randomUUID().slice(0, 2)}`,
display_name: 'X',
password: PASSWORD,
})
.expect(201);
const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32);
await request(server)
.post('/api/v1/users')
.send({ username: longest, display_name: 'X' })
.send({ username: longest, display_name: 'X', password: PASSWORD })
.expect(201);
});
@@ -142,6 +128,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `toolongname_${randomUUID().slice(0, 6)}`,
display_name: 'x'.repeat(101),
password: PASSWORD,
})
.expect(400);
});
@@ -154,6 +141,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `emojiname_${randomUUID().slice(0, 6)}`,
display_name: displayName,
password: PASSWORD,
})
.expect(201);
});
@@ -166,6 +154,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `emojitoolong_${randomUUID().slice(0, 6)}`,
display_name: displayName,
password: PASSWORD,
})
.expect(400);
});
@@ -175,7 +164,7 @@ describe('API мессенджера (e2e) — граничные случаи
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
const res = await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', 'not-a-uuid')
.set('Authorization', 'Bearer not-a-token')
.expect(401);
expect(res.body.error.code).toBe('unauthorized');
});
@@ -186,13 +175,13 @@ describe('API мессенджера (e2e) — граничные случаи
const eve = await createUser('eve');
const chat = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Private', member_ids: [alice.id, bob.id] })
.expect(201);
const res = await request(server)
.get(`/api/v1/chats/${chat.body.id}`)
.set('X-User-Id', eve.id)
.set('Authorization', bearer(eve))
.expect(404);
expect(res.body.error.code).toBe('not_found');
});
@@ -202,7 +191,7 @@ describe('API мессенджера (e2e) — граничные случаи
const bob = await createUser('bob2');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Missing caller', member_ids: [bob.id] })
.expect(400);
});
@@ -211,7 +200,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice3');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({
title: 'Dup members',
member_ids: [alice.id, alice.id],
@@ -223,7 +212,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({
title: 'Unknown member',
member_ids: [alice.id, randomUUID()],
@@ -235,7 +224,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4b');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: ' ', member_ids: [alice.id] })
.expect(400);
});
@@ -244,7 +233,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4c');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -253,7 +242,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4d');
await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(404);
});
});
@@ -263,12 +252,12 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice1');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Only chat', member_ids: [alice.id] })
.expect(201);
const res = await request(server)
.get('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(200);
expect(res.body.items.length).toBeGreaterThanOrEqual(1);
expect(res.body.items.length).toBeLessThanOrEqual(50);
@@ -278,7 +267,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice2');
await request(server)
.get('/api/v1/chats?limit=abc')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -286,7 +275,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice3');
await request(server)
.get('/api/v1/chats?limit=0')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -295,7 +284,7 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.get('/api/v1/chats')
.query({ cursor: 'not-a-real-cursor!!!' })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -308,7 +297,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.get('/api/v1/chats')
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -319,7 +308,7 @@ describe('API мессенджера (e2e) — граничные случаи
for (const title of titles) {
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title, member_ids: [alice.id] })
.expect(201);
}
@@ -330,7 +319,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res: request.Response = await request(server)
.get('/api/v1/chats')
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(200);
seen.push(
...res.body.items.map((c: { title: string }) => c.title),
@@ -343,10 +332,10 @@ describe('API мессенджера (e2e) — граничные случаи
});
describe('сообщения', () => {
async function createChat(alice: { id: string }, bob: { id: string }) {
async function createChat(alice: TestUser, bob: TestUser) {
const res = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Chat', member_ids: [alice.id, bob.id] })
.expect(201);
return res.body as { id: string };
@@ -359,7 +348,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'hi', sender_id: bob.id })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
@@ -371,7 +360,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: '' })
.expect(400);
});
@@ -382,7 +371,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: ' \n\t ' })
.expect(400);
});
@@ -394,7 +383,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', eve.id)
.set('Authorization', bearer(eve))
.send({ text: 'intrusion' })
.expect(404);
});
@@ -405,7 +394,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=0`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -415,7 +404,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=101`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -425,7 +414,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=abc`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -435,7 +424,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'x'.repeat(4001) })
.expect(400);
});
@@ -446,7 +435,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'x'.repeat(4000) })
.expect(201);
});
@@ -459,7 +448,7 @@ describe('API мессенджера (e2e) — граничные случаи
expect([...text].length).toBe(4001);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text })
.expect(400);
});
@@ -471,7 +460,7 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: '!!!not-valid!!!' })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -481,7 +470,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'only message' })
.expect(201);
@@ -492,7 +481,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -501,7 +490,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice10g');
const res = await request(server)
.post('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'hi' })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
@@ -511,7 +500,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice10h');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -524,25 +513,25 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'first' })
.expect(201);
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'second' })
.expect(201);
const page1 = await request(server)
.get(`/api/v1/chats/${chatA.id}/messages?limit=1`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(200);
expect(page1.body.next_cursor).toBeTruthy();
const res = await request(server)
.get(`/api/v1/chats/${chatB.id}/messages`)
.query({ cursor: page1.body.next_cursor })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -555,7 +544,7 @@ describe('API мессенджера (e2e) — граничные случаи
for (const text of sentTexts) {
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text })
.expect(201);
}
@@ -566,7 +555,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res: request.Response = await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(200);
seen.push(
...res.body.items.map((m: { text: string }) => m.text),
+167
View File
@@ -0,0 +1,167 @@
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { randomUUID } from 'crypto';
import { PrismaService } from '../src/db/prisma.service';
import {
basic,
bearer,
createTestApp,
login,
PASSWORD,
registerUser,
} from './helpers';
describe('Аутентификация и сессии (e2e)', () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
({ app, server } = await createTestApp());
});
afterAll(async () => {
await app.close();
});
describe('регистрация', () => {
it('требует password', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: `nopw_${randomUUID().slice(0, 8)}`, display_name: 'X' })
.expect(400);
});
it('отклоняет password короче 12 code points', async () => {
await request(server)
.post('/api/v1/users')
.send({
username: `short_${randomUUID().slice(0, 8)}`,
display_name: 'X',
password: 'x'.repeat(11),
})
.expect(400);
});
it('хранит пароль как Argon2id-хеш, а не открытым текстом', async () => {
const user = await registerUser(server, 'hash');
const row = await app
.get(PrismaService)
.user.findUniqueOrThrow({ where: { id: user.id } });
expect(row.passwordHash.startsWith('$argon2id$')).toBe(true);
expect(row.passwordHash).not.toContain(PASSWORD);
});
});
describe('POST /api/v1/auth/sessions', () => {
it('выдаёт непрозрачный Bearer-токен с expires_at и пользователем', async () => {
const user = await registerUser(server, 'login');
const res = await request(server)
.post('/api/v1/auth/sessions')
.set('Authorization', basic(user.username, PASSWORD))
.expect(201);
expect(res.body.token_type).toBe('Bearer');
expect(res.body.token.length).toBeGreaterThanOrEqual(43);
expect(res.body.token).not.toContain(user.id);
expect(res.body.user.id).toBe(user.id);
const expiresIn = Date.parse(res.body.expires_at) - Date.now();
expect(expiresIn).toBeGreaterThan(3500 * 1000);
expect(expiresIn).toBeLessThanOrEqual(3600 * 1000);
});
it('принимает пароль с двоеточием и не-ASCII символами', async () => {
const username = `colon_${randomUUID().slice(0, 8)}`;
const password = 'пароль:с:двоеточием🔑';
await request(server)
.post('/api/v1/users')
.send({ username, display_name: 'X', password })
.expect(201);
await login(server, username, password);
});
it('отвечает одинаковым 401 на неверный пароль и неизвестного пользователя', async () => {
const user = await registerUser(server, 'wrong');
const wrong = await request(server)
.post('/api/v1/auth/sessions')
.set('Authorization', basic(user.username, 'wrong-password-123'))
.expect(401);
const unknown = await request(server)
.post('/api/v1/auth/sessions')
.set('Authorization', basic(`ghost_${randomUUID().slice(0, 8)}`, PASSWORD))
.expect(401);
for (const res of [wrong, unknown]) {
expect(res.headers['www-authenticate']).toBe(
'Basic realm="messenger", charset="UTF-8"',
);
expect(res.body.error.code).toBe('unauthorized');
}
expect(wrong.body.error.message).toBe(unknown.body.error.message);
});
it('отвечает 401 без заголовка Authorization', async () => {
const res = await request(server)
.post('/api/v1/auth/sessions')
.expect(401);
expect(res.headers['www-authenticate']).toContain('Basic');
});
});
describe('защищённые endpoint', () => {
it('не принимают Basic', async () => {
const user = await registerUser(server, 'basic');
const res = await request(server)
.get('/api/v1/users/me')
.set('Authorization', basic(user.username, PASSWORD))
.expect(401);
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
});
it('не принимают X-User-Id сам по себе', async () => {
const user = await registerUser(server, 'xuid');
await request(server)
.get('/api/v1/users/me')
.set('X-User-Id', user.id)
.expect(401);
});
it('игнорируют X-User-Id рядом с Bearer', async () => {
const alice = await registerUser(server, 'alice');
const eve = await registerUser(server, 'eve');
const res = await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(alice))
.set('X-User-Id', eve.id)
.expect(200);
expect(res.body.id).toBe(alice.id);
});
it('отвечают 401 на неизвестный токен', async () => {
await request(server)
.get('/api/v1/users/me')
.set('Authorization', 'Bearer unknown-token-value')
.expect(401);
});
});
describe('DELETE /api/v1/auth/sessions/current', () => {
it('отзывает только текущий токен: 204, затем 401 на повтор', async () => {
const user = await registerUser(server, 'logout');
const other = await login(server, user.username);
await request(server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(204);
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(401);
await request(server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(401);
await request(server)
.get('/api/v1/users/me')
.set('Authorization', `Bearer ${other}`)
.expect(200);
});
});
});
+20 -43
View File
@@ -1,30 +1,20 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import request from 'supertest';
import { randomUUID } from 'crypto';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
import {
bearer,
createTestApp,
login,
PASSWORD,
registerUser,
} from './helpers';
describe('Безопасность при конкурентном доступе (e2e)', () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const fastifyApp =
moduleRef.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
app = fastifyApp;
configureApp(fastifyApp);
await fastifyApp.listen(0, '127.0.0.1');
server = fastifyApp.getHttpServer();
({ app, server } = await createTestApp());
});
afterAll(async () => {
@@ -35,30 +25,17 @@ describe('Безопасность при конкурентном доступ
const CLIENTS = 10;
const MESSAGES_PER_CLIENT = 10;
const owner = await request(server)
.post('/api/v1/users')
.send({
username: `owner_${randomUUID().slice(0, 8)}`,
display_name: 'Owner',
})
.expect(201);
const owner = await registerUser(server, 'owner');
const clients = await Promise.all(
Array.from({ length: CLIENTS }, (_, i) =>
request(server)
.post('/api/v1/users')
.send({
username: `racer${i}_${randomUUID().slice(0, 6)}`,
display_name: `Racer ${i}`,
})
.expect(201),
registerUser(server, `racer${i}`),
),
);
const memberIds = [owner.body.id, ...clients.map((c) => c.body.id)];
const memberIds = [owner.id, ...clients.map((c) => c.id)];
const chat = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', owner.body.id)
.set('Authorization', bearer(owner))
.send({ title: 'Race', member_ids: memberIds })
.expect(201);
@@ -68,7 +45,7 @@ describe('Безопасность при конкурентном доступ
sendTasks.push(
request(server)
.post(`/api/v1/chats/${chat.body.id}/messages`)
.set('X-User-Id', clients[c].body.id)
.set('Authorization', bearer(clients[c]))
.send({ text: `client-${c}-message-${m}` }),
);
}
@@ -88,7 +65,7 @@ describe('Безопасность при конкурентном доступ
const res: request.Response = await request(server)
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 25, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', owner.body.id)
.set('Authorization', bearer(owner))
.expect(200);
collected.push(...res.body.items);
cursor = res.body.next_cursor;
@@ -105,7 +82,7 @@ describe('Безопасность при конкурентном доступ
await request(server)
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 100 })
.set('X-User-Id', owner.body.id)
.set('Authorization', bearer(owner))
.expect(200)
.then((res) => res.body.items);
const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`);
@@ -121,7 +98,7 @@ describe('Безопасность при конкурентном доступ
Array.from({ length: attempts }, () =>
request(server)
.post('/api/v1/users')
.send({ username, display_name: 'Racer' }),
.send({ username, display_name: 'Racer', password: PASSWORD }),
),
);
@@ -130,12 +107,12 @@ describe('Безопасность при конкурентном доступ
expect(succeeded.length).toBe(1);
expect(conflicted.length).toBe(attempts - 1);
expect(succeeded.length + conflicted.length).toBe(attempts);
const listRes = await request(server)
const token = await login(server, username);
const me = await request(server)
.get('/api/v1/users/me')
.set('X-User-Id', succeeded[0].body.id)
.set('Authorization', `Bearer ${token}`)
.expect(200);
expect(listRes.body.username).toBe(username);
expect(me.body.id).toBe(succeeded[0].body.id);
});
});
+65
View File
@@ -0,0 +1,65 @@
import { INestApplication } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { Test } from '@nestjs/testing';
import { randomUUID } from 'crypto';
import request from 'supertest';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
export const PASSWORD = 'Correct-Horse-Battery-42';
export interface TestUser {
id: string;
username: string;
token: string;
}
export async function createTestApp(): Promise<{
app: INestApplication;
server: any;
}> {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = moduleRef.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
configureApp(app);
await app.listen(0, '127.0.0.1');
return { app, server: app.getHttpServer() };
}
export function basic(username: string, password: string): string {
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
}
export function bearer(user: TestUser): string {
return `Bearer ${user.token}`;
}
export async function login(
server: any,
username: string,
password = PASSWORD,
): Promise<string> {
const res = await request(server)
.post('/api/v1/auth/sessions')
.set('Authorization', basic(username, password))
.expect(201);
return res.body.token;
}
export async function registerUser(
server: any,
label: string,
): Promise<TestUser> {
const username = `u_${label}_${randomUUID().slice(0, 8)}`;
const res = await request(server)
.post('/api/v1/users')
.send({ username, display_name: `User ${label}`, password: PASSWORD })
.expect(201);
return { id: res.body.id, username, token: await login(server, username) };
}