Skip to content

fix(security): enforce the hosted capture refusal, per-tenant billing and quotas, and close CSRF - #75

Merged
OsherElhadad merged 64 commits into
feat/hosted-tls-and-agent-compactionfrom
stack/7-security-isolation-and-control-plane
Aug 17, 2026
Merged

OsherElhadad merged 64 commits into
feat/hosted-tls-and-agent-compactionfrom
stack/7-security-isolation-and-control-plane

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Stacked on the PR below. The second security review's findings — tenant isolation and the web surface — plus control-plane fixes. Every fix has a test that failed before it.

CONTEXT_GURU_DUMP / CONTEXT_GURU_CAPTURE were documented as forbidden in hosted mode but not enforced. Booting hosted with either set produced no error and no warning, and wrote two tenants' pristine, unredacted bodies to one process-wide file with no tenant column — bypassing both per-tenant capture consent and the redactor. Now a startup refusal naming the variable, before any database or socket opens. Verified by booting the real main() in a subprocess, because a startup refusal has no in-process observer and testing an extracted helper would prove the helper works while leaving it unwired.

cg_llm_cost_usd was the delta of a process-global counter, so any other tenant's cheap-model call inside your request's lifetime was charged to your row, and propagated into the spend figure on each Settings page and into Prometheus. Also a low-bandwidth side channel for inferring others' activity. The usage sink now rides on the request context, the one plumbing point that already reaches every model call. Observe mode leaked the same way and now lands on no row.

No per-tenant row quota was actually in force. The flag defaulted to 0, the per-tenant field defaulted to 0, and the unit set neither, so the quota pass returned immediately and the byte rule deleted oldest-first globally — one tenant evicting everyone's history. The byte rule also ran before the quota pass, so the comment claiming a heavy user could not evict others was true only of the disk rule. Non-zero default, set in the unit, reordered quota → age/bytes → disk, with page reclamation without which the reorder is cosmetic.

/compact and the Bob catch-all authenticated then ran unmetered — the full pipeline over a body up to 32 MiB with no limiter. Demonstrated: limiter at 1/min, chat refused the second request while /compact served 20 of 20.

CSRF rested entirely on SameSite=Lax, whose unit is the registrable domain — so any colleague's host under the same domain is "same site". A text/plain form post (no preflight) reached the JSON decoder and could mint a token or force a sign-out. Now an Origin check in the shared decoder: present-and-different rather than required-and-matching, so non-browser callers are unaffected.

/api/register was an account-enumeration oracle — 409 for a verified address, 201 for an unknown one — while /api/login and /api/verify had been carefully built non-enumerating with a decoy argon2 hash. Both answers are now identical, and the owner gets a "someone tried to register your address" notice with no code.

incomingModel was a second credential exit, contradicting the comment claiming one place decides what leaves the box. Also fixed: clickjacking (frame-ancestors/base-uri/form-action do not inherit from default-src), the browser Cookie forwarded to the Bob upstream, and unmetered agent-key guessing — the difference between "unbound key" and a served request was a free impersonation oracle at 30 r/s.

One metrics trap avoided: the new no_provider_key refusal reason partitions auth rather than adding to it, because the SLO dashboard divides an unlabelled refusal total — double counting would have inflated the error-rate SLI on the very panel this migration is judged by.

Verified clean by live probing: query scoping across all 18 routes including crafted ?tenant=, SSE partitioning including Last-Event-ID replay, the content boundary (a manager is correctly refused transcript text under both ?tenant=<id> and ?tenant=*), /expand ownership, session namespacing, XSS across 176 KB of app.js, routing specificity, cookie flags, and the /stats gate.

Osher-Elhadad added 30 commits August 16, 2026 18:48
…st correlation

The proxy had slog calls but no logging: no handler was ever installed, so DEBUG
went nowhere, and the only per-component lines came from metrics.Slog at INFO with
neither tenant nor session on them — several lines per request, burying the request
itself.

Four things:

- internal/logging owns the level/format/sink decision (CG_LOG_LEVEL,
  CG_LOG_FORMAT, CG_LOG_FILE) and installs the default handler. Local use needs no
  configuration: text on stderr. CG_LOG_FILE adds a JSON sink for a log shipper and
  is the ONLY thing that makes logs leave the box. CG_LOG_PLAIN=1 opts out
  entirely, swapping in the stdlib's own text handler.

- Credentials are scrubbed on the way OUT, so a careless call site added later
  cannot leak one — which matters more now that the caller's own provider key
  flows through request handling. A ReplaceAttr covers attribute values (including
  the ones baked in by Logger.With) and a wrapper handler covers the message.
  The patterns are the ones dash already used: they moved to internal/redact and
  dash/redact.go delegates, because two copies of a credential denylist is one
  copy that goes stale.

- Every line of one request's lifecycle carries the tenant id — never its token —
  and, from the point apply resolves it, the session. The logger travels in the
  request context, which is why no component signature changed.

- The lines say what was DECIDED, not just what happened: one INFO per request,
  and at DEBUG the cached-prefix boundary, the bypass gate, the expand loop's
  resolved-against-unresolved counts, why a stream had to be buffered, and one
  line per component with its verdict, token delta and the gates that turned
  candidates away. Those gate names and counts are read off the same Report.Gates
  map /stats sums into components.<name>.gates, so a log line and the metric
  cannot disagree.

Signed-off-by: Osher-Elhadad <[email protected]>
The default hosted pipeline ([format, dedup, failed_run, cmdfilter, extract,
cachesplit], sync) spent most of its CPU re-doing work it had already done. A
CPU profile over 24 real captured Claude Code requests (median 600 KB, 71
messages) attributed the rewrite path as: normalize 44%, wireBreakpoints 22%
(and it runs twice per request), a full transcript deep-clone per component 10%.
None of that is component work.

Six changes, each measured on that capture, output verified byte-identical:

  - wireBreakpoints walked the body with seven `#.field` gjson queries, each a
    full re-scan that squashed every matched array. Now one pass over the
    top-level object, with a substring prefilter before any structural parse
    (neither spelling can be a field if "cache" is not even in the bytes), and
    the post-rewrite cap re-count only when something actually changed — an
    untouched body still carries exactly the inbound count.
  - The pipeline deep-cloned the whole transcript per component for its revert
    snapshot. It now keeps ONE snapshot and re-clones only the messages a
    component changed; a revert re-establishes an independent copy, because
    req.Input then aliases the one we were holding. Every snapshot entry is
    still exactly one clone of a live message, so fidelity is unchanged — two
    new tests fail without either half.
  - The lossless round-trip check (two unmarshals into `any` plus a DeepEqual)
    ran for all ~70 messages up front; it only matters for a message a component
    changed, so it is computed on demand.
  - Every normalized message was marshalled twice: once in normalize, once for
    the count-change rebuild path only summarize takes. The rebuild now reads
    slot.pre.
  - normalize called encoding/json.Unmarshal on a type that implements
    json.Unmarshaler, so encoding/json contributed nothing but a checkValid
    re-scan of bytes gjson had already parsed — 40% of the unmarshal cost. It
    calls UnmarshalJSON directly, and fetches each message's `content` once.
  - ContentKey is memoized (like internal/tokens.Count): every offloader asks
    skipReduce about every candidate, so one request normalized and sha256'd the
    same tool output three or four times. Keyed by (len, hash) — a wrong key
    here would mean a wrong stashed original, unlike a stale token count.

Measured, 24 real captured requests, same test code both sides:

  end-to-end        552.6 ms -> 253.3 ms   (-54%)
  one median req     15.6 ms ->   6.9 ms   (-56%), 9554 -> 3232 allocs (-66%)
  per-component duration_ms, pipeline total  1.75 ms -> 1.06 ms  (-39%)
  live /compact through the proxy, 73 requests, median 37.1 -> 19.2 ms
  live LLM calls through the gateway, cg_added_ms_avg 37.1 -> 25.8

Byte-identical output verified over 373 real captured requests (73
Terminal-Bench + 300 SWE-bench) via a golden hash of every rewritten body, with
the hashes recorded on the unmodified code. Fail-open, never-worse and
reversibility are untouched; the #32 replay test still puts breakpoints on the
wire for 72 of 73 requests.

What did NOT help and was reverted: prefiltering normalize's content walk on a
"tool_result" substring (no measurable change — real user messages nearly all
carry one).

Signed-off-by: Osher-Elhadad <[email protected]>
Grafana stores no logs, so something had to. Loki wins on the property that matters
more than any feature comparison: it is read through the Grafana already running on
this box, so a latency spike on the service dashboard is one click from the log
lines for the same tenant and the same minute — one thing to secure, back up and
explain. Its storage model is also the same shape as the Prometheus beside it: a
single binary indexing a handful of labels, chunks on the local filesystem, one more
container. Elasticsearch would search better and wants a JVM and gigabytes of RAM on
a box whose job is serving agent traffic; ClickHouse is a better analytical store
than reading logs is an analytical problem; files and grep — kept as the fallback —
cannot answer "every line for this tenant's session over three days" without a human
and an ssh session, which is the question this exists for.

- `install.sh grafana` now brings up all four containers, loopback only, and installs
  the logrotate snippet. `grafana-status` checks Loki's readiness (not just its port
  — it answers while the ingester still rejects pushes), that the log file exists,
  that lines actually arrived in the last ten minutes, and which tenants Loki has
  seen. That last set of checks exists because a healthy promtail in front of an
  empty log directory renders an empty dashboard with no error anywhere.

- The proxy never talks to Loki. It writes the journal always and CG_LOG_FILE as
  JSON when set; promtail owns delivery and remembers its position. A shipper inside
  the process being debugged loses exactly the logs you need when that process is
  what is going wrong.

- `tenant` and `level` are Loki labels; `session` and `component` deliberately are
  not — a session label would mint one stream per agent conversation and eventually
  take the index down. They are read out of the JSON at query time, which is what
  the dashboard's two text fields do.

- The logs dashboard filters by tenant, session, level and component, and its
  gate table answers "the component did nothing and I cannot tell why" off the same
  Report.Gates map /stats sums.

Single-tenant proxies log tenant="local" rather than an empty string, which promtail
would drop — leaving the selector empty for exactly the people running this locally.

Signed-off-by: Osher-Elhadad <[email protected]>
A request row recorded what happened to a request but nothing about what the
request ASKED for, so the levers that explain a cost were invisible: reasoning
effort, thinking budget, sampling parameters, and — the one this project exists
to reason about — where the prompt-cache breakpoints sat.

Capture, normalized across both dialects (Anthropic `output_config.effort` /
`thinking.{type,budget_tokens}` / object `tool_choice` / block `system`; OpenAI
`reasoning_effort` / `max_completion_tokens` / string `tool_choice`), plus the
provider's stop reason off the same response bytes the token tiers come from.

Real columns, not a JSON blob: every field is either GROUPED BY in an aggregate
or shown on the row, so a blob would put json_extract() in the middle of every
aggregate and give free text somewhere to hide from the redactor. The sampling
columns are NULLABLE because "unset" and "0" are different facts and 0 is a
legitimate value — a sentinel would make a deterministic request read as an
unspecified one.

Client-supplied metadata is attacker-influenced input, so each text field passes
through a credential-shape check and an identifier-shape bound BEFORE the insert,
never on read. Unrecognized-but-harmless values survive verbatim: a dashboard
that renders ordinary data as «redacted» lies about its own coverage.

Breakpoints ride on apply.Trace, split by location, from the count the pipeline
already makes to respect the provider's cap of four — so placement costs the
request path nothing. The remaining fields are one structural pass over the
top-level object, measured at 0.55 ms/MB against 2.7 ms/MB for a per-field query
loop, and it never parses `messages`.

/api/breakdown groups requests, tokens and spent-vs-saved by one allowlisted
dimension, so per-model cost, cost by reasoning effort and cost by breakpoint
count are one query rather than three that can drift. Per-day usage bars need no
new query at all: bucketing already happens in SQL, so a day is a parameter.

Schema version 6 — the intended migration for a derived view: the old file is
renamed aside and the non-derived tables carried across.

Signed-off-by: Osher-Elhadad <[email protected]>
Left behind by the switch from a per-field query loop to the single pass; a
package-level var nothing reads is not a compile error, so nothing caught it.

Signed-off-by: Osher-Elhadad <[email protected]>
…s tenant

logging.Debugging(ctx) is the single guard for "is anyone reading DEBUG", used by
apply's decision loop and extract_llm's candidate accounting instead of each one
reaching for Enabled(). And BodyOpts's panic recovery now logs through the request's
own logger — a panic is the line you most want attributed to a tenant, and it was
going out on the default logger with nothing on it.

Signed-off-by: Osher-Elhadad <[email protected]>
The UI reads all fifteen fields as top-level keys, which holds only while Meta is
embedded anonymously; a json tag on that field would nest them and blank the
request drawer with nothing else failing.

Signed-off-by: Osher-Elhadad <[email protected]>
The pipeline snapshots messages before each component so it can revert on
error/panic/never-worse. When the JSON round-trip clone fails, fallbackClone falls
back to bifrost's DeepCopyChatMessage — and per [email protected]/schemas/utils.go its
block copier (deepCopyChatContentBlock, l.803) copies only Type, Text, Refusal,
ImageURLStruct, InputAudio and File. ChatContentBlock also carries three
non-OpenAI fields (chatcompletions.go l.1122-1128): CacheControl, Citations and
CachePoint. All three were silently dropped.

So on that path a revert did not restore the message, it degraded it: a request
that arrived with cache_control on a block came back out without it. That is the
never-worse invariant broken on the least visible path — the one that only runs
after something else already went wrong — and it is not cosmetic here. A dropped
breakpoint is a full cache write instead of a cache read, ~12.5x the price, and
getting breakpoints onto the wire is the entire point of cachesplit/cacheinject.

The clone now restores the three fields after bifrost's copy, cloning the pointer
values (TTL/Scope/Enabled) rather than sharing them, so snapshot and live message
stay independent in both directions. The failure is reachable, not theoretical:
ChatMessageContent.MarshalJSON errors when a message carries both string and block
content, which a component can produce, and that is what the new test builds.

TestFallbackCloneKeepsCacheFields fails on the parent commit ("revert dropped
cache_control: a prompt-cache breakpoint is gone from the wire") and passes here.
Output equivalence unchanged: golden hashes still match over the same 373 real
captured requests (73 Terminal-Bench + 300 SWE-bench), the #32 replay still puts
breakpoints on the wire for 72 of 73, and the latency benchmarks are unmoved
(253 ms over 24 requests, 6.5 ms median request, 3222 allocs) since this path is
off the hot path.

Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>

# Conflicts:
#	proxy/proxy.go
…ssage

The writeback ran sjson.SetBytes over the WHOLE body per changed message. sjson
allocates and copies the entire request for every write, so the cost was O(k * body):
30 rewritten tool outputs on a 600 KB request copied ~18 MB to produce one 600 KB
result. Each write also re-scanned the body with gjson to find its target, and
applyMetaWrites did the same once per metadata key.

Now each changed message's own bytes are edited and all of them are spliced back in
one pass. The output is byte-identical, not merely equivalent JSON, because sjson's
splice is local: appendRawPaths ([email protected]) emits json[:res.Index], recurses into
that subtree's Raw, then appends json[res.Index+len(res.Raw):]. Editing a message and
putting it back at the message's span is therefore the same bytes as editing at
"messages.<i>.<rest>" on the whole body. Everything outside an edited span is copied
verbatim, which is what invariant I1 requires.

Two things make that safe rather than clever:

  - Spans come from the offsets gjson already produced for each message, plus the byte
    shift splitVolatileTail now reports (it rewrites the top-level `system` value, so
    everything after it moves). Re-parsing the messages array to find the spans instead
    was the obvious version and it was SLOWER than what it replaced: measured on the
    median captured request, one array parse is 1.21 ms against 0.44 ms for a whole-body
    sjson write, so it only paid above ~3 rewrites per request. That version was a 13%
    regression; this one has no extra parse, and drops one that rebuildCountChanged was
    already duplicating.
  - gjson documents Index as "zero means index unknown" and it is relative to whatever
    json the Result came from, so no span is trusted on its word: the body's own bytes
    at that span must equal the message's Raw or the splice declines and the original
    request is forwarded. A wrong offset therefore costs a rewrite, never a corrupt
    body.

The shift needs its own test, because captured traffic cannot cover it: Claude Code
orders the body `messages` before `system`, so the split shifts nothing on real
requests, and json.Marshal of a map sorts keys the same way. TestSpliceRewrites-
EveryMessageAtItsOwnSpan builds the body with `system` first and both splits and
rewrites in one request; it fails (fail-open, no rewrite forwarded) with the shift
hard-coded to 0 and with it off by one.

Measured, 24 real captured requests:

  end-to-end        253.6 ms -> 243.5 ms  (-4.0%)
  bytes allocated    167 MB  ->  144.5 MB (-13.4%), allocs unchanged
  one median request  6.61 ms ->   6.60 ms (flat)

Per-component duration_ms is untouched by construction — pipeline.runOne's timer wraps
the component call, and this is all after it, so the -39% stands.

Output verified byte-identical over 1868 real captured requests (73 Terminal-Bench +
1795 SWE-bench) against golden hashes recorded before the change, and the #32 replay
still puts breakpoints on the wire for 72 of 73.

applyMetaWrites now takes the message rather than the body, since metaWrite.path was
already message-relative; bodyIndexOf is gone, splitSlotPath does that job.

Signed-off-by: Osher-Elhadad <[email protected]>
Both sides rewrote the breakpoint counter for different reasons, and both
reasons stand. Reconciled to ONE implementation: the perf branch's single
structural walk (ParseBytes().ForEach + mayHold/elemMarks), accumulating into
the metadata branch's location-split Breakpoints instead of one int.

The split is what feeds the four dashboard columns; the single pass is what
takes the counter off ~22% of the rewrite path. Neither needed the other's
implementation — the walk already knows which top-level key it is under, so
the location comes out free, where the 7-path form had to derive it from the
query string. wireBreakpoints stays as the one-line Total() wrapper the cap
check calls.

Kept from fix/clone-and-writeback: the conditional re-count (an untouched
body carries exactly the inbound count, so n > inbound is false by
construction), the duplicate normPre marshal loop's removal (slot.pre already
holds it), and the spliceMessages writeback with its fail-open span check.

Kept from the observability work: every DEBUG line behind its `debug` guard,
dumpToolOutputs, and the cap-breach ERROR — now on the session-bearing
context logger, which is why it no longer repeats "session" as an attribute.

sort.Ints was the only caller of "sort"; slices was already imported for
formatGates, so spliceMessages uses slices.Sorted(maps.Keys(edits)).

Verified: gofmt/vet clean, go test -race green. Byte-identity goldens
reproduce on 373 captured requests (73 terminal-bench + a 300-request
swebench prefix). The merged counter returns the same per-location numbers as
the 7-path version on 3736 real bodies (every captured request, inbound and
post-pipeline). #32 replay: breakpoints reach the wire on 72 of 73. Per-
component duration_ms unchanged — components/pipeline.go is byte-identical to
the perf branch and Pipeline.Run holds the same cumulative CPU.

Signed-off-by: Osher-Elhadad <[email protected]>
A secret in a log attribute's KEY was emitted verbatim: scrubAttr tested the key
name and then replaced only the value. The key is as untrusted as the value —
ranging over parsed data puts data in the key slot — so a credential-shaped key
now takes the whole attr with it.

The auth-header rule matched to end of LINE. Fail-safe for a log record and
destructive for captured transcript content, which the dashboard shows users: a
minified JSON tool result with an "authorization" field lost every field after
it. The value now stops at a string/field terminator as well as the newline; a
bare 'Authorization: Bearer <token>' line still has nothing to stop at but the
newline, so the log case is unchanged.

dash.RedactHeaders had no production caller — nothing in the capture path records
request headers at all — so the allowlist implied a live protection that did not
exist. Deleted rather than wired up, with the docs corrected to say headers are
never captured; git history holds the allowlist if they ever are.

scrubToken read h.Get, the FIRST value of an auth slot, while copyHeaders
forwards ALL of them: two Authorization headers, provider key then our token,
sent the token upstream. It now checks every value, and decides on a prefix match
rather than the exact length LooksLikeToken requires — a token that lost one
character was not token-shaped, so it was forwarded as a caller credential.
Authentication stays strict; only the scrubbing decision is liberal.

Also names the two credential classes a pattern denylist knowingly misses
(base64-encoded, and prefix-less opaque keys outside a named field), so the next
reader does not add speculative patterns for them.

Signed-off-by: Osher-Elhadad <[email protected]>
Three findings from a security review of the tenant package, each with a test
that fails without the fix.

RegisterAccount treated "email_verified_at = 0" as "nobody owns this address",
but migration v3 added that column with DEFAULT 0, so every account created
before email auth migrates to unverified while being in daily use. An
unauthenticated POST to /api/register with a colleague's address therefore
installed the caller's password on a live account, locking the owner out of the
dashboard (token login refuses an account that has a password) and leaving only
the mailed code in the way of a full takeover. The claim is now gated on the
account never having been usable — no password and no token row at all — and
returns ErrEmailTaken otherwise. The v3 upgrade also stamps every account
holding a live token, in the same step that adds the column, so the existing
accounts are never in the claimable state; the same statement runs again as v4
for databases that already reached v3.

BindAgentKey upserted ON CONFLICT DO UPDATE SET tenant_id, which moved a digest
another tenant had bound to whoever asked for it, unaudited. With
capture_content defaulting on, that redirects the victim's request transcripts
to the thief's dashboard. Binding a digest owned by someone else is now
refused, a transfer has to be an unbind by the owner followed by a rebind, keys
shorter than 20 characters are rejected so low-entropy strings cannot be
claimed, and bind and unbind both write an audit row.

decodeHash accepted any non-zero argon2 parameters, so a poisoned row made
every sign-in attempt against that account a 1 GiB allocation. Parameters above
a small multiple of our own are now treated as a corrupt hash.

Also orders Audit by rowid within a timestamp: one Update writes every changed
field with the same millisecond, which left the order inside a change arbitrary.

Signed-off-by: Osher-Elhadad <[email protected]>
…unset key_env

The tenancy cache is where a tenant's frozen compaction decisions live, and it
evicted on recency alone. Registration is open to a whole /8, so max+1 throwaway
accounts sending one request each evicted every real tenant's state, and each
victim's next turn re-wrote its cached prefix at ~11.5x the read price. Entries
that have seen a second request are now last in line for eviction rather than
pinned — the bound still holds, and evicting one is logged as its own case,
because it means the cap itself is the binding constraint. The front entry is
never the victim, so a newcomer cannot be starved by a full cache of active
tenants.

setKey returned the same nil for 'no key_env, caller pays' and 'key_env named
but unset', so a half-finished config edit fell through to forwarding whatever
the caller sent. In gateway mode that is a PLACEHOLDER — non-empty, so the 'no
credential' check passed it — which published the placeholder to a third party
and returned its 401 for the operator to chase. The second case is now a
sentinel error and a 502 naming the upstream, with the variable name in the log
only. No key_env at all still means caller-pays, unchanged.

Signed-off-by: Osher-Elhadad <[email protected]>
MinAgentKeyLen refuses a provider key under 20 characters, so the 11-char
bob-own-key fixture no longer binds. The rename is a merge-time break between
the agent-key floor and the tests that predate it, not a behaviour change.

Recorded while doing it: a real credential measured on this box is 25
characters, so the floor of 20 clears legitimate keys by only five. If any
supported provider issues a shorter key, the floor is a functional refusal
rather than a security win.

Signed-off-by: Osher-Elhadad <[email protected]>
The panels read like documentation: a 40-word note under every heading, a
three-line paragraph under every bar, and a caption under every stat tile
restating the tile's own label. This moves the explanations behind native
<details> disclosures and keeps in the layout only what a reader cannot infer.

Copy:
  - Every panel note is one line. The long version folds into a <details
    class="why">, which is keyboard-operable and collapsed by default.
  - The four savings denominators keep their distinct server-side labels AND
    grow an always-visible `numerator ÷ denominator` line, so shortening the
    prose cannot make two different ratios read as the same measurement.
  - Tile sub-lines survive only where they carry a fact the label cannot: a
    formula, a p95, or the gross/unique distinguisher. Six were deleted.
  - Headings lose their trailing clauses ("Honest savings waterfall" →
    "Savings waterfall", "Latency: context-guru vs upstream" → "Latency").

Layout and accessibility:
  - Fix white-on-accent on the primary button in dark mode: 2.99:1, measured,
    on four screens. New --on-accent token, dark ink on the light-blue accent.
  - Fix horizontal body scroll at 360px (377px wide): the identity group in the
    top bar could neither shrink nor wrap. All four widths are now clean.
  - .clip applied to any element, not just td/code, so the 96-character user
    agent in "Signed-in machines" stops setting that card's width.
  - The bar label column is capped at 220px instead of 30%, so a bar no longer
    starts a third of the way across a wide panel.
  - The six request-metadata filters move behind one "More filters" disclosure,
    badged with how many are set. Thirteen controls wrapped to two rows and
    pushed the first number below the fold.
  - The filter bar is hidden on the five views that read no filter.

Restyled what landed plain:
  - Usage: capped label column, styled in-heading dimension picker, tighter
    rows. The direct value labels on both bars and the always-present legend
    are unchanged — blue-green is the tritan-weak pair.
  - Auth: full-width primary, tracked-out 6-digit code box, amber countdown
    under a minute, token fallback folded away, and the sign-in/register tabs
    hidden during phase two. The countdown still measures against the server's
    absolute expiry; only its styling reads the remaining seconds.
  - Request drawer: 24 flat key/value pairs become four captioned bands, the
    cache_control breakpoints become four labelled slots instead of one
    run-on string, and a null temperature/top_p renders as italic "unset"
    rather than an em dash that could be read as a dash-shaped zero.

Logs affordance: the Config tab and the request drawer carry copyable text for
the Loki-backed Grafana dashboard — the tunnel, the address, and a LogQL query
scoped to the request's own session. Deliberately not a hyperlink and not an
iframe: Grafana binds loopback, so a link would be dead until the tunnel is up,
and an iframe would mean loosening the CSP.

Fix a real regression on the way: two top-level `loadSessions` declarations, one
for the Sessions tab and one for the account's signed-in machines. The later
declaration wins, so the Sessions tab and both of its pager buttons called the
account loader — the tab rendered no rows at all and painted "Could not list
your sessions" into a Settings card. The account one is now loadMachines.

Verified in Chromium against a seeded database: 642 painted foreground/background
pairs measured for WCAG contrast across every tab in both themes, 0 failures
(tightest 4.64:1); no horizontal body scroll at 360/768/1024/1440; every new
disclosure reachable by Tab with a visible focus ring.

Signed-off-by: Osher-Elhadad <[email protected]>
cg_llm_cost_usd was the delta of the PROCESS-GLOBAL cheap-model counters across a
request's lifetime, so on a multi-tenant proxy any other tenant's compaction call
that returned inside that window was billed to whichever request happened to be in
flight. From the row it propagated into tenant_spend, the tenant's month-to-date
figure on its settings page, and cg_tenant_cg_llm_cost_usd. It was also a side
channel: a tenant could infer other tenants' compaction activity from its own rows.

Give each request its own cheapmodel.Sink, carried on the context, and read that in
capture.finish. The context is the plumbing point that already reaches every model
call — apply builds components.Ctx from it, components derive their timeouts from it,
and internal/extract sees only a context.Context — so no call path can miss it
silently. The process totals are untouched: /stats, the Prometheus cg_llm_* series
and the benchmark harness still report what this proxy spent overall.

One consequence worth naming: an observe-mode shadow run happens on the pool's
context, so its spend now lands on no row instead of on some later request's row.

Test: a request whose own pipeline has no model at all, with another tenant's
10000-in/2000-out call made mid-flight, was charged $0.04; now $0.00, while a
request that runs its own summarizer is still charged for it.

Signed-off-by: Osher-Elhadad <[email protected]>
The janitor's own doc comment has always described three rules with fairness first,
but the code ran the byte rule first. DB.Prune's byte rule has no tenant column and
cannot have one — a byte budget is a property of the whole file — so it deletes the
oldest rows in the whole table. Reached while ONE tenant's traffic is what pushed the
database over budget, it therefore evicts the quiet tenants (theirs are the oldest
rows) and leaves the offender's recent history in place.

Run enforceQuotas first, and reclaim the pages a quota trim frees before the byte
rule measures the file: a delete leaves the pages allocated, so without the reclaim
the byte rule still sees the size the offender caused and evicts anyway.

The three-rule sequence moves into Recorder.janitorPass so the order lives in one
place, and the comments on both rules now describe what the code does.

Test: 20 old rows belonging to a quiet tenant against 400 recent rows from a tenant
over its 50-row quota, with the database over its byte budget. The quiet tenant used
to lose all 20 rows; it now keeps them and the byte rule has nothing left to do.

Signed-off-by: Osher-Elhadad <[email protected]>
frame-ancestors, base-uri and form-action do not fall back to default-src, and nginx
sets no X-Frame-Options, so the dashboard's self-only CSP left all three at their
default of "anything". The session cookie is SameSite=Lax, which means a cross-site
frame renders the UNAUTHENTICATED sign-in gate — so the realistic abuse is UI-redress
phishing of the sign-in form rather than riding an existing session, and on a service
reachable from a whole /8 with open self-registration that is worth closing.

Append frame-ancestors 'none'; base-uri 'none'; form-action 'self'. The UI needs none
of the three: it has no <base>, embeds no frames, and its forms carry no action and
are handled by fetch.

Signed-off-by: Osher-Elhadad <[email protected]>
…t's rows

Three deployment-facing fixes in the hosted-mode startup path.

CONTEXT_GURU_DUMP and CONTEXT_GURU_CAPTURE are now fatal in hosted mode. Both are
read once at package init (proxy.capturePath, apply.dumpPath) and append to one
process-wide file: no tenant column, pristine bodies, and on a path the redactor
never runs. In a multi-tenant deployment that is a shared plaintext transcript of
every tenant's source code, written whether or not any tenant consented to content
capture. The rule existed only as prose in docs/hosted.md; it now has to survive one
careless Environment= line. Single-tenant and local runs keep both hooks.

DASHBOARD_MAX_ROWS_PER_TENANT defaults to 100000 instead of 0, and the shipped unit
sets it explicitly. A fairness rule that has to be switched on is not a fairness rule:
at 0 the janitor's quota pass returns immediately, and the only bound left is the
global byte rule, which evicts the quiet tenants. 100k rows is above any plausible
legitimate week against a 7-day retention window (~14k requests/day sustained) and
about 10% of the 512 MiB byte budget for metric-only rows, so several heavy tenants
coexist before the byte rule has anything to do. A manager can still override it per
tenant.

-register-domains no longer claims the address is UNVERIFIED — a mailed verification
code has been mandatory since the email-auth work. What remains true, and is what the
help now says, is that reachability is not entitlement.

Tests boot the real main() in a subprocess: hosted mode with either variable set exits
non-zero naming it, single-tenant mode still starts, the flag's usage output carries a
non-zero default, and the shipped unit sets a positive one.

Signed-off-by: Osher-Elhadad <[email protected]>
…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]>
…est path

Eight findings from the read-only security review of the proxy, each with a test
that fails on 4386ce9 and passes here.

Control plane (proxy/control.go):

- Cross-site writes. Every write is cookie-authenticated and nothing but
  SameSite=Lax stood in the way — and SameSite's unit is the registrable domain,
  so on a deployment under ibm.com any colleague's host under ibm.com is "same
  site". readJSON ignored Content-Type too, so a text/plain form post reached the
  JSON decoder with no preflight. Demonstrated: a cross-origin post minting a
  token on the victim's account, and the same shape signing them out. One guard
  in readJSON, which every write funnels through, plus /api/logout which reads no
  body. Origin present-and-different is refused; a caller that sends none (curl,
  an agent) is untouched. readErr gives the refusal a 403 rather than dressing it
  as a parse error.

- Account enumeration. /api/register answered 409 for a taken VERIFIED address
  and 201 otherwise, unauthenticated, at 3/min — so anyone could ask which
  colleagues have accounts. ctlLogin and ctlVerify were built not to leak that
  (one message for unknown/wrong/no-password, argon2 against a decoy hash); this
  route gave it away. Both paths now answer the same 201 body, and the owner is
  mailed a "someone tried to register your address" notice instead of a code.
  RegisterAccount already hashes before it discovers the address is taken, so the
  timings match; a mail failure maps identically on both paths, or the outage
  would be the oracle.

- The manager's patch did not validate upstream names against the operator's
  allow-list while PUT /api/me did, so a manager could park a tenant on a name
  the proxy refuses at request time — breaking an agent belonging to someone who
  never sees the error. One checkUpstreams, both writers.

- ctlBindAgentKey collapsed every registry error into 500. ErrForbidden (the
  digest belongs to another account) is 403 and says who can unbind it;
  ErrNotFound is 404.

Request path (proxy/proxy.go, proxy/promexport.go):

- /compact and the Bob catch-all authenticated and then ran unmetered: TENANT_RPM
  and TENANT_CONCURRENT were enforced in chat() only. With the limiter at 1/min,
  chat refused the second request while /compact — the full pipeline over a body
  up to 32 MiB — served twenty of twenty. One meter() helper, three call sites,
  429 accounting unchanged and not doubled.

- incomingModel was a second credential exit that disagreed with the first. In
  gateway mode setUpstreamAuth deletes the caller's auth slots and injects the
  server's key while the component's LLM client carried the CALLER's key to the
  same host. Both exits now read the one resolved decision, up.setKey; hosted
  mode degrades rather than spending a server key on a tenant's compaction. The
  comment claiming setUpstreamAuth "is the ONE place that decides" now describes
  what is actually true.

- cg.refused carried no tenant for the two refusals users report: the per-request
  logger was attached after upstream resolution, so rate limits and "no provider
  credential of your own" logged through the default logger with the tenant in
  hand three lines up. And errNoProviderKey was collapsed into reason=auth, which
  hides the blast radius of dropping a server-held upstream key. It now has its
  own series, with the tenant on it, counted exactly once — the SLO panel divides
  an unlabelled sum of that family, so a second count would inflate the SLI.

- The catch-all forwarded the browser's Cookie header, shipping a live cg_dash
  session to a third-party host. Dropped in copyHeaders, which every forward path
  goes through (gateway mode included); Set-Cookie is untouched, so the response
  direction is unaffected.

- A failed proxy authentication was free, and one of them is an oracle: an agent
  is identified by the sha256 of the provider key it already sends, so "is this
  string a bound agent key" was grindable at 30 r/s — and a hit is impersonation,
  not confirmation. Failures are now charged against the same per-address bucket
  registration and sign-in attempts use.

Signed-off-by: Osher-Elhadad <[email protected]>
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]>
Osher-Elhadad added 25 commits August 17, 2026 06:50
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)
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)
MinAgentKeyLen refuses a provider key under 20 characters, so the 11-char
bob-own-key fixture no longer binds. The rename is a merge-time break between
the agent-key floor and the tests that predate it, not a behaviour change.

Recorded while doing it: a real credential measured on this box is 25
characters, so the floor of 20 clears legitimate keys by only five. If any
supported provider issues a shorter key, the floor is a functional refusal
rather than a security win.

Signed-off-by: Osher-Elhadad <[email protected]>
(cherry picked from commit 68f351b)
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)
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)
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)
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)
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)
…fixture

Two loose ends the parallel branches could not tie themselves.

tenant.ErrBadAgentKey did not exist at the branch point where ctlBindAgentKey
was written, so the 400 case was left as a comment. Both halves are now in one
tree, so the case is real. The message deliberately does not call the key
malformed: a short key can be entirely valid at its provider and merely too
short to serve as an identity here, because identity is the key's digest.

security_test.go bound an 11-character fixture, below the new floor.

Signed-off-by: Osher-Elhadad <[email protected]>
(cherry picked from commit a4a3986)
… 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)
… 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]>
…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]>
… 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)
… 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)
… 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]>
…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]>
…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]>
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)
@OsherElhadad
OsherElhadad changed the base branch from stack/6-dashboard-redesign to feat/hosted-tls-and-agent-compaction August 17, 2026 08:29
@OsherElhadad
OsherElhadad merged commit e7ccc05 into feat/hosted-tls-and-agent-compaction Aug 17, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 17, 2026
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]>
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