Files
liqa/server/src/interceptors/logging.interceptor.ts
T
agent 72e127888c
CI / changes (pull_request) Canceled after 0s
CI / server (pull_request) Canceled after 0s
CI / client (pull_request) Canceled after 0s
CI / image (pull_request) Canceled after 0s
fix(auth): redact passwords on normalized login paths
- Normalize login paths before applying request-body redaction.
- Cover trailing-slash paths and assert the password never reaches logs.
2026-11-04 15:59:49 -05:00

60 lines
1.8 KiB
TypeScript

import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from "@nestjs/common";
import type { Request, Response } from "express";
import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger";
export function redactAuthRequestBody(path: string, body: unknown): unknown {
const normalizedPath = path.toLowerCase().replace(/\/+$/, "");
if (
(normalizedPath !== "/auth/login" &&
normalizedPath !== "/api/v1/auth/login") ||
!body ||
typeof body !== "object" ||
Array.isArray(body)
) {
return body;
}
const requestBody = body as Record<string, unknown>;
return {
...requestBody,
password: requestBody.password ? "[REDACTED]" : requestBody.password,
};
}
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
private readonly logger = new TraceLogger(LoggingInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const http = context.switchToHttp();
const req = http.getRequest<Request>();
const res = http.getResponse<Response>();
const { method, url, body } = req;
const start = Date.now();
const safeBody = redactAuthRequestBody(req.path, body);
const bodyStr =
safeBody && Object.keys(safeBody).length
? ` ${JSON.stringify(safeBody)}`
: "";
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
return next.handle().pipe(
tap((responseBody) => {
const ms = Date.now() - start;
const len =
responseBody != null ? JSON.stringify(responseBody).length : 0;
const lenStr = len > 0 ? ` [${len}b]` : "";
this.logger.debug(
`← ${method} ${url} ${res.statusCode} (${ms}ms)${lenStr}`,
);
}),
);
}
}