cred402/BUILD-LOG-2026-10-24.md
caelum0x 086381d507 feat(gateway): make rate limiting org-scoped and plan-tiered
Rate limiting was per-API-key, so an org's `plan` field was decorative — a
free-plan org that minted 5 teammate keys got 5x the effective request
budget of a single-key free org. Org-scoped keys now share ONE rate-limit
bucket per org (`org:<id>`), sized by plan (free=120, pro=1000,
enterprise=10000 per window); orgless credentials (platform admin key,
anonymous dev identities) keep the prior per-identity behavior unchanged.

Adds GET /v1/orgs/usage (bucket status + total request count across an
org's keys) and a shared-bucket meter in the Orgs self-service console
panel.

Verified against a running dev server: 130 concurrent requests on a
free-plan org's owner key yielded exactly 120 successes + 10 real 429s,
and the org's teammate key immediately inherited the same depleted
remaining count (proving the bucket is shared, not per-key). A parallel
enterprise-plan org was unaffected. tsc + frontend build clean, 450/450
existing tests unchanged.
2026-10-24 00:40:11 +03:00

11 KiB

Build log — 2026-10-24

Continuing the 15-item backlog in STRATEGY-2026-10-23.md. Each entry below was run against a live local server (node --import tsx api/server.ts) with real curl calls and real issued keys before being written down — not just typechecked.

Round 1

14. Webhook delivery dashboard — disable/enable + manual replay

Finished the in-progress-uncommitted work from the end of the prior round: lib/gateway/webhooks.ts now logs every delivery (success or exhausted-retry failure) WITH its original payload, so a failed delivery can be manually replayed later (redeliver(), POST /v1/webhooks/deliveries/:id/retry) without waiting for the protocol event to fire again. Subscriptions can be disabled (DELETE /v1/webhooks/:id) and re-enabled (POST /v1/webhooks/:id/enable). New frontend/src/components/Webhooks.tsx (extracted out of Developer.tsx) renders the delivery log with a per-subscription filter, 5s auto-refresh, and a retry button on failed rows.

Verified for real: full tsc + vite build clean, 450/450 existing tests unchanged, exercised POST/DELETE/enable/deliveries against a running dev server with curl, and ran WebhookService directly against a local HTTP receiver that rejects-then-accepts to confirm a failed delivery logs correctly and a manual replay flips it to delivered.

13. Real multi-tenant org / API-key scoping depth

Found a genuine, unaddressed gap: lib/gateway/api_keys.ts had no concept of who a key belongs to beyond its own scopes — ANY valid admin key (or, worse, in dev mode with CRED402_AUTH_REQUIRED=false, no key at all) could see or mutate every API key, webhook, and resource in the process. For a protocol onboarding real paying integrators (the owner's actual target — businesses/small teams, not a single operator), that's not multi-tenant at all; every customer would be able to see every other customer's credentials.

Built a real org layer:

  • New lib/gateway/orgs.ts — OrgStore: { id, name, plan, created_at }.

  • lib/gateway/api_keys.ts — ApiKeyRecord/issue() now carry an optional org_id (undefined only for the platform bootstrap/admin key — deliberately orgless, it's the operator, not a tenant) and a request_count incremented on every successful verify(), so org usage is sum(request_count) over its keys with zero new counters to wire up. listByOrg() + get() added.

  • lib/gateway/index.ts — wires OrgStore into Gateway. Also fixed a real pre-existing testability gap in authenticate(): when authRequired=false (dev), a presented API key was previously ignored entirely (any key, valid or not, fell through to anonymous ip: identity with NO scope check) — now a VALID presented key is resolved onto AuthContext AND still scope-checked, while a missing key still never blocks (dev's "never blocks" contract is preserved, just no longer silently bypasses scope checks for a key that WAS presented). This is what makes the org self-service routes below testable against a real local dev server with real issued keys, identically to how they behave once CRED402_AUTH_REQUIRED=true in production.

  • api/v1/router.ts — Ctx now carries auth: AuthContext (every route handler can see the calling key). New routes:

    • POST /v1/orgs (admin) — operator onboards a new org + its first ["read","write"] owner key, ONCE.
    • GET /v1/orgs (admin) — operator's full org list.
    • GET /v1/orgs/:id (admin) — operator inspects one org + its keys.
    • GET /v1/orgs/me (read, self) — the calling key's own org + sibling keys.
    • GET /v1/orgs/keys (read, self) — same, keys only.
    • POST /v1/orgs/keys (write, self) — mint a sibling key for a teammate, scopes capped to a SUBSET of the caller's own scopes (no self-escalation — a read-only key can never mint itself a write key).
    • DELETE /v1/orgs/keys/:id (write, self) — revoke a key, but ONLY if it belongs to the caller's own org_id — a different org's valid key gets a 404, not the target key's real state. This is the actual tenant boundary.

    Route-ordering gotcha caught by actually running it, not by re-reading the diff: the router matches path patterns in file order with no specificity ranking, so the literal GET v1/orgs/me / GET v1/orgs/keys had to be listed BEFORE the wildcard GET v1/orgs/:id — otherwise :id swallowed "me" and "keys" as org ids and 404'd. Caught via the live curl flow below, not by inspection.

  • Frontend: frontend/src/api.ts adds createOrg/listOrgs/getMyOrg/ mintOrgKey/revokeOrgKey. New frontend/src/components/Orgs.tsx — two panels: operator onboarding (admin, console's own zero-key dev calls) and a self-service panel where you paste an org's own secret (never the admin key) to see its profile, mint teammate keys, and revoke keys — exactly the two credential tiers a real integrator uses. Wired into Developer.tsx.

Verified for real, end to end, against a running dev server (not just typechecked): onboarded two orgs (Acme, Globex) with the admin-equivalent dev-mode call; Acme self-minted a read-only teammate key using ONLY its own secret (no admin key); the teammate key's attempt to self-mint a write key was rejected 403 (requires 'write' scope); Globex's own valid key tried to revoke Acme's teammate key by id and got a real 404 (cross-tenant isolation); Acme revoking its OWN key succeeded; Globex's non-admin key hitting the admin-only GET /v1/orgs/:id on Acme's org was correctly rejected 403 after the dev-mode scope-check fix (it had actually LEAKED before the fix — see above). Full tsc --noEmit + cd frontend && npm run build clean, 450/450 existing tests unchanged (zero behavior change for keys without org_id, fully backward compatible).

Remaining from the 15-item backlog (not started)

  1. MCP server directory / Claude Desktop extension listing (manifest + docs).
  2. Guided wallet-connect → multichain-link → provisional-score onboarding UI (Onboard.tsx already covers register→stake→verify→list — re-check against the backlog's exact ask before rebuilding).
  3. Public /disputes or /trust page (Trust.tsx/Disputes.tsx already exist — check coverage first).
  4. Go port of the relayer/proof-service.
  5. Python ML risk/fraud scoring variant.
  6. Python/Go/Rust SDK cold-start retry (TS SDK done 2026-10-23).

Also not done, flagged for a future round: per-org USAGE page in the Orgs.tsx self-service panel (request_count is already tracked server-side per key — just needs a chart/table), and org-scoped RATE LIMITS (today rate limiting is per-identity i.e. per-key, not per-org — a free-plan org with 5 keys gets 5x the effective rate limit of a single-key org, which isn't billing-correct for a real plan field).

Round 2 (same day): closed the org-scoped rate-limit follow-up

Picked up the two flagged follow-ups from round 1 together, since they're the same underlying gap: rate limiting was per-API-KEY, not per-org, so a plan field was decorative — a free-plan org that minted 5 teammate keys got 5x the effective request budget of a single-key free org, and there was no way for an org to see how close it was to its limit.

  • lib/gateway/rate_limit.ts — RateLimiter.check()/new peek() now take an optional per-call capacityOverride, so ONE shared limiter instance can serve plan-tiered buckets (previously capacity was fixed at construction, which only worked for a single global limit). peek() reads a bucket's current refill state without consuming a token, for status displays. Fully backward compatible — existing callers that omit the override behave exactly as before.
  • lib/gateway/orgs.ts — new PLAN_RATE_LIMITS/planRateLimit(): free 120/window (matches the pre-org platform default so a single-key free org is never worse off than before orgs existed), pro 1,000, enterprise 10,000.
  • lib/gateway/index.ts — Gateway.rateLimitKeyFor(auth): org-scoped keys all bucket on org:<org_id> (ONE shared bucket per org, sized by its plan) instead of each key's own key:<id> identity; orgless credentials (platform admin key, anonymous dev ip: identity) keep the old per-identity behavior unchanged. enforceRateLimit() gained an optional capacity param (defaults to the platform-wide config value — existing single-arg call sites, including the ones in test/gateway_customer_flow.test.ts, are untouched). New Gateway.orgUsage(orgId) returns the org's live rate-limit bucket state (via peek, no token consumed) plus its total request count summed across all its keys.
  • api/v1/router.ts — handle() now calls rateLimitKeyFor(auth) before enforceRateLimit, so every route (not just /v1/orgs/*) gets org-scoped limiting for org-scoped keys. New self-service route GET /v1/orgs/usage (read scope, same org-ownership gate as /v1/orgs/me).
  • Frontend: frontend/src/api.ts adds OrgUsage/getOrgUsage(). Orgs.tsx's self-service panel now loads usage alongside the org profile and renders a shared-bucket meter (reusing the existing .meter/.bar/ .fill styling from Agents.tsx/CreditPool.tsx, no new CSS) plus a "Total requests" stat, with a caption explaining the bucket is shared across the org's keys.

Verified for real, against a running dev server (not by inspection): onboarded a free-plan org (Acme) and an enterprise-plan org (Globex), minted Acme a teammate key, then fired 130 CONCURRENT requests on Acme's OWNER key alone — exactly 120 succeeded and the other 10 got real 429s with Retry-After, matching the free plan's 120 cap. Confirmed the bucket is genuinely SHARED (not per-key, which is the actual bug being fixed): the teammate key's very next request came back with the SAME depleted X-RateLimit-Remaining the owner key had just left it at, not a fresh 120. Confirmed Globex's enterprise org was completely unaffected by Acme's exhaustion (independent bucket, 10,000 cap, 9999/9998 remaining). Confirmed GET /v1/orgs/usage reports total_requests correctly as the sum of request_count across an org's keys. Full tsc --noEmit clean on both the backend and frontend/, cd frontend && npm run build clean, 450/450 existing tests unchanged throughout (zero behavior change for the non-org/default rate-limit path).

Remaining backlog (unchanged from round 1, still not started)

  1. MCP server directory / Claude Desktop extension listing (manifest + docs).
  2. Re-check Onboard.tsx against the backlog's exact ask before rebuilding.
  3. Re-check Trust.tsx/Disputes.tsx against the backlog's exact ask.
  4. Go port of the relayer/proof-service.
  5. Python ML risk/fraud scoring variant.
  6. Python/Go/Rust SDK cold-start retry (TS SDK done 2026-10-23).