mirror of
https://github.com/outline/outline.git
synced 2026-11-26 15:43:48 +03:00
fix: Rate limit response headers and first-request accounting (#13506)
* fix: Rate limit response headers and first-request accounting Retry-After and RateLimit-Reset are both defined as a whole number of seconds. Retry-After was sent as a fraction and RateLimit-Reset as a full date string, neither of which a client can act on. A route limiter is registered by middleware that runs after the point where quota is consumed, so the first request to reach a path in each process was never charged against it. Charge it at registration time instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test: Cover rate limit headers and first request accounting Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
67b53220ce
commit
2beacf9d56
3 files changed
+149
-31
No files matched your search
@@ -10,6 +10,8 @@ interface MockContextOptions {
|
||||
path?: string;
|
||||
mountPath?: string;
|
||||
ip?: string;
|
||||
/** Records the response headers the middleware writes. */
|
||||
set?: ReturnType<typeof vi.fn>;
|
||||
/** When set, presented as a bearer token in the authorization header. */
|
||||
token?: string;
|
||||
}
|
||||
@@ -18,13 +20,15 @@ const createContext = ({
|
||||
path = "/some/path",
|
||||
mountPath,
|
||||
ip = "192.168.1.1",
|
||||
set,
|
||||
token,
|
||||
}: MockContextOptions = {}) =>
|
||||
({
|
||||
path,
|
||||
mountPath,
|
||||
ip,
|
||||
set: vi.fn(),
|
||||
state: {},
|
||||
set: set ?? vi.fn(),
|
||||
request: {
|
||||
get: () => (token ? `Bearer ${token}` : undefined),
|
||||
body: {},
|
||||
@@ -348,4 +352,83 @@ describe("rateLimiter middleware", () => {
|
||||
expect(consumeSpy).toHaveBeenCalledWith("/api/documents.export:user-abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("first request accounting", () => {
|
||||
it("charges the request that registers a route limiter", async () => {
|
||||
const path = "/auth/registers";
|
||||
const register = rateLimiter({ duration: 3600, requests: 1 });
|
||||
|
||||
// Registration happens downstream of the point where quota is consumed,
|
||||
// so this request has to be charged here or it goes uncounted.
|
||||
const next = vi.fn();
|
||||
await register(createContext({ path }), next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
|
||||
// The single point is now spent, so the next request is rejected by the
|
||||
// default middleware.
|
||||
await expect(
|
||||
defaultRateLimiter()(createContext({ path }), vi.fn())
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("reuses the identifiers the default middleware resolved", async () => {
|
||||
const path = "/auth/reuses";
|
||||
const ctx = createContext({ path, token: "verified-token" });
|
||||
const cacheSpy = vi
|
||||
.spyOn(RateLimiter, "getCachedUserIdForToken")
|
||||
.mockResolvedValue("user-abc");
|
||||
|
||||
await defaultRateLimiter()(ctx, vi.fn());
|
||||
cacheSpy.mockClear();
|
||||
|
||||
await rateLimiter({ duration: 3600, requests: 5 })(ctx, vi.fn());
|
||||
|
||||
expect(cacheSpy).not.toHaveBeenCalled();
|
||||
const limiter = RateLimiter.getRateLimiter(path);
|
||||
await expect(limiter.get(`${path}:user-abc`)).resolves.toMatchObject({
|
||||
consumedPoints: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("rejection headers", () => {
|
||||
/** Trips a route limiter and returns the headers it wrote. */
|
||||
const tripLimiter = async (path: string, msBeforeNext: number) => {
|
||||
await rateLimiter({ duration: 3600, requests: 5 })(
|
||||
createContext({ path }),
|
||||
vi.fn()
|
||||
);
|
||||
|
||||
vi.spyOn(RateLimiter.getRateLimiter(path), "consume").mockRejectedValue(
|
||||
new RateLimiterRes(0, msBeforeNext, 6)
|
||||
);
|
||||
|
||||
const set = vi.fn();
|
||||
await expect(
|
||||
defaultRateLimiter()(createContext({ path, set }), vi.fn())
|
||||
).rejects.toThrow();
|
||||
return set;
|
||||
};
|
||||
|
||||
it("reports the wait as a whole number of seconds", async () => {
|
||||
const set = await tripLimiter("/auth/whole", 59986);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("Retry-After", "60");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Reset", "60");
|
||||
});
|
||||
|
||||
it("rounds up so a client that waits is not rejected again", async () => {
|
||||
const set = await tripLimiter("/auth/rounds", 1);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("Retry-After", "1");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Reset", "1");
|
||||
});
|
||||
|
||||
it("reports the limit and the remaining quota", async () => {
|
||||
const set = await tripLimiter("/auth/quota", 30000);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Limit", "5");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Remaining", "0");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -52,6 +52,56 @@ async function getRateLimiterIdentifiers(ctx: AppContext): Promise<string[]> {
|
||||
return [ctx.ip];
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a point from a limiter for every identifier on the request. A
|
||||
* limiter that is unreachable is logged and skipped, so an outage of the store
|
||||
* does not take the endpoint down with it.
|
||||
*
|
||||
* @param ctx The application context.
|
||||
* @param fullPath The path the limiter is registered against.
|
||||
* @param identifiers The identifiers to consume for this request.
|
||||
* @throws RateLimitExceededError when an identifier is out of quota.
|
||||
*/
|
||||
async function consume(
|
||||
ctx: AppContext,
|
||||
fullPath: string,
|
||||
identifiers: string[]
|
||||
): Promise<void> {
|
||||
const isPathScoped = RateLimiter.hasRateLimiter(fullPath);
|
||||
const limiter = RateLimiter.getRateLimiter(fullPath);
|
||||
|
||||
try {
|
||||
for (const identifier of identifiers) {
|
||||
await limiter.consume(
|
||||
isPathScoped ? `${fullPath}:${identifier}` : identifier
|
||||
);
|
||||
}
|
||||
} catch (rateLimiterRes) {
|
||||
if (
|
||||
rateLimiterRes instanceof Error ||
|
||||
!(rateLimiterRes instanceof RateLimiterRes)
|
||||
) {
|
||||
Logger.error("Rate limiter error", toError(rateLimiterRes));
|
||||
return;
|
||||
}
|
||||
|
||||
// Both headers are defined as a whole number of seconds, rounded up so that
|
||||
// a client waiting exactly this long is not turned away a second time.
|
||||
const resetSeconds = Math.ceil(rateLimiterRes.msBeforeNext / 1000);
|
||||
|
||||
ctx.set("Retry-After", `${resetSeconds}`);
|
||||
ctx.set("RateLimit-Limit", `${limiter.points}`);
|
||||
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
|
||||
ctx.set("RateLimit-Reset", `${resetSeconds}`);
|
||||
|
||||
Metrics.increment("rate_limit.exceeded", {
|
||||
path: fullPath,
|
||||
});
|
||||
|
||||
throw RateLimitExceededError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that limits the number of requests that are allowed within a given
|
||||
* window. Should only be applied once to a server – do not use on individual
|
||||
@@ -67,38 +117,12 @@ export function defaultRateLimiter() {
|
||||
|
||||
const fullPath = `${ctx.mountPath ?? ""}${ctx.path}`;
|
||||
const identifiers = await getRateLimiterIdentifiers(ctx);
|
||||
const isPathScoped = RateLimiter.hasRateLimiter(fullPath);
|
||||
const limiter = RateLimiter.getRateLimiter(fullPath);
|
||||
|
||||
try {
|
||||
for (const identifier of identifiers) {
|
||||
await limiter.consume(
|
||||
isPathScoped ? `${fullPath}:${identifier}` : identifier
|
||||
);
|
||||
}
|
||||
} catch (rateLimiterRes) {
|
||||
if (
|
||||
rateLimiterRes instanceof Error ||
|
||||
!(rateLimiterRes instanceof RateLimiterRes)
|
||||
) {
|
||||
Logger.error("Rate limiter error", toError(rateLimiterRes));
|
||||
return next();
|
||||
}
|
||||
// Kept for a route that registers its own limiter further down the chain,
|
||||
// so that it can charge this request without resolving them again.
|
||||
ctx.state.rateLimiterIdentifiers = identifiers;
|
||||
|
||||
ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`);
|
||||
ctx.set("RateLimit-Limit", `${limiter.points}`);
|
||||
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
|
||||
ctx.set(
|
||||
"RateLimit-Reset",
|
||||
new Date(Date.now() + rateLimiterRes.msBeforeNext).toString()
|
||||
);
|
||||
|
||||
Metrics.increment("rate_limit.exceeded", {
|
||||
path: fullPath,
|
||||
});
|
||||
|
||||
throw RateLimitExceededError();
|
||||
}
|
||||
await consume(ctx, fullPath, identifiers);
|
||||
|
||||
return next();
|
||||
};
|
||||
@@ -150,6 +174,15 @@ export function rateLimiter(config: RateLimiterConfig) {
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// The limiter did not exist when the request entered the default
|
||||
// middleware, so this request has not been charged against it yet.
|
||||
await consume(
|
||||
ctx,
|
||||
fullPath,
|
||||
ctx.state.rateLimiterIdentifiers ??
|
||||
(await getRateLimiterIdentifiers(ctx))
|
||||
);
|
||||
}
|
||||
|
||||
return next();
|
||||
|
||||
@@ -76,6 +76,8 @@ export type AppState = {
|
||||
oauthClient?: OAuthClient;
|
||||
oauthIntent?: OAuthIntent;
|
||||
oauthState?: OAuthState;
|
||||
/** The identifiers this request is rate limited against. */
|
||||
rateLimiterIdentifiers?: string[];
|
||||
};
|
||||
|
||||
export type AppContext = ParameterizedContext<AppState, DefaultContext>;
|
||||
|
||||
Reference in new issue
Block a user