feat: add optional basic auth for metrics endpoint

This commit is contained in:
Julian Tölle 2020-12-06 03:03:33 +01:00
parent a6097204c7
commit 879c6a62e2
7 changed files with 92 additions and 3 deletions

View file

@ -0,0 +1,36 @@
import {
Injectable,
NestMiddleware,
UnauthorizedException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { IncomingMessage } from "http";
@Injectable()
export class MetricsAuthMiddleware implements NestMiddleware {
private readonly expectedHeaderValue: string;
constructor(config: ConfigService) {
const username = config.get<string>("PROMETHEUS_BASIC_AUTH_USERNAME");
const password = config.get<string>("PROMETHEUS_BASIC_AUTH_PASSWORD");
this.expectedHeaderValue = MetricsAuthMiddleware.buildHeaderValue(
username,
password
);
}
private static buildHeaderValue(username: string, password: string): string {
return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
}
use(req: IncomingMessage, res: any, next: () => void) {
const header = req.headers?.authorization;
if (header !== this.expectedHeaderValue) {
throw new UnauthorizedException("MetricsBasicAuthNotMatching");
}
next();
}
}