From 4c396717efd1787598c8889c21b6c6fc2f3839ed Mon Sep 17 00:00:00 2001 From: Jack Date: Sat, 12 Mar 2022 15:20:18 +0100 Subject: [PATCH] Added a custom auth counter to prometheus metrics (#2690) * added basic auth and prom client dependencies * incrementing auth counter * added custom prometheus metric * turns out there is no need for basic auth * updated name * exact * exact --- backend/middlewares/auth.ts | 9 ++++++++- backend/utils/prometheus.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 backend/utils/prometheus.ts diff --git a/backend/middlewares/auth.ts b/backend/middlewares/auth.ts index afe9db835..bb241e6c3 100644 --- a/backend/middlewares/auth.ts +++ b/backend/middlewares/auth.ts @@ -5,6 +5,7 @@ import { verifyIdToken } from "../utils/auth"; import { base64UrlDecode } from "../utils/misc"; import { NextFunction, Response, Handler } from "express"; import statuses from "../constants/monkey-status-codes"; +import { incrementAuth } from "../utils/prometheus"; interface RequestAuthenticationOptions { isPublic?: boolean; @@ -38,7 +39,11 @@ function authenticateRequest(authOptions = DEFAULT_OPTIONS): Handler { options ); } else if (options.isPublic) { - return next(); + token = { + type: "None", + uid: "", + email: "", + }; } else if (process.env.MODE === "dev") { token = authenticateWithBody(req.body); } else { @@ -49,6 +54,8 @@ function authenticateRequest(authOptions = DEFAULT_OPTIONS): Handler { ); } + incrementAuth(token.type); + req.ctx = { ...req.ctx, decodedToken: token, diff --git a/backend/utils/prometheus.ts b/backend/utils/prometheus.ts new file mode 100644 index 000000000..119ee1ad1 --- /dev/null +++ b/backend/utils/prometheus.ts @@ -0,0 +1,12 @@ +import "dotenv/config"; +import { Counter } from "prom-client"; + +const auth = new Counter({ + name: "api_request_auth_total", + help: "Counts authentication events", + labelNames: ["type"], +}); + +export function incrementAuth(type: "Bearer" | "ApeKey" | "None"): void { + auth.inc({ type }); +}