fix(#337): Propagate database errors from guards instead of masking as access denied

SEC-API-2: WorkspaceGuard now propagates database errors as 500s instead of
returning "access denied". Only Prisma P2025 (record not found) is treated
as "user not a member".

SEC-API-3: PermissionGuard now propagates database errors as 500s instead of
returning null role (which caused permission denied). Only Prisma P2025 is
treated as "not a member".

This prevents connection timeouts, pool exhaustion, and other infrastructure
errors from being misreported to users as authorization failures.

Refs #337

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Jason Woltje
2026-02-05 15:35:11 -06:00
parent 6bb9846cde
commit e237c40482
4 changed files with 152 additions and 10 deletions

View File

@@ -3,8 +3,10 @@ import {
CanActivate,
ExecutionContext,
ForbiddenException,
InternalServerErrorException,
Logger,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { Reflector } from "@nestjs/core";
import { PrismaService } from "../../prisma/prisma.service";
import { PERMISSION_KEY, Permission } from "../decorators/permissions.decorator";
@@ -99,6 +101,10 @@ export class PermissionGuard implements CanActivate {
/**
* Fetches the user's role in a workspace
*
* SEC-API-3 FIX: Database errors are no longer swallowed as null role.
* Connection timeouts, pool exhaustion, and other infrastructure errors
* are propagated as 500 errors to avoid masking operational issues.
*/
private async getUserWorkspaceRole(
userId: string,
@@ -119,11 +125,23 @@ export class PermissionGuard implements CanActivate {
return member?.role ?? null;
} catch (error) {
// Only handle Prisma "not found" errors (P2025) as expected cases
// All other database errors (connection, timeout, pool) should propagate
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2025" // Record not found
) {
return null;
}
// Log the error before propagating
this.logger.error(
`Failed to fetch user role: ${error instanceof Error ? error.message : "Unknown error"}`,
`Database error during permission check: ${error instanceof Error ? error.message : "Unknown error"}`,
error instanceof Error ? error.stack : undefined
);
return null;
// Propagate infrastructure errors as 500s, not permission denied
throw new InternalServerErrorException("Failed to verify permissions");
}
}