Skip to content

Commit 3478bd6

Browse files
committed
fix: avoid regex-based bearer parsing
1 parent 72c339d commit 3478bd6

3 files changed

Lines changed: 30 additions & 10 deletions

File tree

src/controllers/metricsController.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,17 @@ import {
55
renderMetrics,
66
} from "../metrics/authMetrics";
77
import { env } from "../config/env";
8-
9-
const getBearerToken = (request: Request): string | null => {
10-
const authorization = request.header("authorization");
11-
const match = authorization?.match(/^Bearer\s+(.+)$/i);
12-
13-
return match?.[1]?.trim() || null;
14-
};
8+
import { extractBearerToken } from "../utils/bearerToken";
159

1610
export async function metrics(req: Request, res: Response) {
1711
if (!metricsEnabled) {
1812
return res.status(404).json({ message: "metrics disabled" });
1913
}
2014

21-
if (env.METRICS_AUTH_TOKEN && getBearerToken(req) !== env.METRICS_AUTH_TOKEN) {
15+
if (
16+
env.METRICS_AUTH_TOKEN &&
17+
extractBearerToken(req.header("authorization")) !== env.METRICS_AUTH_TOKEN
18+
) {
2219
return res.status(401).json({
2320
error: {
2421
code: "METRICS_AUTHORIZATION_REQUIRED",

src/middlewares/authMiddleware.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { SessionStatus } from "@prisma/client";
33
import AppError from "../errors/AppError";
44
import tokenService from "../services/tokenService";
55
import sessionRepository from "../repositories/sessionRepository";
6+
import { extractBearerToken } from "../utils/bearerToken";
67

78
export default async function authMiddleware(
89
req: Request,
@@ -21,8 +22,7 @@ export default async function authMiddleware(
2122
);
2223
}
2324

24-
const match = authorization.match(/^Bearer\s+(.+)$/i);
25-
const token = match?.[1];
25+
const token = extractBearerToken(authorization);
2626
if (!token) {
2727
return next(
2828
new AppError({

src/utils/bearerToken.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export function extractBearerToken(authorization: string | undefined): string | null {
2+
if (!authorization) {
3+
return null;
4+
}
5+
6+
const trimmed = authorization.trim();
7+
if (trimmed.length === 0) {
8+
return null;
9+
}
10+
11+
const separatorIndex = trimmed.indexOf(" ");
12+
if (separatorIndex === -1) {
13+
return null;
14+
}
15+
16+
const scheme = trimmed.slice(0, separatorIndex);
17+
if (scheme.toLowerCase() !== "bearer") {
18+
return null;
19+
}
20+
21+
const token = trimmed.slice(separatorIndex + 1).trim();
22+
return token.length > 0 ? token : null;
23+
}

0 commit comments

Comments
 (0)