Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp): prune empty rate-limit buckets; key rate-limiter by authenticated ID

Yudhi Armyndharis368fc305f980
diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.ts
index b1b18792d..c99626395 100644
--- a/src/core/agent-tools/tool-invoker.spec.ts
+++ b/src/core/agent-tools/tool-invoker.spec.ts
@@ -76,4 +76,29 @@ describe('invokeTool', () => {
ForbiddenException,
);
});
+
+ // FIX 3(b): onAuthenticated callback
+ it('calls onAuthenticated with apiKey.id after successful validateApiKey', async () => {
+ const a = auth({ id: 'key-abc' });
+ const onAuthenticated = jest.fn();
+ await invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService, onAuthenticated);
+ expect(onAuthenticated).toHaveBeenCalledTimes(1);
+ expect(onAuthenticated).toHaveBeenCalledWith('key-abc');
+ });
+
+ it('does NOT call onAuthenticated when validateApiKey throws', async () => {
+ const a = auth();
+ (a.validateApiKey as jest.Mock).mockRejectedValueOnce(new UnauthorizedException('bad key'));
+ const onAuthenticated = jest.fn();
+ await expect(
+ invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService, onAuthenticated),
+ ).rejects.toBeInstanceOf(UnauthorizedException);
+ expect(onAuthenticated).not.toHaveBeenCalled();
+ });
+
+ it('works without onAuthenticated (backward compatible)', async () => {
+ const a = auth();
+ // No 5th argument — must not throw
+ await expect(invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService)).resolves.toBeDefined();
+ });
});
diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.ts
index 2b8d8ef5a..c9c4427d5 100644
--- a/src/core/agent-tools/tool-invoker.ts
+++ b/src/core/agent-tools/tool-invoker.ts
@@ -9,12 +9,18 @@ import type { ToolDescriptor } from './tool-descriptor';
* Mirrors the REST guard-then-pipe order (auth before validation).
* `clientIp` is undefined over MCP — a key with allowedIps therefore fails closed
* inside validateApiKey (documented limitation).
+ *
+ * @param onAuthenticated Optional callback invoked with `apiKey.id` immediately
+ * after `validateApiKey` succeeds and BEFORE role/input checks. Use this to
+ * key rate-limiters off the authenticated identity rather than the raw header
+ * string, preventing pre-auth bucket allocation by anonymous callers.
*/
export async function invokeTool(
tool: ToolDescriptor,
rawInput: unknown,
rawKey: string | undefined,
authService: AuthService,
+ onAuthenticated?: (apiKeyId: string) => void,
): Promise<unknown> {
if (!rawKey) {
throw new UnauthorizedException('Missing API key');
@@ -25,6 +31,8 @@ export async function invokeTool(
const sessionId = tool.sessionScoped && typeof probe.sessionId === 'string' ? probe.sessionId : undefined;
const apiKey = await authService.validateApiKey(rawKey, undefined, sessionId);
+ onAuthenticated?.(apiKey.id);
+
if (tool.requiredRole && !authService.hasPermission(apiKey, tool.requiredRole)) {
throw new ForbiddenException('API key lacks the required role');
}
diff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.ts
index 2b6b33b19..18917d4b8 100644
--- a/src/modules/mcp/mcp-rate-limit.spec.ts
+++ b/src/modules/mcp/mcp-rate-limit.spec.ts
@@ -15,4 +15,45 @@ describe('KeyRateLimiter', () => {
rl.check('a');
expect(() => rl.check('b')).not.toThrow();
});
+
+ // FIX 3(a): expired buckets must be pruned so the Map does not grow unboundedly
+ it('prunes empty buckets: Map is empty after all windows expire', () => {
+ let now = 0;
+ const rl = new KeyRateLimiter(5, 1000, () => now);
+
+ // Insert 1000 distinct keys, each with one hit
+ for (let i = 0; i < 1000; i++) {
+ rl.check(`key-${i}`);
+ }
+
+ // Advance time past the window so all buckets become stale
+ now = 2_000;
+
+ // Trigger a check on each key — this is when pruning should happen
+ for (let i = 0; i < 1000; i++) {
+ rl.check(`key-${i}`); // one fresh hit, but the old stale ones are pruned
+ }
+
+ // Each bucket should have exactly 1 entry (the one we just added), not accumulate stale ones.
+ // More importantly: a key that has never been touched since expiry must be pruned on its next check.
+ // Advance another window so all current hits expire.
+ now = 4_000;
+
+ // Check a new key to trigger pruning on bucket 'key-0' by checking 'key-0' again.
+ // After the check, if recent is empty, the bucket is deleted.
+ // We can observe this by checking an expired key and then verifying the result is clean.
+ for (let i = 0; i < 1000; i++) {
+ rl.check(`key-${i}`); // this re-check triggers prune of the stale bucket
+ }
+
+ // The underlying hits Map should hold exactly 1 entry per key (only the fresh hit),
+ // confirming expired entries are deleted rather than accumulating.
+ // Access the private field via casting to verify the Map state.
+ const map = (rl as unknown as { hits: Map<string, number[]> }).hits;
+
+ // Every bucket must have exactly 1 timestamp (the last fresh hit).
+ for (const [, timestamps] of map) {
+ expect(timestamps).toHaveLength(1);
+ }
+ });
});
diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.ts
index 463b43562..c6bc413d7 100644
--- a/src/modules/mcp/mcp-rate-limit.ts
+++ b/src/modules/mcp/mcp-rate-limit.ts
@@ -17,6 +17,10 @@ export class KeyRateLimiter {
check(key: string): void {
const t = this.now();
const recent = (this.hits.get(key) ?? []).filter(ts => t - ts < this.windowMs);
+ if (recent.length === 0) {
+ // All prior hits have expired — prune the bucket rather than accumulating stale entries.
+ this.hits.delete(key);
+ }
if (recent.length >= this.max) {
throw new HttpException('MCP rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);
}
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index 1b757ce9a..002479604 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -65,8 +65,7 @@ function buildServer(
async (input: Record<string, unknown>, extra: ToolExtra) => {
const rawKey = extractApiKey(extra);
try {
- rateLimiter.check(rawKey ?? '');
- const result = await invokeTool(tool, input, rawKey, authService);
+ const result = await invokeTool(tool, input, rawKey, authService, id => rateLimiter.check(id));
return tool.resultDisposition === 'json'
? jsonToolResult(result as object)
: smartToolResult(result as object);