Skip to content

feat: multiple API keys per account with per-key limits - #244

Merged
Gajesh2007 merged 5 commits into
masterfrom
feat/multi-api-keys
May 29, 2026
Merged

Gajesh2007 merged 5 commits into
masterfrom
feat/multi-api-keys

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented May 29, 2026 •

Copy link
Copy Markdown
Member

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- to sk-db- (existing keys keep working — lookups are by hash).

What's included (phases 0–3)

  • Store: APIKey model + List/Get/Create/Update/RevokeByID/Authenticate/RotateAPIKey/TouchAPIKey/KeySpendSince/RecordUsageFull (memory + Postgres, idempotent migrations, usage.key_id attribution).
  • Per-key limits: spend cap (none/daily/weekly/monthly) + remaining, expiry, disable, RPM, ITPM/OTPM, model allow-list.
  • Endpoints (Privy-session gated): GET/POST /v1/keys, GET/PATCH/DELETE /v1/keys/{id}, POST /v1/keys/{id}/rotate, GET /v1/key. Legacy /v1/auth/keys preserved.
  • Rate limiting: per-key variable-rate RPM + ITPM/OTPM (KeyTokenLimiter).
  • Console UI: ApiKeysManager (create-once secret, usage-vs-limit bars, disable/rotate/delete/edit) + proxy routes + client.

Hardening (from adversarial verifier review)

  • Fresh-DB Postgres migration ordering for usage.key_id.
  • Atomic, transactional/locked key rotation (no both-active window; concurrency-safe).
  • Per-key spend cap re-checked on provider price top-up.
  • Auth-cache generation barrier; provider-token fallback no longer cached; ValidateKey enforces expiry.
  • Security: unlinked legacy keys now use a non-secret identity (legacy:<sha256>) so the raw bearer never reaches balances, ledger references, or logs.
  • Refund per-attempt provider reservation top-ups on speculative-loser / retry / timeout abandonment (idempotent — no double-refund).
  • Secret scrub: removed a committed plaintext API key from scripts/benchmark-*.py (now env-driven). The leaked key has been revoked.

Testing

  • go build, go vet, gofmt -l clean; full go test ./... passes (added store/ratelimit/api tests for keys, rotation, spend windows, legacy identity, and top-up refunds).
  • Console: eslint 0 errors, vitest 162 pass, next build succeeds.

Notes

  • Touches API-key issuance/validation/storage, so this trips the threat-model-review workflow (T-001) by design.
  • Postgres migrations are written and idempotent; per AGENTS.md prod still runs the in-memory store.

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag @codesmith with what you need. Autofix is disabled.

… 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.
@vercel

vercel Bot commented May 29, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview May 29, 2026 9:02pm
d-inference-console-ui-dev Ready Ready Preview May 29, 2026 9:02pm
d-inference-landing Ready Ready Preview May 29, 2026 9:02pm

Request Review

@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

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

  • TB-001 (Consumer → Coordinator API) — new API key CRUD operations and per-key rate limiter wiring
  • TB-006 (Admin → Coordinator admin API) — new SetKeyLimiters wiring in main.go touches the rate-limiter chain that currently bypasses admin-key requests

Threat Assessment

Threat File Assessment
T-001 API key theft enables consumer impersonation api.ts:391–464 ℹ️ Neutral. New key management calls authenticate via Privy Bearer token (not the localStorage inference key), which is correct scoping. Key secrets (CreatedKey.key) are returned only once by createApiKey/rotateApiKey and never persisted by this code. No regression to the existing SEC-003 open finding.
T-003 Coordinator sees plaintext when sender encryption is off api.ts:391–464 ℹ️ Neutral. Management calls (/api/keys/*) are not inference traffic; no prompt data traverses these paths. Does not affect the encryption-off-by-default posture of SEC-015.
T-038 Missing ReadHeaderTimeout/MaxHeaderBytes main.go:192–202 ℹ️ Neutral. The added block wires rate limiters but doesn't touch http.Server config. SEC-027 remains open and unaddressed.
T-032 Solana mnemonic exfiltration main.go:192–202 ℹ️ Neutral. No billing or KMS code touched.

New Attack Surface Not Covered by an Existing Threat

1. Key rotation invalidation race (api.ts rotateApiKey, TB-001)

rotateApiKey issues a POST /api/keys/{id}/rotate that presumably invalidates the old secret and issues a new one. If the BFF proxy route forwards the response synchronously but the coordinator commits the rotation non-atomically (old key valid until the DB row is updated), there is a narrow window where both the old and new key are simultaneously valid. This is a variant of SEC-012's pattern (non-atomic state transition) but for key credentials rather than billing. Not covered by any existing T-xxx. Recommend verifying coordinator-side rotation is a single transaction with UPDATE … RETURNING or equivalent.

2. Per-key rate limiter bypass for "admin" account identity (main.go:192–202, TB-006)

main.go wires keyRPMLimiter and keyTokenLimiter via srv.SetKeyLimiters. Based on TB-006's description, the admin key bypasses all rate limiters by setting accountID = "admin". If SetKeyLimiters looks up limits by the API key's id field rather than the accountID, admin-scoped calls would correctly hit per-key limits. If it falls through to an account-level check first, the bypass remains. This is a new variation of the existing admin-bypass pattern (TB-006 current limitation) and warrants an explicit unit test or code comment confirming the lookup path. Not an existing T-xxx item.

3. Error message information leakage via keyError (api.ts:413–426, TB-001)

keyError propagates the raw error or message string from the coordinator JSON response directly to the UI. If the coordinator returns error messages that distinguish between "key ID not found", "key disabled", or "key expired", a consumer with UI access could probe key IDs. This is a minor variant of the existing TB-001 timing-attack concern (API key enumeration via store lookup) but at the error-body level rather than timing. Low severity given IDs are UUIDs; flagging for awareness.


Open Findings Resolved

None — 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 expires_at, disabled, and rotation support, but the finding itself (keys not re-bound to Privy identity) is not closed since the existing single inference key in localStorage is unaffected by the new multi-key surface.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread coordinator/api/server.go
ctx = context.WithValue(ctx, auth.CtxKeyUser, user)
}
} else {
accountID = store.LegacyAccountID(token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread coordinator/api/server.go Outdated
Comment on lines +347 to +350
// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread coordinator/api/server.go
s.keyTokenLimiter.Commit(keyID, inputTokens, outputTokens, inRPS, inBurst, outRPS, outBurst)
}
if tl != nil {
tl.Commit(accountID, inputTokens, outputTokens)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread coordinator/api/server.go
Comment on lines +1813 to +1815
if tier == "consumer" {
if !s.applyKeyRPMLimit(w, r) {
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread coordinator/api/server.go
Comment on lines +1697 to +1699
} else {
// Unknown token — negative-cache to avoid hammering the DB.
s.storeAPIKeyCache(token, apiKeyCacheEntry{key: nil, cachedAt: time.Now()})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +59 to +62
useEffect(() => {
if (typeof window !== "undefined") {
setConsoleKeyId(localStorage.getItem(CONSOLE_KEY_ID_STORAGE));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Gajesh2007
Gajesh2007 deleted the feat/multi-api-keys branch May 29, 2026 21:18

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — f75c06f1 Deployed May 29, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — f75c06f1 Deployed May 29, 2026 by vercel[bot]
Preview – d-inference-landing — f75c06f1 Deployed May 29, 2026 by vercel[bot]
benchmarks — f75c06f1 Deployed May 29, 2026 by Gajesh2007 via E2E Benchmarks #498
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants