diff --git a/services/collector/src/auth/write-key.guard.ts b/services/collector/src/auth/write-key.guard.ts new file mode 100644 index 0000000..d73f1bf --- /dev/null +++ b/services/collector/src/auth/write-key.guard.ts @@ -0,0 +1,38 @@ +import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import type { Request } from 'express'; + +export const IS_PUBLIC_KEY = 'isPublic'; + +@Injectable() +export class WriteKeyGuard implements CanActivate { + private readonly writeKey: string; + + constructor(private readonly reflector: Reflector) { + const key = process.env['COLLECTOR_WRITE_KEY']; + if (!key) { + throw new Error('COLLECTOR_WRITE_KEY environment variable is required'); + } + this.writeKey = key; + } + + canActivate(context: ExecutionContext): boolean { + const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ + context.getHandler(), + context.getClass(), + ]); + + if (isPublic) { + return true; + } + + const request = context.switchToHttp().getRequest(); + const provided = request.headers['x-write-key']; + + if (provided !== this.writeKey) { + throw new UnauthorizedException('Invalid or missing write key'); + } + + return true; + } +}