Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { RateLimiter } from "./rate_limiter.ts";
export type HttpHandler = (request: Request, info?: Deno.ServeHandlerInfo) => Promise<Response> | Response;
export type Middleware = (next: HttpHandler) => HttpHandler;

const healthPattern = new URLPattern({ pathname: "/health" });
const HEALTH_PATTERN = new URLPattern({ pathname: "/health" });

export function withAuth(apiToken: string): Middleware {
return (next: HttpHandler) => {
return (request: Request, info?: Deno.ServeHandlerInfo) => {
if (healthPattern.exec(request.url)) {
if (HEALTH_PATTERN.exec(request.url)) {
return next(request, info);
}
const authHeader = request.headers.get("Authorization");
Expand All @@ -23,7 +23,7 @@ export function withAuth(apiToken: string): Middleware {
export function withRateLimit(limiter: RateLimiter): Middleware {
return (next: HttpHandler) => {
return (request: Request, info?: Deno.ServeHandlerInfo) => {
if (healthPattern.exec(request.url)) {
if (HEALTH_PATTERN.exec(request.url)) {
return next(request, info);
}
const remoteAddr = info?.remoteAddr && info.remoteAddr.transport === "tcp"
Expand Down
10 changes: 10 additions & 0 deletions tests/handler_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,16 @@ Deno.test("response body: rate limited returns 'Too many requests'", async () =>
assertEquals(await res.text(), "Too many requests");
});

Deno.test("middleware: rate limiting runs before authentication", async () => {
const handler = makeHandler(undefined, undefined, 1);
const firstResponse = await handler(new Request("http://localhost/length/q"));
const secondResponse = await handler(new Request("http://localhost/length/q"));

assertEquals(firstResponse.status, 401);
assertEquals(secondResponse.status, 429);
assertEquals(await secondResponse.text(), "Too many requests");
});

Deno.test("response body: queues POST returns 'Method not allowed'", async () => {
const handler = makeHandler();
const res = await handler(new Request("http://localhost/queues", { method: "POST", headers: auth }));
Expand Down