Skip to content

feat(proxy)!: forward the caller's own provider key, and add real account auth - #70

Closed
OsherElhadad wants to merge 10 commits into
stack/1-docsfrom
stack/2-credentials-and-auth
Closed

OsherElhadad wants to merge 10 commits into
stack/1-docsfrom
stack/2-credentials-and-auth

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Stacked on the PR below.

Breaking, and deliberate. The hosted proxy no longer injects a server-held upstream key. setUpstreamAuth forwards 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, which copyHeaders already stripped before forwarding. Claude Code sets it via ANTHROPIC_CUSTOM_HEADERS. Bob cannot send a custom header at all — its fetch() builds the header set from internal state, and the documented headers setting is MCP-server-only — so it is identified by sha256(BOBSHELL_API_KEY), bound once via POST /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 process ANTHROPIC_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/verify picks the flow from the stored code's purpose, 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_FROM must 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.

Osher-Elhadad added 4 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]>
Osher-Elhadad added 6 commits August 17, 2026 06:50
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant