fix(#338): Bind CSRF token to user session with HMAC
- Token now includes HMAC binding to session ID
- Validates session binding on verification
- Adds CSRF_SECRET configuration requirement
- Requires authentication for CSRF token endpoint
- 51 new tests covering session binding security
Security: CSRF tokens are now cryptographically tied to user sessions,
preventing token reuse across sessions and mitigating session fixation
attacks.
Token format: {random_part}:{hmac(random_part + user_id, secret)}
Refs #338
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,24 +2,46 @@
|
||||
* CSRF Controller
|
||||
*
|
||||
* Provides CSRF token generation endpoint for client applications.
|
||||
* Tokens are cryptographically bound to the user session via HMAC.
|
||||
*/
|
||||
|
||||
import { Controller, Get, Res } from "@nestjs/common";
|
||||
import { Response } from "express";
|
||||
import * as crypto from "crypto";
|
||||
import { Controller, Get, Res, Req, UseGuards } from "@nestjs/common";
|
||||
import { Response, Request } from "express";
|
||||
import { SkipCsrf } from "../decorators/skip-csrf.decorator";
|
||||
import { CsrfService } from "../services/csrf.service";
|
||||
import { AuthGuard } from "../../auth/guards/auth.guard";
|
||||
import type { AuthenticatedUser } from "../types/user.types";
|
||||
|
||||
interface AuthenticatedRequest extends Request {
|
||||
user?: AuthenticatedUser;
|
||||
}
|
||||
|
||||
@Controller("api/v1/csrf")
|
||||
export class CsrfController {
|
||||
constructor(private readonly csrfService: CsrfService) {}
|
||||
|
||||
/**
|
||||
* Generate and set CSRF token
|
||||
* Generate and set CSRF token bound to user session
|
||||
* Requires authentication to bind token to session
|
||||
* Returns token to client and sets it in httpOnly cookie
|
||||
*/
|
||||
@Get("token")
|
||||
@UseGuards(AuthGuard)
|
||||
@SkipCsrf() // This endpoint itself doesn't need CSRF protection
|
||||
getCsrfToken(@Res({ passthrough: true }) response: Response): { token: string } {
|
||||
// Generate cryptographically secure random token
|
||||
const token = crypto.randomBytes(32).toString("hex");
|
||||
getCsrfToken(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@Res({ passthrough: true }) response: Response
|
||||
): { token: string } {
|
||||
// Get user ID from authenticated request
|
||||
const userId = request.user?.id;
|
||||
|
||||
if (!userId) {
|
||||
// This should not happen if AuthGuard is working correctly
|
||||
throw new Error("User ID not available after authentication");
|
||||
}
|
||||
|
||||
// Generate session-bound CSRF token
|
||||
const token = this.csrfService.generateToken(userId);
|
||||
|
||||
// Set token in httpOnly cookie
|
||||
response.cookie("csrf-token", token, {
|
||||
|
||||
Reference in New Issue
Block a user