mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
Turn protection from opt-in into default-deny
Nothing in src/nest/** was an APP_GUARD. Every protected route said so itself, 62 times, which means a forgotten @UseGuards was a silent bypass rather than an error. GlobalAuthGuard inverts that: a route is authenticated unless it carries @Public() or @OptionalAuth(), or declares its own guard chain. Reading the declared chain is what makes this behaviour-neutral. Nest runs global guards before route guards, so without that check the global guard would 401 an anonymous request to an addon-gated controller before its AddonGuard could answer 404 - inverting an order four e2e suites pin, and leaking which addons are installed. A controller that declared a chain keeps deciding for itself. It is a new class rather than JwtAuthGuard gaining a Reflector: that guard is constructed positionally in its own test with a context stub that has no getHandler, and the two want opposite behaviour anyway. @Public() takes a required reason, and the reasons are the diff worth reading: the invite token IS the credential, help assets are loaded by <img> which cannot send one, logout has to work with an expired session or nobody can sign out. The real deliverable is the inventory. validateRouteGuards runs in buildApp next to the body-contract gate and refuses to start when a route answers anonymously without being on a reviewed list of 25 - or when a listed one no longer does. An allow list nobody prunes stops being a list. Default-deny found two controllers on its own: SharedController and OidcController both sit in a file next to a guarded controller, so a file-level search for unguarded ones missed them. 37 tests went red and named them. That is the mechanism working before the change shipped, not after.
This commit is contained in:
@@ -8,6 +8,7 @@ import { getClientIp } from '../audit/client-ip';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { willDropSecureCookie } from '../common/cookie';
|
||||
import type { User } from '../../types';
|
||||
import { Public } from './public.decorator';
|
||||
|
||||
const WINDOW = 15 * 60 * 1000;
|
||||
const LOGIN_MIN_LATENCY_MS = 350;
|
||||
@@ -40,6 +41,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('demo-login')
|
||||
@Public('issues a session for the demo account; there is nothing to authenticate yet')
|
||||
@HttpCode(200)
|
||||
demoLogin(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
const result = this.auth.demoLogin();
|
||||
@@ -51,6 +53,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Get('invite/:token')
|
||||
@Public('the invite token IS the credential')
|
||||
invite(@Param('token') token: string, @Req() req: Request) {
|
||||
this.limit('login', req, 10);
|
||||
const result = this.auth.validateInviteToken(token);
|
||||
@@ -61,6 +64,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('register')
|
||||
@Public('creating the account that would carry the session')
|
||||
@HttpCode(201)
|
||||
register(@Body() body: RegisterDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.limit('login', req, 10);
|
||||
@@ -74,6 +78,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
@Public('the login itself')
|
||||
@HttpCode(200)
|
||||
async login(@Body() body: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.limit('login', req, 10);
|
||||
@@ -101,6 +106,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('forgot-password')
|
||||
@Public('reached by somebody who cannot log in')
|
||||
@HttpCode(200)
|
||||
async forgotPassword(@Body() body: ForgotPasswordDto, @Req() req: Request) {
|
||||
this.limit('forgot', req, 3);
|
||||
@@ -128,6 +134,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('reset-password')
|
||||
@Public('the reset token IS the credential')
|
||||
@HttpCode(200)
|
||||
resetPassword(@Body() body: ResetPasswordDto, @Req() req: Request) {
|
||||
// Per-IP brute-force guard, parity with the legacy resetLimiter (5 / 15 min on
|
||||
@@ -147,6 +154,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('mfa/verify-login')
|
||||
@Public('second factor of a login that has no session yet')
|
||||
@HttpCode(200)
|
||||
verifyMfaLogin(@Body() body: MfaVerifyLoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.limit('mfa', req, 5);
|
||||
@@ -160,6 +168,7 @@ export class AuthPublicController {
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@Public('clearing a cookie must work even with an expired token, or the client cannot sign out')
|
||||
@HttpCode(200)
|
||||
logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.auth.clearAuthCookie(res, req);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import type { Request } from 'express';
|
||||
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
|
||||
import { IS_PUBLIC, OPTIONAL_AUTH } from './public.decorator';
|
||||
|
||||
/**
|
||||
* Default-deny. Registered as an APP_GUARD, so a route is authenticated unless
|
||||
* it says otherwise — the inverse of what TREK had, where protection was opt-in
|
||||
* through 62 separate `@UseGuards(JwtAuthGuard)` and a forgotten one was a
|
||||
* silent bypass rather than an error.
|
||||
*
|
||||
* It is a new class rather than JwtAuthGuard gaining a Reflector, for two
|
||||
* reasons. JwtAuthGuard is constructed positionally in its own unit test with an
|
||||
* ExecutionContext stub that has no getHandler, so a Reflector lookup there
|
||||
* would break it; and the two want different behaviour anyway — this one stands
|
||||
* down, that one refuses.
|
||||
*
|
||||
* The third check is what keeps this change behaviour-neutral: a controller
|
||||
* that DECLARES its own guard chain keeps it, untouched. Nest runs global guards
|
||||
* before route guards, so without this the global guard would 401 an anonymous
|
||||
* request to an addon-gated controller before its AddonGuard could answer 404 —
|
||||
* inverting an order that four e2e suites pin, and leaking which addons are
|
||||
* installed. Reading the declared chain and standing down means every existing
|
||||
* @UseGuards keeps deciding for itself, and this guard only covers what nobody
|
||||
* claimed.
|
||||
*/
|
||||
@Injectable()
|
||||
export class GlobalAuthGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const handler = context.getHandler();
|
||||
const controller = context.getClass();
|
||||
|
||||
if (this.reflector.getAllAndOverride(IS_PUBLIC, [handler, controller])) return true;
|
||||
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
|
||||
if (this.reflector.getAllAndOverride(OPTIONAL_AUTH, [handler, controller])) {
|
||||
const token = extractToken(req);
|
||||
(req as { user: unknown }).user = (token ? verifyJwtAndLoadUser(token) : null) || null;
|
||||
return true;
|
||||
}
|
||||
|
||||
// A declared chain decides for itself, in the order it declared.
|
||||
const declared = [
|
||||
...(this.reflector.get<unknown[]>(GUARDS_METADATA, handler) ?? []),
|
||||
...(this.reflector.get<unknown[]>(GUARDS_METADATA, controller) ?? []),
|
||||
];
|
||||
if (declared.length > 0) return true;
|
||||
|
||||
const token = extractToken(req);
|
||||
if (!token) {
|
||||
throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
const user = verifyJwtAndLoadUser(token);
|
||||
if (!user) {
|
||||
throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
req.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
/** Metadata key `@Public()` writes. */
|
||||
export const IS_PUBLIC = 'trek:public';
|
||||
/** Metadata key `@OptionalAuth()` writes. */
|
||||
export const OPTIONAL_AUTH = 'trek:optional-auth';
|
||||
|
||||
/**
|
||||
* Marks a route as reachable without a session, under the global auth guard.
|
||||
*
|
||||
* The reason is required, and that is the point: with default-deny, the only
|
||||
* routes a reader has to think about are the ones carrying this decorator, so
|
||||
* each one should say why it is exempt. Same discipline as
|
||||
* common/body-contract-allow-list.ts — a list nobody can add to without
|
||||
* explaining themselves stays short.
|
||||
*
|
||||
* `@Public()` does NOT populate req.user. A route that wants the user when a
|
||||
* token happens to be present, and no 401 when it is not, wants
|
||||
* `@OptionalAuth()` instead.
|
||||
*/
|
||||
export const Public = (reason: string) => SetMetadata(IS_PUBLIC, { reason });
|
||||
|
||||
/**
|
||||
* Marks a route whose response varies by auth state but which never demands it:
|
||||
* the global guard loads the user when a valid token is present and leaves
|
||||
* `req.user` null otherwise, exactly like the legacy `optionalAuth` middleware.
|
||||
*
|
||||
* Reach for `@Public()` unless the handler actually reads `req.user`. Populating
|
||||
* it has a side effect beyond the handler: the IdempotencyInterceptor steps
|
||||
* aside when there is no user, so making a route optional-auth newly enrols its
|
||||
* mutations in idempotency replay.
|
||||
*/
|
||||
export const OptionalAuth = (reason: string) => SetMetadata(OPTIONAL_AUTH, { reason });
|
||||
Reference in New Issue
Block a user