Repository navigation
feat(proxy)!: forward the caller's own provider key, and add real account auth - #78
Merged
OsherElhadad merged 10 commits intoAug 17, 2026
Conversation
added 10 commits
August 16, 2026 19:19
…the spend cap The hosted proxy injected a SERVER-HELD upstream key for every tenant, which bills every user's traffic to one account. It now forwards the credential the caller's agent already sends, so each user's spend lands on their own provider account. Identity moves out of the auth slot, because the auth slot is now the caller's key. `x-context-guru-token` carries the token, and copyHeaders already strips every x-context-guru-* header before forwarding, so it cannot leave the box. A token presented in an auth slot is still accepted — some tools have nowhere else to put it — and is scrubbed on the way out, recognisable because only our tokens are shaped cg_live_ + 26 characters. Bob (BobShell) can carry no header of ours: its client builds Content-Type, User-Agent, Authorization, x-instance-id and x-team-id itself, and its `headers` setting applies to MCP servers only. So it is identified by sha256 of the provider key it already sends, bound once via POST /api/me/agent-key. Only the digest is stored; the key is never inserted, selected or logged. Agent-family detection is unchanged — it reads the User-Agent. A caller with no credential of their own gets a 401. That is the one thing that must never become a fallback onto whatever key the box holds. Server-held keys remain supported as an explicit per-upstream `key_env` — the eval-containers gateway and local single-tenant use — and are no longer required to boot. Upstreams stay an allow-list of operator-configured names. The LLM-calling components now spend the caller's credential too: incomingModel prefers it, the "config"-source cheap model is withheld in hosted mode, and a tenant config that pins a model with no api_key no longer falls back to the process's ambient provider key. All three fail OPEN — no credential means no client and the component degrades, never an error. The monthly cap goes entirely: monthly_cap_usd, the 402 path, the spend cache, the Settings meter, the manager's Set cap button, the Prometheus gauge and the Grafana panels. It only existed because one shared key was being spent. Cost tracking and display stay. Signed-off-by: Osher-Elhadad <[email protected]>
…econd factor Registration and sign-in stop being "paste your proxy token". An account is now an email address, a password, and a 6-digit code we mail to that address. Registration is two phases: POST /api/register creates the account UNVERIFIED with no token and no session, and mails a code; POST /api/verify spends it, marks the address verified, mints the first cg_live_ token and opens the session. Sign-in is the same shape — POST /api/login checks the password and mails a fresh code, and only /api/verify sets a cookie. Phase one never issues a session, so knowing a password is not by itself a signed-in browser. /api/verify infers which flow it is from the pending code's own purpose rather than from anything the client sends, so a login code cannot be spent on the branch that mints a token. Passwords are argon2id (64 MiB, 3 passes, 2 lanes, per-account 16-byte salt) in PHC string format, so the parameters travel with the hash and can be raised later without invalidating an existing password. Comparison is constant time, and the verify runs against a random decoy hash for an unknown address so "no such account" and "wrong password" cost the same ~50 ms and return the same message. The 6-digit code is only a factor because of three bounds, all of them here: a 5-minute expiry, a cap of 5 wrong guesses after which the code is DESTROYED rather than refused, and rate limits of 5 password attempts and 10 code submissions per minute charged against both the email address and the client address. Issuing a code REPLACES the pending one — (tenant_id, purpose) is the primary key — so a resend narrows the valid set instead of widening it. dash_sessions grows label/user_agent/ip/last_seen_at and gains a derived public handle, so several machines can be signed in at once and the owner can see and revoke one of them (GET/DELETE /api/me/sessions). last_seen_at is stamped at most once a minute per session, so reading the dashboard is not a writer on the control database. Mail goes out through stdlib net/smtp, no dependency: STARTTLS whenever the relay advertises it, and a failed negotiation aborts the send rather than continuing in the clear. Host, port, from, HELO and any credential are read from the environment per send. With nothing configured, registration answers 503 naming the missing variable — a registration whose code went nowhere is worse than one that refuses. CG_MAIL_DEV_SINK is an explicit, documented escape hatch for a deployment with no relay. Self-registration flips to open by default. Both halves of the old reason to keep it closed are gone: an account no longer spends the operator's key (users forward their own), and "nobody proves they own the address" — which the old comment named as the missing control — is exactly what the mailed code now supplies. Proxy tokens are untouched and remain how agents authenticate to the proxy. An account that has a password can no longer exchange a token for a browser session; one that has none still can, because it has nothing else. Schema v2 is purely additive: every new column has a DEFAULT, so an existing tenant migrates to "no password, unverified" and keeps working. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]> # Conflicts: # docs/get-started/connect-ibm-service.md
Union both features. The per-tenant monthly spend cap stays deleted: none of monthly_cap_usd, MonthlyCapUSD, spendCache or spendgate.go come back, and the dangling references the cap removal left behind (a Grafana row description, two comments in proxy/tenancy.go, one in proxy/promexport.go) are cleaned up too. Migrations: both branches shipped a migration they each called "v2". They are now two sequential entries — tenant_agent_keys is v2, the accounts/email_codes migration is v3 — in that order because a database written by a build of this integration branch is already at v2 with tenant_agent_keys, and reordering would leave those files never running the accounts step. The schema version is len(migrations), so it follows automatically. Covered by two new tests: a fresh database has every table and column from both branches, and every migration also applies in sequence to a database that stopped at v1 or v2. Register keeps its (*Tenant, string, error) signature and email-auth's split into newTenant + insertTenant, so the token-first flow and RegisterAccount share one list of defaults. insertTenant writes password_hash and email_verified_at but not monthly_cap_usd, and returns error. tenantCols and scanTenant gain the account columns LAST, in the same order, with no cap column between capture_content and max_rows. The package doc comment states both properties: the tenant token is minted by us, the provider key belongs to the caller and is never stored, so every secret in this database is a derived digest — sha256 of a token, of a session cookie, of an agent's provider key, argon2id of a dashboard password, sha256 of a 5-minute email code — and the only value ever displayed is a token's 8-character prefix. docs/hosted.md documents both: the mail path and the password + mailed-code sign-in, with no cap and no claim that we hold anyone's provider key. Fixes the section numbering that shifted when the email-path step was inserted, the two places that still said there was no mail path and therefore no email verification, and the dashboard table's token-only registration description. Also fixes the mojibake the credential-passthrough branch committed into tenant/tenant.go, where two em-dashes had been round-tripped through latin-1. Signed-off-by: Osher-Elhadad <[email protected]>
Resolving the connect-ibm-service.md conflict took the credential branch's version wholesale, because its facts were current and the prose branch's were stale. That discarded the prose branch's anchor fix: use-with-claude-code.md's 'The one-liner' heading had become 'Steps', and hosted.md was repointed while this file was not. mkdocs build --strict catches it; the merged tree did not build until now. Both docs branches passed on their own - taking one side of a conflict wholesale is what lost it. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit df749b5)
…e median The regression this guards - content redaction on the request goroutine, ~53ms - is unconditional work, so it lands on every sample including the fastest. Contention only ever makes a sample slower. The minimum is therefore the statistic least polluted by the machine while staying fully sensitive to the defect. The median gate failed roughly one run in three on a loaded box, with the package run alone. A gate that reports the machine rather than the code gets ignored exactly when it is right. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit a2b665c)
A fixed 5ms budget cannot mean the same thing at both ends of this machine's range. Idle, a fake-upstream request settles near 1-2ms; with the suite saturating 16 cores its own median was 331ms. The gate was reporting the machine, failing about one run in three with nothing wrong. Budget is now max(5ms, 10% of the measured baseline), which catches the ~53ms regression at any baseline while contention that slows both handlers equally cannot trip it. The median stays the statistic: the minimum was tried and is worse, being one unaveraged sample - in one run the paired medians differed by 1.27ms where the paired minima differed by 8.13ms. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 3aad033)
The limiter is charged before the argon2 verify, deliberately, because 64 MiB per attempt is itself an amplifier. So the attempts the loop is allowed each pay a full KDF, and on a contended machine those can outlast the limiter's own one-minute window - at which point the earliest attempts have aged out and the bound correctly did not fire. From inside the test, "not limited" and "the window expired underneath us" are indistinguishable, and failing on the second is a test reporting the machine rather than the code. It now skips with the elapsed time named when the loop outran the window, and still fails outright when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 26e8e50)
… conclude Same root cause as the sign-in limiter test: each registration the loop is allowed hashes a password with argon2 at 64 MiB, so on a contended machine the allowed attempts outlast the limiter's one-minute window and age themselves out. The bound then correctly does not fire, which from inside the test looks exactly like the bypass it is checking for. It now skips with the elapsed time named when the loop outran the window, and still fails when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 0531c36)
…ter tests The form's own minlength=12 was refusing registration before the server saw it. Server, form and hint now all say 8; the mailed code, the 5-attempt cap, the per-email and per-address rate limits and a 64 MiB argon2id hash are what bound online guessing. The limiter tests are timed because each attempt they are allowed pays a full KDF, so on a loaded machine they outlast the one-minute window they exist to exhaust - which reads as a bypass when it is not. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
merged commit Aug 17, 2026
346884d
into
feat/hosted-tls-and-agent-compaction
10 checks passed
OsherElhadad
added a commit
that referenced
this pull request
Aug 17, 2026
…servability (#79) Lands the nine reviewed PRs (#69, #78, #71-#77) on main. Caller-pays credentials: each request's own provider key is forwarded upstream and a request without one is refused, so no account spends the operator's credential. The per-tenant spend cap goes with it. Email+password accounts with a mailed second factor, 14 confirmed security findings fixed with a failing test each, the rewrite path down from 15.6ms to 6.85ms per request with byte-identical output over 1,868 real captured requests, structured logging with credential scrubbing into Loki, request metadata and a Usage view, a redesigned dashboard, user feedback, full manager control over accounts, and Bob working through the proxy for the first time. Squashed because main carries #67 the same way, and because the nine merge commits GitHub generated for the stack carry no sign-off of their own; every authored commit in them does. The per-PR history stays on feat/hosted-tls-and-agent-compaction and in #69/#78/#71-#77. Signed-off-by: Osher-Elhadad <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Nov 16, 2026
… out of the text ratio (#1176) Pin the accountant library to v0.1.2. It leaves thinking signatures and redacted thinking data out of the text ratio (accountant#73, accountant#76), and also brings accountant#74, #75 and #78. Behavior change: booked savings. Thinking signatures are about 20% of the message bytes and Claude bills them as about 0 tokens, so they diluted the tokens-per-byte ratio from about 0.41 to 0.32: removals booked about 1.12 Claude tokens per counted token, where the measured truth is 1.51. Now the preset, sweep, searchfold and textclean figures rise, by about 1.5 to 2.5 points of preset share on a laptop. Turn it off: revert this one dependency line. Owner's yes, 2026-11-16/17, in the integrator session: "1176 yes". Data dependence: none. go.sum: the 2 v0.1.2 lines come from sum.golang.org (the accountant repo is public); v0.1.2's go.mod is the same as v0.1.1's. Reviews: 1 offload review round (Bob backend, GLM did not answer): both approve at 6da3e1c, which is the PR head. Signed-off-by: DAVID AMID <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Stacked on the PR below.
Breaking, and deliberate. The hosted proxy no longer injects a server-held upstream key.
setUpstreamAuthforwards the caller's own credential untouched and scrubs only our token from it; a request with no provider key gets 401 before the body is read, rather than silently spending the operator's credential. The per-tenant monthly spend cap is deleted with it — file, metric, flag, Settings meter, manager column — because an account spending its own credential needs no cap from us.The tenant token moves to
x-context-guru-token, whichcopyHeadersalready stripped before forwarding. Claude Code sets it viaANTHROPIC_CUSTOM_HEADERS. Bob cannot send a custom header at all — itsfetch()builds the header set from internal state, and the documentedheaderssetting is MCP-server-only — so it is identified bysha256(BOBSHELL_API_KEY), bound once viaPOST /api/me/agent-key. That key is hashed on arrival and never stored, logged or echoed.A path-prefixed token (
/t/<token>) was rejected as Bob's fallback despite being the smaller diff: it would put a credential in nginx access logs.Also closed: a tenant's own
model:block could fall back to the processANTHROPIC_API_KEY, reintroducing the operator credential through the config door after the front door was shut.Account auth. Email + password (argon2id, 64 MiB / t=3 / p=2, PHC-formatted so parameters can be raised later without invalidating passwords) plus a 5-minute emailed 6-digit code as a second factor. Phase one issues no cookie.
/api/verifypicks the flow from the stored code'spurpose, never from client input, so a login code cannot be spent on the branch that mints a token. 5 attempts per code, then the row is deleted — that, not the 20 bits of entropy, is what makes the code a factor. Rate limits are charged against both the email and the client address, applied before the argon2 verify, and use a rolling window rather than a sticky lockout (a sticky lock is a denial of service you can aim at a colleague by typing their address).Mail is honest about its state: the relay accepts on port 25 with STARTTLS and full certificate verification, but inbox delivery is unconfirmed and
CG_SMTP_FROMmust be a routable domain or the code will be filtered. With mail unconfigured, registration answers 503 naming the variable rather than stranding a user with a code nobody received.Verified:
go test -race ./...green. Tests prove the caller key reaches the upstream, the server key is not used even when its env var is set, two tenants keep separate credentials and stores, and no password, code or hash appears in any log line.Replaces #70, which GitHub auto-closed when its base branch (
stack/1-docs) was deleted on merge of #69. Same branch, same commits, retargeted to the base that now carries #69.