From fb87202683b53816c23630ce72100436735d13cb Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 1 Aug 2026 17:40:16 +0200 Subject: [PATCH] feat(server): validate auth request bodies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DTO ratchet for the auth domain (collections sibling-commit precedent): - shared/src/auth/auth.schema.ts gains the six missing request schemas — mapsKey (nullable: the client clears with an explicit null), apiKeys and settings (per-key partials, nullable key values), appSettings (open record — the server's ADMIN_SETTINGS_KEYS allow-list and its bespoke lockout/self-MFA 400s stay service-owned), mfaDisable, resourceToken (the 'Invalid purpose' 400 stays service-owned) — plus spec cases. - New nest/auth/auth.dto.ts createZodDto wrappers; all 14 raw @Body() params typed (9 AuthController + 5 AuthPublicController), validated by the global ZodValidationPipe. - All 14 auth entries removed from body-contract-allow-list.ts (PasskeyController's 4 stay until passkeyService migrates). - auth.e2e mirrors the production pipe and pins the { error: 'field: ...' } envelope on a shapeless login body; auth.controller.ts drops its duplicated avatarDir const in favour of the auth.helpers export. --- .../src/nest/auth/auth-public.controller.ts | 11 ++--- server/src/nest/auth/auth.controller.ts | 31 ++++++++----- server/src/nest/auth/auth.dto.ts | 40 +++++++++++++++++ .../nest/common/body-contract-allow-list.ts | 14 ------ shared/src/auth/auth.schema.spec.ts | 41 +++++++++++++++++ shared/src/auth/auth.schema.ts | 44 +++++++++++++++++++ 6 files changed, 152 insertions(+), 29 deletions(-) create mode 100644 server/src/nest/auth/auth.dto.ts diff --git a/server/src/nest/auth/auth-public.controller.ts b/server/src/nest/auth/auth-public.controller.ts index 7b68238dd..837cf532e 100644 --- a/server/src/nest/auth/auth-public.controller.ts +++ b/server/src/nest/auth/auth-public.controller.ts @@ -1,6 +1,7 @@ import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; import type { Request, Response } from 'express'; import { AuthService } from './auth.service'; +import { RegisterDto, LoginDto, ForgotPasswordDto, ResetPasswordDto, MfaVerifyLoginDto } from './auth.dto'; import { RateLimitService } from './rate-limit.service'; import { OptionalJwtGuard } from './optional-jwt.guard'; import { getClientIp } from '../audit/client-ip'; @@ -61,7 +62,7 @@ export class AuthPublicController { @Post('register') @HttpCode(201) - register(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + register(@Body() body: RegisterDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) { this.limit('login', req, 10); const result = this.auth.registerUser(body); if (result.error) { @@ -74,7 +75,7 @@ export class AuthPublicController { @Post('login') @HttpCode(200) - async login(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + async login(@Body() body: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) { this.limit('login', req, 10); const started = Date.now(); const result = this.auth.loginUser(body); @@ -101,7 +102,7 @@ export class AuthPublicController { @Post('forgot-password') @HttpCode(200) - async forgotPassword(@Body() body: { email?: unknown }, @Req() req: Request) { + async forgotPassword(@Body() body: ForgotPasswordDto, @Req() req: Request) { this.limit('forgot', req, 3); const started = Date.now(); const rawEmail = typeof body?.email === 'string' ? body.email : ''; @@ -128,7 +129,7 @@ export class AuthPublicController { @Post('reset-password') @HttpCode(200) - resetPassword(@Body() body: unknown, @Req() req: Request) { + resetPassword(@Body() body: ResetPasswordDto, @Req() req: Request) { // Per-IP brute-force guard, parity with the legacy resetLimiter (5 / 15 min on // a dedicated bucket) — without it reset tokens could be guessed unthrottled. this.limit('reset', req, 5); @@ -147,7 +148,7 @@ export class AuthPublicController { @Post('mfa/verify-login') @HttpCode(200) - verifyMfaLogin(@Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + verifyMfaLogin(@Body() body: MfaVerifyLoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) { this.limit('mfa', req, 5); const result = this.auth.verifyMfaLogin(body); if (result.error) { diff --git a/server/src/nest/auth/auth.controller.ts b/server/src/nest/auth/auth.controller.ts index edba212e1..6097fbae2 100644 --- a/server/src/nest/auth/auth.controller.ts +++ b/server/src/nest/auth/auth.controller.ts @@ -22,6 +22,18 @@ import fs from 'fs'; import { v4 as uuid } from 'uuid'; import { readEnv } from '../../app-config'; import { AuthService } from './auth.service'; +import { avatarDir } from './auth.helpers'; +import { + ChangePasswordDto, + MapsKeyUpdateDto, + ApiKeysUpdateDto, + SettingsUpdateDto, + AppSettingsUpdateDto, + MfaEnableDto, + MfaDisableDto, + McpTokenCreateDto, + ResourceTokenDto, +} from './auth.dto'; import { RateLimitService } from './rate-limit.service'; import { JwtAuthGuard } from './jwt-auth.guard'; import { CurrentUser } from './current-user.decorator'; @@ -31,7 +43,6 @@ import { isDemoEmail } from '../../services/demo'; import type { User } from '../../types'; const WINDOW = 15 * 60 * 1000; -const avatarDir = path.join(__dirname, '../../../uploads/avatars'); const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; const AVATAR_UPLOAD = { storage: diskStorage({ @@ -79,7 +90,7 @@ export class AuthController { } @Put('me/password') - changePassword(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request, @Res({ passthrough: true }) res: Response) { + changePassword(@CurrentUser() user: User, @Body() body: ChangePasswordDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) { this.limit('login', req, 5); const result = this.auth.changePassword(user.id, user.email, body); if (result.error) { @@ -103,17 +114,17 @@ export class AuthController { } @Put('me/maps-key') - mapsKey(@CurrentUser() user: User, @Body() body: { maps_api_key?: unknown }) { + mapsKey(@CurrentUser() user: User, @Body() body: MapsKeyUpdateDto) { return this.auth.updateMapsKey(user.id, body.maps_api_key); } @Put('me/api-keys') - apiKeys(@CurrentUser() user: User, @Body() body: unknown) { + apiKeys(@CurrentUser() user: User, @Body() body: ApiKeysUpdateDto) { return this.auth.updateApiKeys(user.id, body); } @Put('me/settings') - updateSettings(@CurrentUser() user: User, @Body() body: unknown) { + updateSettings(@CurrentUser() user: User, @Body() body: SettingsUpdateDto) { const result = this.auth.updateSettings(user.id, body); if (result.error) { throw new HttpException({ error: result.error }, result.status!); @@ -172,7 +183,7 @@ export class AuthController { } @Put('app-settings') - updateAppSettings(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + updateAppSettings(@CurrentUser() user: User, @Body() body: AppSettingsUpdateDto, @Req() req: Request) { const result = this.auth.updateAppSettings(user.id, body); if (result.error) { throw new HttpException({ error: result.error }, result.status!); @@ -204,7 +215,7 @@ export class AuthController { @Post('mfa/enable') @HttpCode(200) - mfaEnable(@CurrentUser() user: User, @Body() body: { code?: unknown }, @Req() req: Request) { + mfaEnable(@CurrentUser() user: User, @Body() body: MfaEnableDto, @Req() req: Request) { this.limit('mfa', req, 5); const result = this.auth.enableMfa(user.id, body.code); if (result.error) { @@ -216,7 +227,7 @@ export class AuthController { @Post('mfa/disable') @HttpCode(200) - mfaDisable(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) { + mfaDisable(@CurrentUser() user: User, @Body() body: MfaDisableDto, @Req() req: Request) { this.limit('login', req, 5); const result = this.auth.disableMfa(user.id, user.email, body); if (result.error) { @@ -233,7 +244,7 @@ export class AuthController { @Post('mcp-tokens') @HttpCode(201) - createMcpToken(@CurrentUser() user: User, @Body() body: { name?: unknown }, @Req() req: Request) { + createMcpToken(@CurrentUser() user: User, @Body() body: McpTokenCreateDto, @Req() req: Request) { this.limit('login', req, 5); const result = this.auth.createMcpToken(user.id, body.name); if (result.error) { @@ -263,7 +274,7 @@ export class AuthController { @Post('resource-token') @HttpCode(200) - resourceToken(@CurrentUser() user: User, @Body() body: { purpose?: unknown }) { + resourceToken(@CurrentUser() user: User, @Body() body: ResourceTokenDto) { const token = this.auth.createResourceToken(user.id, body.purpose); if (!token) { throw new HttpException({ error: 'Service unavailable' }, 503); diff --git a/server/src/nest/auth/auth.dto.ts b/server/src/nest/auth/auth.dto.ts new file mode 100644 index 000000000..7a6be4ea4 --- /dev/null +++ b/server/src/nest/auth/auth.dto.ts @@ -0,0 +1,40 @@ +import { createZodDto } from 'nestjs-zod'; +import { + registerRequestSchema, + loginRequestSchema, + forgotPasswordRequestSchema, + resetPasswordRequestSchema, + changePasswordRequestSchema, + mfaVerifyLoginRequestSchema, + mfaEnableRequestSchema, + mfaDisableRequestSchema, + mcpTokenCreateRequestSchema, + mapsKeyUpdateRequestSchema, + apiKeysUpdateRequestSchema, + settingsUpdateRequestSchema, + appSettingsUpdateRequestSchema, + resourceTokenRequestSchema, +} from '@trek/shared'; + +/** + * Server-side createZodDto wrappers over the @trek/shared auth contracts. The + * global ZodValidationPipe (APP_PIPE in app.module.ts) validates any @Body() + * parameter typed with one of these classes by metatype — the Zod schemas in + * shared/ remain the single source of truth for the wire contract. The + * credential/MFA rules (and their bespoke 4xx strings) stay in AuthService; + * these pin only the well-defined request shapes. + */ +export class RegisterDto extends createZodDto(registerRequestSchema) {} +export class LoginDto extends createZodDto(loginRequestSchema) {} +export class ForgotPasswordDto extends createZodDto(forgotPasswordRequestSchema) {} +export class ResetPasswordDto extends createZodDto(resetPasswordRequestSchema) {} +export class ChangePasswordDto extends createZodDto(changePasswordRequestSchema) {} +export class MfaVerifyLoginDto extends createZodDto(mfaVerifyLoginRequestSchema) {} +export class MfaEnableDto extends createZodDto(mfaEnableRequestSchema) {} +export class MfaDisableDto extends createZodDto(mfaDisableRequestSchema) {} +export class McpTokenCreateDto extends createZodDto(mcpTokenCreateRequestSchema) {} +export class MapsKeyUpdateDto extends createZodDto(mapsKeyUpdateRequestSchema) {} +export class ApiKeysUpdateDto extends createZodDto(apiKeysUpdateRequestSchema) {} +export class SettingsUpdateDto extends createZodDto(settingsUpdateRequestSchema) {} +export class AppSettingsUpdateDto extends createZodDto(appSettingsUpdateRequestSchema) {} +export class ResourceTokenDto extends createZodDto(resourceTokenRequestSchema) {} diff --git a/server/src/nest/common/body-contract-allow-list.ts b/server/src/nest/common/body-contract-allow-list.ts index 9fca3f599..a9af41be0 100644 --- a/server/src/nest/common/body-contract-allow-list.ts +++ b/server/src/nest/common/body-contract-allow-list.ts @@ -28,20 +28,6 @@ export const BODY_CONTRACT_ALLOW_LIST: string[] = [ 'AdminController.updateTemplateCategory', 'AdminController.updateTemplateItem', 'AdminController.updateUser', - 'AuthController.apiKeys', - 'AuthController.changePassword', - 'AuthController.createMcpToken', - 'AuthController.mapsKey', - 'AuthController.mfaDisable', - 'AuthController.mfaEnable', - 'AuthController.resourceToken', - 'AuthController.updateAppSettings', - 'AuthController.updateSettings', - 'AuthPublicController.forgotPassword', - 'AuthPublicController.login', - 'AuthPublicController.register', - 'AuthPublicController.resetPassword', - 'AuthPublicController.verifyMfaLogin', 'BackupController.updateAutoSettings', 'BookingImportController.confirm', 'BookingImportController.preview', diff --git a/shared/src/auth/auth.schema.spec.ts b/shared/src/auth/auth.schema.spec.ts index a7ca2d5ab..39840eeb4 100644 --- a/shared/src/auth/auth.schema.spec.ts +++ b/shared/src/auth/auth.schema.spec.ts @@ -6,7 +6,13 @@ import { changePasswordRequestSchema, mfaVerifyLoginRequestSchema, mfaEnableRequestSchema, + mfaDisableRequestSchema, mcpTokenCreateRequestSchema, + mapsKeyUpdateRequestSchema, + apiKeysUpdateRequestSchema, + settingsUpdateRequestSchema, + appSettingsUpdateRequestSchema, + resourceTokenRequestSchema, } from './auth.schema'; import { describe, it, expect } from 'vitest'; @@ -59,7 +65,42 @@ describe('mfa + mcp-token schemas', () => { expect(mfaVerifyLoginRequestSchema.safeParse({ mfa_token: 't', code: '123456' }).success).toBe(true); expect(mfaVerifyLoginRequestSchema.safeParse({ mfa_token: 't' }).success).toBe(false); expect(mfaEnableRequestSchema.safeParse({ code: '123456' }).success).toBe(true); + expect(mfaDisableRequestSchema.safeParse({ password: 'pw', code: '123456' }).success).toBe(true); + expect(mfaDisableRequestSchema.safeParse({ code: '123456' }).success).toBe(false); expect(mcpTokenCreateRequestSchema.safeParse({ name: 'CLI' }).success).toBe(true); expect(mcpTokenCreateRequestSchema.safeParse({}).success).toBe(true); }); }); + +describe('api-key / settings schemas', () => { + it('mapsKey accepts a string, an explicit null (clear) and omission', () => { + expect(mapsKeyUpdateRequestSchema.safeParse({ maps_api_key: 'k' }).success).toBe(true); + expect(mapsKeyUpdateRequestSchema.safeParse({ maps_api_key: null }).success).toBe(true); + expect(mapsKeyUpdateRequestSchema.safeParse({}).success).toBe(true); + expect(mapsKeyUpdateRequestSchema.safeParse({ maps_api_key: 7 }).success).toBe(false); + }); + + it('apiKeys is a per-key partial with nullable values', () => { + expect(apiKeysUpdateRequestSchema.safeParse({ unsplash_api_key: null }).success).toBe(true); + expect(apiKeysUpdateRequestSchema.safeParse({ maps_api_key: 'k', openweather_api_key: 'w' }).success).toBe(true); + expect(apiKeysUpdateRequestSchema.safeParse({}).success).toBe(true); + }); + + it('settings accepts profile + key fields, all optional', () => { + expect(settingsUpdateRequestSchema.safeParse({ username: 'alice' }).success).toBe(true); + expect(settingsUpdateRequestSchema.safeParse({ email: 'a@b.c', maps_api_key: null }).success).toBe(true); + expect(settingsUpdateRequestSchema.safeParse({ username: 42 }).success).toBe(false); + }); + + it('appSettings is an open string-keyed map (the server owns the key allow-list)', () => { + expect(appSettingsUpdateRequestSchema.safeParse({ require_mfa: true, smtp_host: 'mail' }).success).toBe(true); + expect(appSettingsUpdateRequestSchema.safeParse({}).success).toBe(true); + expect(appSettingsUpdateRequestSchema.safeParse('nope').success).toBe(false); + }); + + it('resourceToken keeps purpose an optional string (the 400 is a service rule)', () => { + expect(resourceTokenRequestSchema.safeParse({ purpose: 'download' }).success).toBe(true); + expect(resourceTokenRequestSchema.safeParse({}).success).toBe(true); + expect(resourceTokenRequestSchema.safeParse({ purpose: 5 }).success).toBe(false); + }); +}); diff --git a/shared/src/auth/auth.schema.ts b/shared/src/auth/auth.schema.ts index f85c8c1e7..6a8779cb9 100644 --- a/shared/src/auth/auth.schema.ts +++ b/shared/src/auth/auth.schema.ts @@ -64,3 +64,47 @@ export const mcpTokenCreateRequestSchema = z.object({ name: z.string().optional(), }); export type McpTokenCreateRequest = z.infer; + +// The client sends an explicit `null` to clear the stored key; optional keeps +// the legacy accept-anything omission path (omitting also clears — service rule). +export const mapsKeyUpdateRequestSchema = z.object({ + maps_api_key: z.string().nullable().optional(), +}); +export type MapsKeyUpdateRequest = z.infer; + +// Per-key partial update: an absent key keeps the stored value, `null` clears it. +export const apiKeysUpdateRequestSchema = z.object({ + maps_api_key: z.string().nullable().optional(), + openweather_api_key: z.string().nullable().optional(), + unsplash_api_key: z.string().nullable().optional(), +}); +export type ApiKeysUpdateRequest = z.infer; + +export const settingsUpdateRequestSchema = z.object({ + maps_api_key: z.string().nullable().optional(), + openweather_api_key: z.string().nullable().optional(), + unsplash_api_key: z.string().nullable().optional(), + username: z.string().optional(), + email: z.string().optional(), +}); +export type SettingsUpdateRequest = z.infer; + +// Deliberately an open map: the accepted keys are the server's ADMIN_SETTINGS_KEYS +// allow-list (unknown keys are ignored there), and values arrive as strings or +// booleans (`require_mfa` toggles) — the service owns the per-key coercion and +// the lockout/self-MFA guards with their bespoke 400 strings. +export const appSettingsUpdateRequestSchema = z.record(z.string(), z.unknown()); +export type AppSettingsUpdateRequest = z.infer; + +export const mfaDisableRequestSchema = z.object({ + password: z.string(), + code: z.string(), +}); +export type MfaDisableRequest = z.infer; + +// `purpose` must be the literal 'download' today, but the 400 'Invalid purpose' +// answer is a service rule (kept bespoke), so the wire type stays a plain string. +export const resourceTokenRequestSchema = z.object({ + purpose: z.string().optional(), +}); +export type ResourceTokenRequest = z.infer;