mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
5e797463fa
PERMISSION_ACTIONS, PermissionLevel, PermissionKey and evaluatePermission() move to shared/src/permissions. PermissionsService decides through evaluatePermission and re-exports the catalog for its importers, and @RequirePermission takes a PermissionKey, so a misspelt action fails to compile. Levels, defaults and every verdict stay as they were.
95 lines
4.6 KiB
TypeScript
95 lines
4.6 KiB
TypeScript
import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common';
|
|
import { Reflector } from '@nestjs/core';
|
|
import { EntityManager } from '@mikro-orm/core';
|
|
import type { Request } from 'express';
|
|
import type { PermissionKey } from '@trek/shared';
|
|
import { Trips } from '../../db/entities/Trips.entity';
|
|
import type { TripAccess } from '../../db/repositories/Trips.repository';
|
|
import { PermissionsService } from './permissions.service';
|
|
import type { User } from '../../types';
|
|
|
|
/** Where the guard parks the resolved trip row for `@Trip()` to pick up. */
|
|
export const TRIP_REQUEST_KEY = 'trekTrip';
|
|
|
|
/** The metadata key `@RequirePermission()` writes and the guard reads. */
|
|
export const TRIP_PERMISSION_KEY = 'trekTripPermission';
|
|
|
|
/**
|
|
* Requires a permission on the trip the route is scoped to, on top of access.
|
|
*
|
|
* The action is a key of the shared catalog (`PermissionKey` from `@trek/shared`),
|
|
* the same one the domain services pass to `PermissionsService.checkPermission`
|
|
* ('day_edit', 'budget_edit', …), so a route and its MCP counterpart cannot drift
|
|
* apart on which right they demand, and a misspelt key fails to compile.
|
|
*/
|
|
export const RequirePermission = (action: PermissionKey) => SetMetadata(TRIP_PERMISSION_KEY, action);
|
|
|
|
type TripRequest = Request & { user?: User; [TRIP_REQUEST_KEY]?: TripAccess };
|
|
|
|
/**
|
|
* Resolves `:tripId` once per request, refuses what the user cannot reach, and hands
|
|
* the trip row to the handler.
|
|
*
|
|
* Every trip-scoped controller used to carry its own `requireTrip` helper doing the
|
|
* same three lines, and a `requireEdit` next to it. That is 18 copies of a security
|
|
* check, each of which had to remember that no access is a 404 "Trip not found" and
|
|
* never a 403 — the distinction that keeps a stranger from learning which trip ids
|
|
* exist. One of them getting it wrong would have looked like nothing.
|
|
*
|
|
* The status codes and bodies here are byte-identical to those copies, because the
|
|
* e2e suites assert them and the client branches on them.
|
|
*
|
|
* It deliberately does NOT replace the `verifyTripAccess`/`canEdit` methods on the
|
|
* domain services. Of their callers, the large majority are `*.mcp.ts` tools, which
|
|
* never pass through an HTTP guard; those methods stay exactly where they are.
|
|
*
|
|
* Injects `EntityManager`, not `DatabaseService`/`@InjectRepository(Trips)`
|
|
* (Plan 3c Task 0b, the `JwtAuthGuard` precedent): this guard is applied via
|
|
* `@UseGuards(…, TripAccessGuard)` on 146 handlers across 22 controller
|
|
* classes, and Nest resolves a class-referenced guard's constructor
|
|
* dependencies from the HOST CONTROLLER'S OWN module graph —
|
|
* `@InjectRepository(Trips)` would need `MikroOrmModule.forFeature([Trips])`
|
|
* added to every one of those modules (D5's blast radius). `EntityManager`
|
|
* comes from `MikroOrmModule.forRoot`'s core module, which IS `@Global()`, so
|
|
* no module needs new wiring. `this.em.getRepository(Trips)` inside
|
|
* `canActivate` is the same per-request resolution `JwtAuthGuard` uses for
|
|
* `Users`.
|
|
*/
|
|
@Injectable()
|
|
export class TripAccessGuard implements CanActivate {
|
|
constructor(
|
|
private readonly em: EntityManager,
|
|
private readonly permissions: PermissionsService,
|
|
private readonly reflector: Reflector,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<TripRequest>();
|
|
const user = request.user;
|
|
// JwtAuthGuard runs first and 401s an anonymous request, so a missing user here
|
|
// means the route was wired without it. Refuse rather than read `user.id` off
|
|
// undefined and turn a wiring mistake into a 500.
|
|
if (!user) throw new HttpException({ error: 'Unauthorized' }, 401);
|
|
|
|
const tripId = Number((request.params as Record<string, string>)?.tripId);
|
|
const trip = Number.isFinite(tripId) ? await this.em.getRepository(Trips).findAccessible(tripId, user.id) : undefined;
|
|
// A trip the user may not see is reported as absent, never as forbidden: a 403
|
|
// would confirm the id exists to someone who has no business knowing.
|
|
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
|
|
|
|
const action = this.reflector.getAllAndOverride<string | undefined>(TRIP_PERMISSION_KEY, [
|
|
context.getHandler(),
|
|
context.getClass(),
|
|
]);
|
|
if (action) {
|
|
const shared = trip.user_id !== user.id;
|
|
if (!(await this.permissions.checkPermission(action, user.role, trip.user_id, user.id, shared))) {
|
|
throw new HttpException({ error: 'No permission' }, 403);
|
|
}
|
|
}
|
|
|
|
request[TRIP_REQUEST_KEY] = trip;
|
|
return true;
|
|
}
|
|
}
|