Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(api): return 402 when a per-key spend limit denies credits (#4412)

claude[bot]f9389226d85b
diff --git a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts b/apps/api/src/__tests__/routes/check-credits-middleware.test.ts
index c716cf300..485a34de9 100644
--- a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts
+++ b/apps/api/src/__tests__/routes/check-credits-middleware.test.ts
@@ -52,13 +52,16 @@ function buildReq(overrides: any = {}): any {
};
}
-function runMiddleware(req: any): Promise<{ res: any; nextErr?: any }> {
+function runMiddleware(
+ req: any,
+): Promise<{ res: any; nextErr?: any; nextCalled: boolean }> {
return new Promise(resolve => {
let settled = false;
+ let nextCalled = false;
const settle = (payload: { res: any; nextErr?: any }) => {
if (settled) return;
settled = true;
- resolve(payload);
+ resolve({ ...payload, nextCalled });
};
const res: any = {
@@ -71,7 +74,10 @@ function runMiddleware(req: any): Promise<{ res: any; nextErr?: any }> {
headersSent: false,
};
- const next: NextFunction = (err?: any) => settle({ res, nextErr: err });
+ const next: NextFunction = (err?: any) => {
+ nextCalled = true;
+ settle({ res, nextErr: err });
+ };
checkCreditsMiddleware()(req, res, next);
});
}
@@ -103,13 +109,63 @@ describe("checkCreditsMiddleware – Autumn overage handling", () => {
});
it("adjusts crawl limit down when Autumn denies but some credits remain", async () => {
- checkCreditsMock.mockResolvedValue({ allowed: false, remaining: 5 });
+ checkCreditsMock
+ .mockResolvedValueOnce({ allowed: false, remaining: 5 })
+ .mockResolvedValueOnce({ allowed: true, remaining: 5 });
const req = buildReq({ body: { limit: 100 } });
const { res } = await runMiddleware(req);
expect(res.status).not.toHaveBeenCalled();
expect(req.body.limit).toBe(5);
+ expect(checkCreditsMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ value: 5,
+ properties: expect.objectContaining({
+ source: "checkCreditsMiddleware:clamp",
+ apiKeyId: null,
+ }),
+ }),
+ );
+ });
+
+ it("blocks with 402 when a per-key spend limit denies but the team balance is healthy", async () => {
+ // A per-API-key spend limit does not lower the team balance, so both the
+ // initial check and the clamped re-check deny with credits still remaining.
+ checkCreditsMock.mockResolvedValue({ allowed: false, remaining: 5000 });
+
+ const req = buildReq({ body: { limit: 100 } });
+ const { res, nextCalled } = await runMiddleware(req);
+
+ expect(res.status).toHaveBeenCalledWith(402);
+ expect(nextCalled).toBe(false);
+ // A request that ends in a 402 keeps the caller's original limit.
+ expect(req.body.limit).toBe(100);
+ });
+
+ it("clamps the crawl limit down only, never up to the remaining balance", async () => {
+ checkCreditsMock
+ .mockResolvedValueOnce({ allowed: false, remaining: 5000 })
+ .mockResolvedValueOnce({ allowed: true, remaining: 5000 });
+
+ const req = buildReq({ body: { limit: 5 } });
+ const { res } = await runMiddleware(req);
+
+ expect(res.status).not.toHaveBeenCalled();
+ expect(req.body.limit).toBe(5);
+ });
+
+ it("fails open when the clamped re-check finds Autumn unavailable", async () => {
+ checkCreditsMock
+ .mockResolvedValueOnce({ allowed: false, remaining: 5 })
+ .mockResolvedValueOnce(null);
+
+ const req = buildReq({ body: { limit: 100 } });
+ const { res, nextCalled } = await runMiddleware(req);
+
+ expect(res.status).not.toHaveBeenCalled();
+ expect(nextCalled).toBe(true);
+ expect(req.body.limit).toBe(5);
});
it("forwards the API key id in the check properties so Autumn can enforce per-key limits", async () => {
diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.ts
index 3d8443b27..a6d34ce59 100644
--- a/apps/api/src/routes/shared.ts
+++ b/apps/api/src/routes/shared.ts
@@ -167,19 +167,41 @@ export function checkCreditsMiddleware(
const remainingCredits = success ? Infinity : autumnResult.remaining;
req.account = { remainingCredits };
if (!success) {
+ const requestedLimit = Number((req.body as any)?.limit);
+ const clampedLimit = Math.min(requestedLimit, remainingCredits);
if (
!_minimum &&
req.body &&
(req.body as any).limit !== undefined &&
- remainingCredits > 0
+ Number.isFinite(clampedLimit) &&
+ clampedLimit > 0
) {
- logger.warn("Adjusting limit to remaining credits", {
+ // `remaining` is the team's credit balance, and a per-API-key spend
+ // limit never lowers it, so a key over its own cap still reports a
+ // healthy balance here. Re-check the clamped limit so only a genuinely
+ // low team balance gets shrunk to fit; a per-key denial falls through
+ // to the 402 below. A null re-check keeps the fail-open behavior.
+ const clampedResult = await autumnService.checkCredits({
teamId: req.auth.team_id,
- remainingCredits,
- request: req.body,
+ value: clampedLimit,
+ properties: {
+ source: "checkCreditsMiddleware:clamp",
+ path: req.path,
+ apiKeyId: req.acuc?.api_key_id ?? null,
+ },
+ featureId,
});
- (req.body as any).limit = remainingCredits;
- return next();
+
+ if (clampedResult === null || clampedResult.allowed) {
+ logger.warn("Adjusting limit to remaining credits", {
+ teamId: req.auth.team_id,
+ remainingCredits,
+ clampedLimit,
+ request: req.body,
+ });
+ (req.body as any).limit = clampedLimit;
+ return next();
+ }
}
const currencyName = req.acuc?.is_extract ? "tokens" : "credits";