-
Notifications
You must be signed in to change notification settings - Fork 1
feat(mcp): rate-limit client_credentials issuance and CIMD fetch attempts (#163) #171
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
heskew
wants to merge
8
commits into
main
Choose a base branch
from
feat/163-token-rate-limit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
33cb06b
feat(mcp): rate-limit client_credentials issuance and CIMD fetch atte…
heskew cdaa77d
refactor(cimd): check concurrency cap before spending a fetch-limiter…
heskew ad30fb2
fix(mcp): clamp sub-1 bucket capacity and cap client_id length
heskew 523ce12
fix(mcp): move issuance limiter post-auth; fingerprint limiter keys
heskew e267f91
docs(mcp): correct the rate-limiter ordering claim after the post-aut…
heskew b221570
feat(mcp): surface 429 + Retry-After on CIMD throttles; centralize cl…
heskew f056475
fix(mcp): cap Retry-After; cover the authorize-endpoint 429 branch
heskew 1fa1e28
fix(mcp): correct Retry-After comment; guard refill rate in the limiter
heskew File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| /** | ||
| * Per-node in-memory token-bucket rate limiter (#163). | ||
| * | ||
| * Deliberately PER-NODE, not replicated: Harper replication makes a shared | ||
| * counter table a hot-write anti-pattern, and the surfaces this limits are | ||
| * already bounded cross-node — the client_credentials grant by the assertion | ||
| * replay guard and its ≤60s `exp` window, CIMD fetches by the concurrency | ||
| * caps. A node-local bucket is the right defense-in-depth without turning | ||
| * every token request into a replicated write. | ||
| * | ||
| * Buckets refill continuously (elapsed-time based — no interval timers), so a | ||
| * limit of N/min admits a burst of up to N and then one request per 60/N | ||
| * seconds. Keys may be ATTACKER-CHOSEN strings (client_ids, URLs), so: (1) the | ||
| * key space is LRU-bounded — at `maxKeys` the least-recently-used bucket is | ||
| * evicted (an evicted bucket forgets that key's spend history, acceptable | ||
| * because eviction requires `maxKeys` distinct keys inside one window and the | ||
| * global concurrency caps still bound aggregate work); and (2) the key is | ||
| * stored as a fixed-size SHA-256 fingerprint, so a flood of long distinct keys | ||
| * bounds map memory to `maxKeys` × a constant, not × the raw key length. | ||
| */ | ||
|
|
||
| import { createHash } from 'node:crypto'; | ||
|
|
||
| type BucketState = { tokens: number; lastRefill: number }; | ||
|
|
||
| export type RateLimitResult = { allowed: true } | { allowed: false; retryAfterSeconds: number }; | ||
|
|
||
| export type RateLimiter = { | ||
| tryTake(key: string): RateLimitResult; | ||
| /** Drop all bucket state (for testing). @internal */ | ||
| _reset(): void; | ||
| }; | ||
|
|
||
| const DEFAULT_MAX_KEYS = 10_000; | ||
|
|
||
| // Cap the advertised Retry-After. A tiny configured rate (e.g. 0.001/min) | ||
| // would otherwise yield an absurd multi-year value; 2,147,483 s (≈24.8 days, | ||
| // int32-max milliseconds expressed as whole seconds) is a sane ceiling for any | ||
| // client parsing the header. | ||
| const MAX_RETRY_AFTER_SECONDS = 2_147_483; | ||
|
heskew marked this conversation as resolved.
|
||
|
|
||
| export function createRateLimiter(options: { | ||
| /** Bucket capacity (maximum burst). */ | ||
| capacity: number; | ||
| /** Continuous refill rate, tokens per minute. */ | ||
| refillPerMinute: number; | ||
| /** LRU bound on distinct keys tracked. Default 10 000. */ | ||
| maxKeys?: number; | ||
| /** Clock override (for testing). Default Date.now. */ | ||
| now?: () => number; | ||
|
heskew marked this conversation as resolved.
|
||
| }): RateLimiter { | ||
| // A token bucket takes 1 token per request, so a burst ceiling below 1 could | ||
|
heskew marked this conversation as resolved.
|
||
| // never admit anyone — clamp it up. The refill rate is left untouched (a | ||
| // sub-1/min limit still means "one request, then one per 60/rate seconds"), | ||
| // except that a non-finite or non-positive rate — which would make the | ||
| // bucket never refill and the retry-after math divide by zero/negative — | ||
| // falls back to the (already ≥1) capacity so the limiter stays well-defined. | ||
| const capacity = Math.max(1, options.capacity); | ||
| const refillPerMinute = | ||
| Number.isFinite(options.refillPerMinute) && options.refillPerMinute > 0 ? options.refillPerMinute : capacity; | ||
| const maxKeys = options.maxKeys ?? DEFAULT_MAX_KEYS; | ||
| const now = options.now ?? Date.now; | ||
|
heskew marked this conversation as resolved.
|
||
| const buckets = new Map<string, BucketState>(); | ||
|
|
||
| return { | ||
| tryTake(key: string): RateLimitResult { | ||
| // Fixed-size fingerprint: the raw key may be an attacker-chosen URL of | ||
| // arbitrary length, and it is retained in the map until evicted. | ||
| const mapKey = createHash('sha256').update(key).digest('base64url'); | ||
| const at = now(); | ||
| let bucket = buckets.get(mapKey); | ||
| if (bucket) { | ||
| const elapsedMs = at - bucket.lastRefill; | ||
| if (elapsedMs > 0) { | ||
| bucket.tokens = Math.min(capacity, bucket.tokens + (elapsedMs / 60_000) * refillPerMinute); | ||
| bucket.lastRefill = at; | ||
| } | ||
| // Delete now; the set below re-inserts so Map order tracks recency (LRU). | ||
| buckets.delete(mapKey); | ||
| } else { | ||
| bucket = { tokens: capacity, lastRefill: at }; | ||
| if (buckets.size >= maxKeys) { | ||
| const oldest = buckets.keys().next().value; | ||
| if (oldest !== undefined) buckets.delete(oldest); | ||
| } | ||
| } | ||
| let result: RateLimitResult; | ||
| if (bucket.tokens >= 1) { | ||
|
heskew marked this conversation as resolved.
|
||
| bucket.tokens -= 1; | ||
| result = { allowed: true }; | ||
| } else { | ||
| const deficit = 1 - bucket.tokens; | ||
| const retryAfterSeconds = Math.min(MAX_RETRY_AFTER_SECONDS, Math.ceil((deficit * 60) / refillPerMinute)); | ||
| result = { allowed: false, retryAfterSeconds }; | ||
| } | ||
| buckets.set(mapKey, bucket); | ||
| return result; | ||
| }, | ||
| _reset(): void { | ||
| buckets.clear(); | ||
| }, | ||
| }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.