Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/mcp/src/rate-limit.test.ts
T
2026-07-08 16:15:37 +02:00

62 lines
2.5 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createSharedStore } from "@hivegrid/shared-store";
import {
checkMcpPreAuthIpRateLimit,
checkMcpRateLimit,
MCP_KEY_RATE_LIMIT_PER_HOUR,
MCP_MAX_BATCH_OPERATIONS,
MCP_PREAUTH_IP_RATE_LIMIT_PER_MINUTE,
__resetMcpRateLimitStoreForTests,
__setMcpRateLimitStoreForTests,
} from "./rate-limit.js";
beforeEach(() => {
__setMcpRateLimitStoreForTests(createSharedStore({ namespace: "test-mcp-rate-limit" }));
});
afterEach(() => {
__resetMcpRateLimitStoreForTests();
});
describe("checkMcpRateLimit weighting", () => {
it("charges one token per operation so a batch cannot bypass the per-key cap", async () => {
// Each batch charges MCP_MAX_BATCH_OPERATIONS tokens (the weight is clamped
// to the batch cap, since larger batches are rejected upstream). Enough
// full batches to exhaust the per-hour budget must be blocked afterwards.
const batches = MCP_KEY_RATE_LIMIT_PER_HOUR / MCP_MAX_BATCH_OPERATIONS;
for (let index = 0; index < batches; index += 1) {
expect((await checkMcpRateLimit({ apiKeyId: "k1", tenantId: "t1", weight: MCP_MAX_BATCH_OPERATIONS })).allowed).toBe(true);
}
const overflow = await checkMcpRateLimit({ apiKeyId: "k1", tenantId: "t1", weight: 1 });
expect(overflow.allowed).toBe(false);
});
it("defaults to a single token when no weight is given", async () => {
for (let index = 0; index < MCP_KEY_RATE_LIMIT_PER_HOUR; index += 1) {
expect((await checkMcpRateLimit({ apiKeyId: "k2", tenantId: "t2" })).allowed).toBe(true);
}
expect((await checkMcpRateLimit({ apiKeyId: "k2", tenantId: "t2" })).allowed).toBe(false);
});
});
describe("checkMcpPreAuthIpRateLimit", () => {
it("sheds an unauthenticated flood from a single IP after the per-minute cap", async () => {
for (let index = 0; index < MCP_PREAUTH_IP_RATE_LIMIT_PER_MINUTE; index += 1) {
expect((await checkMcpPreAuthIpRateLimit("203.0.113.5")).allowed).toBe(true);
}
const blocked = await checkMcpPreAuthIpRateLimit("203.0.113.5");
expect(blocked.allowed).toBe(false);
if (!blocked.allowed) {
expect(blocked.status).toBe(429);
}
});
it("keys the shield per IP so distinct IPs do not share a bucket", async () => {
for (let index = 0; index < MCP_PREAUTH_IP_RATE_LIMIT_PER_MINUTE; index += 1) {
await checkMcpPreAuthIpRateLimit("203.0.113.5");
}
expect((await checkMcpPreAuthIpRateLimit("203.0.113.6")).allowed).toBe(true);
});
});