Skip to content

Commit 4418de5

Browse files
committed
Whitelist api endpoints that don’t use an authorization endpoint from the rate limiter
1 parent 0d2a71c commit 4418de5

1 file changed

Lines changed: 27 additions & 14 deletions

File tree

apps/webapp/app/services/apiRateLimit.server.ts

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ type Options = {
3838
redis: RedisOptions;
3939
keyPrefix: string;
4040
pathMatchers: (RegExp | string)[];
41+
pathWhiteList?: (RegExp | string)[];
4142
limiter: ConstructorParameters<typeof Ratelimit>[0]["limiter"];
4243
};
4344

@@ -47,6 +48,7 @@ export function authorizationRateLimitMiddleware({
4748
keyPrefix,
4849
limiter,
4950
pathMatchers,
51+
pathWhiteList = [],
5052
log = {
5153
rejections: true,
5254
requests: true,
@@ -78,6 +80,18 @@ export function authorizationRateLimitMiddleware({
7880
return next();
7981
}
8082

83+
// Check if the path matches any of the whitelisted paths
84+
if (
85+
pathWhiteList.some((matcher) =>
86+
matcher instanceof RegExp ? matcher.test(path) : path === matcher
87+
)
88+
) {
89+
if (log.requests) {
90+
logger.info(`RateLimiter (${keyPrefix}): whitelisted ${req.path}`);
91+
}
92+
return next();
93+
}
94+
8195
if (log.requests) {
8296
logger.info(`RateLimiter (${keyPrefix}): matched ${req.path}`);
8397
}
@@ -88,20 +102,18 @@ export function authorizationRateLimitMiddleware({
88102
logger.info(`RateLimiter (${keyPrefix}): no key`);
89103
}
90104
res.setHeader("Content-Type", "application/problem+json");
91-
return res
92-
.status(401)
93-
.send(
94-
JSON.stringify(
95-
{
96-
title: "Unauthorized",
97-
status: 401,
98-
type: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401",
99-
detail: "No authorization header provided",
100-
},
101-
null,
102-
2
103-
)
104-
);
105+
return res.status(401).send(
106+
JSON.stringify(
107+
{
108+
title: "Unauthorized",
109+
status: 401,
110+
type: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401",
111+
detail: "No authorization header provided",
112+
},
113+
null,
114+
2
115+
)
116+
);
105117
}
106118

107119
const hash = createHash("sha256");
@@ -170,6 +182,7 @@ export const apiRateLimiter = authorizationRateLimitMiddleware({
170182
},
171183
limiter: Ratelimit.slidingWindow(env.API_RATE_LIMIT_MAX, env.API_RATE_LIMIT_WINDOW as Duration),
172184
pathMatchers: [/^\/api/],
185+
pathWhiteList: ["/api/v1/authorization-code", "/api/v1/token"],
173186
log: {
174187
rejections: true,
175188
requests: false,

0 commit comments

Comments
 (0)