Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions apps/api-e2e/src/api/auth.e2e.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { createTestApp, login, seedEmployee, type TestContext } from '../support/test-app';
import {
createTestApp,
login,
seedEmployee,
type TestContext,
} from '../support/test-app';

describe('Auth — POST /api/auth/login', () => {
let ctx: TestContext;
Expand Down Expand Up @@ -33,6 +38,7 @@ describe('Auth — POST /api/auth/login', () => {
firstName: 'Hannah',
role: 'HRAdmin',
});
expect(await ctx.prisma.loginAttemptState.count()).toBe(0);
});

it('rejects wrong password with 401', async () => {
Expand Down Expand Up @@ -63,14 +69,85 @@ describe('Auth — POST /api/auth/login', () => {
lastName: 'Roth',
email: 'hannah@test.local',
});
await ctx.prisma.employee.update({ where: { id: e.id }, data: { isActive: false } });
await ctx.prisma.employee.update({
where: { id: e.id },
data: { isActive: false },
});

await ctx.http
.post('/api/auth/login')
.send({ email: 'hannah@test.local', password: 'test1234' })
.expect(401);
});

it('uses the same generic denial for unknown, inactive, wrong-password, and non-owner Solo accounts', async () => {
const owner = await seedEmployee(ctx.prisma, {
personalNo: 'OWNER',
firstName: 'Solo',
lastName: 'Owner',
email: 'owner@test.local',
});
const inactive = await seedEmployee(ctx.prisma, {
personalNo: 'INACTIVE',
firstName: 'Inactive',
lastName: 'Employee',
email: 'inactive@test.local',
});
await ctx.prisma.employee.update({
where: { id: inactive.id },
data: { isActive: false },
});
await seedEmployee(ctx.prisma, {
personalNo: 'OUTSIDER',
firstName: 'Team',
lastName: 'Outsider',
email: 'outsider@test.local',
});
await ctx.prisma.installationSettings.create({
data: { mode: 'Solo', ownerEmployeeId: owner.id },
});

const attempts = [
{ email: owner.email, password: 'wrong-password' },
{ email: 'unknown@test.local', password: 'test1234' },
{ email: inactive.email, password: 'test1234' },
{ email: 'outsider@test.local', password: 'test1234' },
];
let genericDenial: unknown;
for (const credentials of attempts) {
const response = await ctx.http
.post('/api/auth/login')
.send(credentials)
.expect(401);
genericDenial ??= response.body;
expect(response.body).toEqual(genericDenial);
expect(response.body.message).toBe('Invalid credentials');
}
});

it('atomically rate-limits parallel attempts with Retry-After responses', async () => {
await seedEmployee(ctx.prisma, {
personalNo: '0001',
firstName: 'Hannah',
lastName: 'Roth',
email: 'hannah@test.local',
});

const responses = await Promise.all(
Array.from({ length: 10 }, () =>
ctx.http
.post('/api/auth/login')
.send({ email: 'hannah@test.local', password: 'wrong-password' }),
),
);
expect(responses.filter(({ status }) => status === 401)).toHaveLength(5);
expect(responses.filter(({ status }) => status === 429)).toHaveLength(5);
const limited = responses.find(({ status }) => status === 429);

expect(limited?.body.code).toBe('AUTH_LOGIN_RATE_LIMITED');
expect(Number(limited?.headers['retry-after'])).toBeGreaterThan(0);
});

it('GET /api/auth/me echoes the token subject', async () => {
await seedEmployee(ctx.prisma, {
personalNo: '0001',
Expand Down
71 changes: 69 additions & 2 deletions apps/api-e2e/src/api/refresh.e2e.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { createTestApp, seedEmployee, type TestContext } from '../support/test-app';
import {
createTestApp,
seedEmployee,
type TestContext,
} from '../support/test-app';

describe('Auth — refresh tokens', () => {
let ctx: TestContext;
Expand Down Expand Up @@ -58,6 +62,66 @@ describe('Auth — refresh tokens', () => {
.expect(200);
});

it('detects refresh-token replay and revokes the whole session family', async () => {
await seedEmployee(ctx.prisma, {
personalNo: '0001',
firstName: 'Hannah',
lastName: 'Roth',
email: 'hannah@test.local',
});
const login = await ctx.http
.post('/api/auth/login')
.send({ email: 'hannah@test.local', password: 'test1234' })
.expect(200);
const rotated = await ctx.http
.post('/api/auth/refresh')
.send({ refreshToken: login.body.refreshToken })
.expect(200);

// Reusing the consumed token is treated as family compromise.
await ctx.http
.post('/api/auth/refresh')
.send({ refreshToken: login.body.refreshToken })
.expect(401);
await ctx.http
.post('/api/auth/refresh')
.send({ refreshToken: rotated.body.refreshToken })
.expect(401);
await ctx.http
.get('/api/auth/me')
.set('Authorization', `Bearer ${rotated.body.accessToken}`)
.expect(401);
});

it('server logout revokes refresh and access tokens in Solo mode', async () => {
const employee = await seedEmployee(ctx.prisma, {
personalNo: '0001',
firstName: 'Hannah',
lastName: 'Roth',
email: 'hannah@test.local',
});
await ctx.prisma.installationSettings.create({
data: { mode: 'Solo', ownerEmployeeId: employee.id },
});
const login = await ctx.http
.post('/api/auth/login')
.send({ email: 'hannah@test.local', password: 'test1234' })
.expect(200);

await ctx.http
.post('/api/auth/logout')
.send({ refreshToken: login.body.refreshToken })
.expect(204);
await ctx.http
.post('/api/auth/refresh')
.send({ refreshToken: login.body.refreshToken })
.expect(401);
await ctx.http
.get('/api/auth/me')
.set('Authorization', `Bearer ${login.body.accessToken}`)
.expect(401);
});

it('rejects garbage refresh token with 401', async () => {
await ctx.http
.post('/api/auth/refresh')
Expand Down Expand Up @@ -110,7 +174,10 @@ describe('Auth — refresh tokens', () => {
.post('/api/auth/login')
.send({ email: 'hannah@test.local', password: 'test1234' })
.expect(200);
await ctx.prisma.employee.update({ where: { id: e.id }, data: { isActive: false } });
await ctx.prisma.employee.update({
where: { id: e.id },
data: { isActive: false },
});
await ctx.http
.post('/api/auth/refresh')
.send({ refreshToken: login.body.refreshToken })
Expand Down
2 changes: 2 additions & 0 deletions apps/api-e2e/src/support/test-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export interface TestContext {

const RESET_SQL = `
TRUNCATE TABLE
"LoginAttemptState",
"AuthSession",
"InstallationSettings",
"InstallationEvent",
"SoloPolicy",
Expand Down
37 changes: 36 additions & 1 deletion apps/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,10 @@
},
"responses": {
"200": {
"description": ""
"description": "Authentication succeeded."
},
"429": {
"description": "The account or network source exceeded its login budget."
}
},
"tags": ["auth"]
Expand Down Expand Up @@ -718,6 +721,28 @@
"tags": ["auth"]
}
},
"/api/auth/logout": {
"post": {
"operationId": "AuthController_logout",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LogoutDto"
}
}
}
},
"responses": {
"204": {
"description": "The refresh session was revoked."
}
},
"tags": ["auth"]
}
},
"/api/auth/me/preferences": {
"patch": {
"operationId": "AuthController_updatePreferences",
Expand Down Expand Up @@ -6262,6 +6287,16 @@
},
"required": ["refreshToken"]
},
"LogoutDto": {
"type": "object",
"properties": {
"refreshToken": {
"type": "string",
"description": "The refresh token for the session family that should be revoked."
}
},
"required": ["refreshToken"]
},
"ThemePreference": {
"type": "string",
"enum": ["Light", "Dark", "System"],
Expand Down
51 changes: 48 additions & 3 deletions apps/api/src/app/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ import {
Body,
Controller,
Get,
HttpException,
HttpCode,
HttpStatus,
Patch,
Post,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import {
ApiBearerAuth,
ApiNoContentResponse,
ApiOkResponse,
ApiTags,
ApiTooManyRequestsResponse,
} from '@nestjs/swagger';
import type { Request, Response } from 'express';
import { CurrentUser } from './current-user.decorator';
import { AuthService } from './auth.service';
import {
LoginDto,
LogoutDto,
ChangePasswordDto,
UpdateOwnProfileDto,
RefreshDto,
Expand Down Expand Up @@ -53,8 +64,35 @@ export class AuthController {

@Post('login')
@HttpCode(HttpStatus.OK)
login(@Body() dto: LoginDto): Promise<LoginResponse> {
return this.auth.login(dto.email, dto.password);
@ApiOkResponse({ description: 'Authentication succeeded.' })
@ApiTooManyRequestsResponse({
description: 'The account or network source exceeded its login budget.',
})
async login(
@Body() dto: LoginDto,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
): Promise<LoginResponse> {
try {
// Do not trust a caller-provided forwarding header. Express `ip` is the
// peer address unless the deployment explicitly configures trusted proxies.
const source =
request.ip ?? request.socket.remoteAddress ?? 'unknown-peer';
return await this.auth.login(dto.email, dto.password, source);
} catch (error) {
if (error instanceof HttpException && error.getStatus() === 429) {
const body = error.getResponse();
const retryAfterSeconds =
typeof body === 'object' &&
body !== null &&
'retryAfterSeconds' in body &&
typeof body.retryAfterSeconds === 'number'
? body.retryAfterSeconds
: 60;
response.setHeader('Retry-After', String(retryAfterSeconds));
}
throw error;
}
}

@Post('refresh')
Expand All @@ -63,6 +101,13 @@ export class AuthController {
return this.auth.refresh(dto.refreshToken);
}

@Post('logout')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiNoContentResponse({ description: 'The refresh session was revoked.' })
logout(@Body() dto: LogoutDto): Promise<void> {
return this.auth.logout(dto.refreshToken);
}

@Get('me')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/app/auth/auth.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export class RefreshDto {
refreshToken!: string;
}

export class LogoutDto {
@ApiProperty({
description:
'The refresh token for the session family that should be revoked.',
})
@IsString()
@MinLength(1)
refreshToken!: string;
}

export class UpdatePreferencesDto {
@ApiProperty({
enum: ThemePreference,
Expand Down
Loading