Repository navigation
feat: multiple API keys per account with per-key limits - #244
Conversation
… limits
OpenRouter-style multi-key support: one account can mint many named API keys,
each with its own limits. The per-account prepaid balance stays the hard
ceiling; per-key limits are soft sub-caps checked before the ledger reservation.
- Key prefix changed from "eigeninference-" to "sk-db-"; masked key labels
- Store: APIKey model + List/Get/Create/Update/RevokeByID/Authenticate/
RotateAPIKey/TouchAPIKey/KeySpendSince/RecordUsageFull (memory + Postgres,
with idempotent migrations and usage.key_id attribution)
- Per-key limits: spend cap (none/daily/weekly/monthly) + remaining, expiry,
disable, RPM, ITPM/OTPM, model allow-list
- OpenRouter-shaped endpoints: GET/POST /v1/keys, GET/PATCH/DELETE
/v1/keys/{id}, POST /v1/keys/{id}/rotate, GET /v1/key (Privy-session gated)
- ratelimit: per-key variable-rate RPM + ITPM/OTPM (KeyTokenLimiter)
- Console UI: ApiKeysManager component, proxy routes, api client
Hardening from adversarial verifier review:
- Fix fresh-DB Postgres migration ordering (usage.key_id)
- Atomic, transactional/locked key rotation
- Re-check per-key spend cap on provider price top-up
- Auth-cache generation barrier; provider-token fallback no longer cached;
ValidateKey enforces expiry
- Unlinked legacy keys use a non-secret identity (legacy:<sha256>) so the raw
key never reaches balances, ledger references, or logs
- Refund per-attempt provider reservation top-ups on speculative-loser/retry/
timeout abandonment (idempotent; no double-refund)
scripts/benchmark-{models,light}.py hardcoded a real API key. Read
DARKBLOOM_API_KEY / DARKBLOOM_BASE_URL from the environment instead and exit
with a clear message when unset. The leaked key has been revoked.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR introduces the multi-key API key management surface and per-key rate limiters; neither change directly weakens existing mitigations, but the new key management surface warrants close attention on one SEC-003–adjacent gap. Trust Boundaries Touched
Threat Assessment
New Attack Surface Not Covered by an Existing Threat1. Key rotation invalidation race (api.ts
2. Per-key rate limiter bypass for
3. Error message information leakage via
Open Findings ResolvedNone — this PR does not appear to resolve any SEC-* findings. SEC-003 (no-expiry long-lived keys) is arguably improved in spirit by this PR introducing 🔐 Threat model: |
Break the ~1100-line ApiKeysManager.tsx into a clean components/api-keys/ module with single-responsibility files: - constants.ts storage keys, shared class strings, copy, reset options - format.ts pure presentation helpers (usd/time/status/usage color) - limits.ts form-input -> sparse PATCH value parsers - Modal.tsx shared dialog shell - KeyForm.tsx create/edit form - SecretReveal.tsx show-once secret reveal - ConfirmBody.tsx confirm dialog body - KeyCard.tsx key row (+ chip/usage-bar/icon-action internals) - useApiKeys.ts data + mutations + console-key bookkeeping hook - ApiKeysManager.tsx thin orchestrator (modal state only) - index.ts barrel export No behavior change. Page import updated to @/components/api-keys. eslint clean, vitest 162 pass, next build succeeds.
Add a "Code Structure & Modularity" section to AGENTS.md and CLAUDE.md: keep files small and single-responsibility, group a feature into a dedicated module with a thin entry point, and do a behavior-preserving modular refactor pass at the end of every large piece of work. Wire that refactor step into CLAUDE.md's Quality Gate.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 494e315d80
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ctx = context.WithValue(ctx, auth.CtxKeyUser, user) | ||
| } | ||
| } else { | ||
| accountID = store.LegacyAccountID(token) |
There was a problem hiding this comment.
Preserve existing balances for unlinked keys
For unlinked/legacy API keys this changes the authenticated account ID from the raw bearer token to legacy:<sha256>. Existing balances and ledger rows were written under the old raw-token account ID by the previous requireAuth path, and the store only has key_hash/masked prefixes, so there is no migration path to move those balances after the fact. After deploy, any already-funded unlinked key will read a zero balance and inference will fail with insufficient funds until credits are manually recreated under the new ID.
Useful? React with 👍 / 👎.
| // Per-key ITPM/OTPM override (checked first so the binding per-key limit | ||
| // rejects before the account bucket is debited). | ||
| if !s.applyKeyTokenRateLimit(w, r, inputTokens, outputTokens) { | ||
| return false |
There was a problem hiding this comment.
Avoid charging key token buckets for rejected requests
When a key has an ITPM/OTPM override and the account-level token limiter later rejects the same request (for example because the shared account bucket is exhausted), this call has already consumed the key's token buckets even though the client receives a 429. Repeated account-level rejections can therefore drain the per-key quota and keep the key throttled after the account bucket refills; the key and account buckets need to be peeked/committed together or otherwise rolled back on downstream rejection.
Useful? React with 👍 / 👎.
…ances) Codex P2 — don't charge per-key token buckets for a request the account-level limiter rejects. applyTokenRateLimit now PEEKS the per-key and account token limiters, and only COMMITS both when both have capacity, so a rejection in one never debits the other. Adds Peek/Commit to TokenLimiter + KeyTokenLimiter. Codex P1 — preserve balances when an unlinked legacy key's identity changes from the raw bearer token to legacy:<sha256>. Adds an atomic MigrateAccountBalance (memory + Postgres) + LedgerMigration entries; requireAuth lazily migrates any funds from the old raw-token identity to the new one on first auth (one-time, no-op once moved; raw token never logged). CodeQL clear-text-storage — documents the console-key localStorage write as the pre-existing, accepted SEC-003 tradeoff (a browser console must hold its bearer key locally); no architectural change here. Tests: MigrateAccountBalance idempotency + Peek/Commit no-drain-across-limiters; update the legacy-identity billing tests to track funds under the derived id.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f75c06f139
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| s.keyTokenLimiter.Commit(keyID, inputTokens, outputTokens, inRPS, inBurst, outRPS, outBurst) | ||
| } | ||
| if tl != nil { | ||
| tl.Commit(accountID, inputTokens, outputTokens) |
There was a problem hiding this comment.
Make token limiter admission atomic
When two requests for the same account/key arrive concurrently and the token bucket only has room for one, both can pass the read-only Peek checks before either reaches this Commit because the limiter locks are released between the two phases. The second Commit then ignores a failed AllowN, so the request is admitted without being charged to the token bucket, allowing concurrent traffic to bypass ITPM/OTPM limits. This is fresh evidence after the earlier token-bucket comment: the new peek/commit path removes cross-limiter drain but introduces a non-atomic admission window.
Useful? React with 👍 / 👎.
| if tier == "consumer" { | ||
| if !s.applyKeyRPMLimit(w, r) { | ||
| return |
There was a problem hiding this comment.
Avoid consuming key RPM before account admission
For a key with an rpm_limit, this call consumes from the per-key request bucket before the account/service RPM limiter is checked below. If the account limiter later rejects the same request, the client receives a 429 but the key's bucket has still been drained, so repeated account-level rejections can keep that key throttled even after the account bucket refills; the key and account RPM checks need to be admitted/committed together or the key charge rolled back on downstream rejection.
Useful? React with 👍 / 👎.
| } else { | ||
| // Unknown token — negative-cache to avoid hammering the DB. | ||
| s.storeAPIKeyCache(token, apiKeyCacheEntry{key: nil, cachedAt: time.Now()}) |
There was a problem hiding this comment.
Do not negative-cache transient store errors
This negative-cache path runs after any AuthenticateKey error, not just an unknown key. With Postgres, a timeout or transient query error for a valid API key falls through here and caches nil, so the key keeps receiving 401s until the cache TTL expires even if the database immediately recovers; only cache definite not-found/disabled/expired results, or skip the negative cache on store errors.
Useful? React with 👍 / 👎.
| useEffect(() => { | ||
| if (typeof window !== "undefined") { | ||
| setConsoleKeyId(localStorage.getItem(CONSOLE_KEY_ID_STORAGE)); | ||
| } |
There was a problem hiding this comment.
Reconcile auto-provisioned console keys
For users whose active browser key was created by the existing /api/auth/keys auto-provisioning flow, darkbloom_console_key_id is never written, so this initializes consoleKeyId to null even though darkbloom_api_key points at one of the listed keys. If they rotate or revoke that active key from the new manager, the consoleKeyId === key.id branches do not run, leaving the console on a revoked secret until a later request fails; resolve the active key's id (for example via /v1/key) or store it when auto-provisioning.
Useful? React with 👍 / 👎.
Summary
OpenRouter-style multi-key support: one account can mint many named API keys, each with its own limits. The per-account prepaid balance stays the hard ceiling; per-key limits are soft sub-caps enforced before the ledger reservation.
Key prefix changed from
eigeninference-tosk-db-(existing keys keep working — lookups are by hash).What's included (phases 0–3)
APIKeymodel +List/Get/Create/Update/RevokeByID/Authenticate/RotateAPIKey/TouchAPIKey/KeySpendSince/RecordUsageFull(memory + Postgres, idempotent migrations,usage.key_idattribution).GET/POST /v1/keys,GET/PATCH/DELETE /v1/keys/{id},POST /v1/keys/{id}/rotate,GET /v1/key. Legacy/v1/auth/keyspreserved.KeyTokenLimiter).ApiKeysManager(create-once secret, usage-vs-limit bars, disable/rotate/delete/edit) + proxy routes + client.Hardening (from adversarial verifier review)
usage.key_id.ValidateKeyenforces expiry.legacy:<sha256>) so the raw bearer never reaches balances, ledger references, or logs.scripts/benchmark-*.py(now env-driven). The leaked key has been revoked.Testing
go build,go vet,gofmt -lclean; fullgo test ./...passes (added store/ratelimit/api tests for keys, rotation, spend windows, legacy identity, and top-up refunds).eslint0 errors,vitest162 pass,next buildsucceeds.Notes
Need help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.