SmartfolioBackend / src /modules /auth /admin-key.guard.ts
ibrahimgulbutt's picture
Restore AI: Groq retired the Llama models
2f666f7
Raw History Blame Contribute Delete
1.86 kB
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { timingSafeEqual } from 'crypto';
/**
* Guards operator-only endpoints (scraper maintenance, cross-user reads) with a
* shared secret sent as `x-admin-key`.
*
* This is deliberately not a role on the User entity: there is no admin UI and
* no self-serve path to becoming an admin, so a role column would be schema
* surface with no reader. If an admin dashboard is built later, replace this
* with a proper role guard.
*
* Fails closed — if ADMIN_API_KEY is unset the endpoint is unreachable rather
* than open, so a missing env var can never silently expose these routes.
*/
@Injectable()
export class AdminKeyGuard implements CanActivate {
private readonly logger = new Logger(AdminKeyGuard.name);
constructor(private readonly config: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const expected = this.config.get<string>('ADMIN_API_KEY');
if (!expected) {
this.logger.error(
'ADMIN_API_KEY is not configured: refusing admin request (failing closed).',
);
throw new ForbiddenException('Admin access is not configured.');
}
const request = context.switchToHttp().getRequest();
const provided = request.headers?.['x-admin-key'];
if (typeof provided !== 'string' || !this.matches(provided, expected)) {
throw new ForbiddenException('Admin access denied.');
}
return true;
}
/** Constant-time compare so a wrong key can't be recovered by timing. */
private matches(provided: string, expected: string): boolean {
const a = Buffer.from(provided);
const b = Buffer.from(expected);
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
}