Compare commits

...
Author SHA1 Message Date
antje 139bd734f0 deps: luxfi/consensus v1.36.2 -> v1.36.3 — the v1.36.2 tag was re-pushed
Cold builds fail sumdb verification against the moved tag (downloaded
eKzasq4O... vs sealed IbeWQF1w...). v1.36.3 is the immutable successor;
never re-tag a published version.
2026-07-17 01:26:35 -07:00
antje 6e24fcfd28 mirror: skip hidden files — AppleDouble forks pass the extension check
._foo.png is a mac resource fork, not a render; 700+ of them poisoned a
library within an hour of the mirror going live.
2026-07-17 01:15:16 -07:00
antje 9e7931e81c render: poll window matches the dispatch cap; engine recycles after each render
The 10m local history poll undercut the 4h startToCloseTimeout the dispatcher
grants — live renders (observed 8-70m) were marked failed while still sampling;
only the mirror later delivered them. renderWindow now matches the cap.

The engine leaks ~58GB per render. The handler signals a recycle after each
COMPLETED render (never on timeout — the engine may still be sampling and the
mirror rescues late finishes); the supervisor restarts on the signal.
2026-07-17 01:09:39 -07:00
494a6582c4 bench(finance): BenchmarkListUsage — the co-resident usage-read path (BUG 2) (#325)
The finance domain had no benchmark; this measures the read that replaced the
commerceinproc self-dispatch — finance.ListUsage over a per-org SQLite ledger,
at 100/1000/5000 seeded debits. Backs the reproducibility claim in the
hanzo-unified-tenant-cloud paper (1.25/10.5/61 ms). Also surfaces a real N+1:
store.Entries fetches postings per row the usage view never uses — a
postings-free read would cut this ~10x (follow-up).

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-17 01:06:20 -07:00
zandhanzo-dev b0254454c9 Money names its unit: Int -> Atto
There were two words for one idea. money.Amount.Minor() returns an integer at the
CURRENCY's decimals — money.USD declares 2, so cents. cloudmoney.Amount.Int()
returns an integer at 18 decimals — atto. Both are "the backing integer", neither
name says which, and they differ by 10^16.

That is not a style complaint. It is how

    Amount: cloudmoney.FromInt(u.Charge.Minor()), // exact 18-dp USD, no floor

got written, reviewed, and shipped. It type-checked (both sides *big.Int), it read
as "make an Amount from the integer", and it billed a $17.376 zen call as
$0.0000000000000017 until v1.801.44. The package documented the trap in prose —
"Take the decimal, never Amount.Minor()" — because a comment was the only place
the unit existed. Prose is not a type.

So name the unit, not the Go type: FromInt -> FromAtto, Int() -> Atto(),
IntString() -> AttoString(). FromCents/Cents already did this and were never
confused with anything. Now the units are visible at the call site, and the
mistake reads as one: FromAtto(x.Cents()) is obviously wrong where
FromInt(x.Minor()) was obviously fine. It no longer type-checks either —
FromAtto takes *big.Int, Cents() returns int64 — so the pairing that cost us the
money is now two independent kinds of error instead of zero.

Values are untouched: Atto/AttoString return exactly what Int/IntString did, so
the treasury ledger hash and every stored 18-decimal string are byte-identical.
No migration, no data change — only the names, and the compiler found every one
of them (45 sites; a regex could not have, because .Int() also belongs to big.Int
and decimal).

Zero regressions: the failing set is identical to origin/main.
2026-07-17 00:52:06 -07:00
zeekayandClaude Opus 4.8 c93ddf92bf build(deps): adopt stable luxfi/keys v1.4.1 (unbreak force-moved v1.4.0 checksum)
luxfi/keys v1.4.0 was force-moved on the remote (tree 5153d639→80a3745a),
producing a go.sum checksum mismatch that broke `go mod tidy`/`go build` and
the hanzoai/cloud image build in CI. Every keys tag v1.1.0..v1.4.0 was
force-moved with content changes; only v1.4.1 is byte-stable (local==remote
tree 17551acd). Adopt v1.4.1 as the single stable version. Its go.mod floors
the unified luxfi stack, so the transitive set moves forward (geth 1.17.12→
1.20.1, consensus 1.35.32→1.36.2, crypto/database/warp/zap/…), all within v1.

go.mod/go.sum only; diff vs origin/main is luxfi/* exclusively. Embedded
iam2 v0.14.0, apps.go, and concurrent commerce/agent work untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 00:50:13 -07:00
74478bb9a2 build: decomplect the cloud image — cloud compiles ONLY Go (#321)
The console SPA, agent-skills catalog, and native flags staticlib are each now
built by their OWN CI as a versioned immutable image and PULLED into the cloud
build, instead of rebuilding node+python+rust from scratch every release. The
console stage (cold npm install + full Next static export, cache-busted every
build) was the ~20-min long pole; it is now a registry pull.

- Dockerfile: console/skills/flagslib stages -> FROM ${CONSOLE_IMAGE}/
  ${SKILLS_IMAGE}/${FLAGS_IMAGE} prebuilt pulls; COPY sources updated
  (/dist, /catalog, /libhanzo_flags.a). Mirror golang+alpine bases, GOPRIVATE,
  and every RED gate (SQLCipher proof, modernc guard, cek frozen-format) are
  unchanged. Pins are ghcr.io so both buildx lanes pull directly; mirrored to
  registry.hanzo.ai (S3) for GET-flow consumers. release.yml still owns the
  cloud image + v* tags (it resolves CONSOLE_IMAGE to a fresh console-embed
  digest, as CONSOLE_CACHEBUST did).
- native/flags/Dockerfile: the cloud-flags artifact (rust -> scratch /libhanzo_flags.a).
- hanzo.yml: images: cloud-flags (distinct artifact, never a v* tag) + zccache
  RUSTC_WRAPPER on the native-flags gate (no-op unless the runner carries it).

Companion artifact publishers: hanzoai/console#(console-embed),
hanzoai/openapi#(agent-skills).

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-17 00:49:57 -07:00
hanzo-dev f76e714d37 refactor(flags): extract the Policy primitive — fold featuregate's waitlist into the flags engine
featureflags -> flags (Hanzo's Unleash-analog / hanzoai/flags): ONE runtime
decision engine, (Principal, context) -> verdict, evaluated in-process, hot.

Fold the launch-control waitlist off its DUPLICATE SQLite mode store
(clients/featuregate) onto the one engine:

  - a service's waitlist mode IS the platform switch waitlist.<svc>,
    evaluated through the same native evaluator as every other flag
  - the host->service registry folds into clients/flags (waitlist_store.go,
    mode column dropped — the mode is the switch)
  - featuregate.Enforce stays but as a CONSUMER of flags.WaitlistModeForHost
    (the decide), via an injectable Gate seam
  - /v1/featuregate/mode -> served by flags (the decide), same wire shape
  - /v1/admin/services -> an admin lens like /v1/admin/flags
  - per-user approval still reuses IAM (featuregate/approval.go, unchanged)
  - featuregate dropped from apps Wire() — it exposes only Enforce now

The flags package doc names the aspirational end-state: authz (access policy)
and entitlements (product-access policy) are the SAME (Principal,context)->
verdict shape and could COMPOSE this one engine. NOT touched here — flagged only.

Tests (green): featuregate RULE acceptance matrix + approvals; folded-registry
store (Seed/ServiceForHost/List/Upsert); flags env/board/parsers;
apps TestWireOrderMatchesFrozen. Native-engine + cek store tests need
CGO+libsqlcipher+libhanzo_flags (CI), unchanged.
2026-07-17 00:48:30 -07:00
hanzo-dev 53cd7c585d billing bridge: ask commerce what it gates, stop keeping a copy
The bridge's mint guard kept its own list of commerce's mint routes under the
comment 'kept in lockstep with api/billing/handlers.go'. A comment cannot hold
two lists together, and it hadn't: 10 paths here against the 16 commerce gates.
Six money-mint routes were outside this guard entirely.

Commerce now DECLARES its gated surface — middleware.Mint records what it gates,
MintRoutes() exports it (commerce v1.49.0) — so the guard reads that declaration
instead of copying it. A mint route added in commerce is covered here with nobody
remembering anything, which is the only version of this that survives contact
with a busy repo.

Registration is what populates the registry, so the guard registers commerce's
billing routes before reading it. The request-level assertion is unchanged and is
the part that matters: an ordinary org user's call must never REACH commerce,
because arriving at all means arriving with the admin service token that
satisfies MayMintMoney.

Proof it bites: allowlisting 'deposit' fails with the escalation itself —
'POST /v1/billing/deposit reached commerce carrying Bearer svc-tok'.

16/16 gated routes refused. All six bridge tests pass.
2026-07-17 00:41:23 -07:00
antjeandGitHub 8479418021 gpu: mirror local studio renders to the library (independent of claims) (#324)
Every 30s (its own ticker in the connect select loop), scan --studio-dir/output
recursively for image files new or changed since the last scan and POST each to
<studio-url>/v1/library/upload with the worker's bearer, tagged ?node=<identity>
and ?subpath=<subfolder>. So EVERY render lands in studio.hanzo.ai — including
ones produced OUTSIDE the job path: a graph hand-run on the node, or a render
that finished after its activity was reaped (the stranded-late-render class). The
mirror's independence from claims/activities is the point.

State is a tiny in-memory map[relpath]size that skips unchanged files; the studio
endpoint dedupes byte-identical uploads, so a re-scan after restart is cheap and
harmless. One log line per newly stored file; upload failures are summarized once
per scan and retried next tick (no 5xx spam). New --studio-url flag (default
https://studio.hanzo.ai, HANZO_STUDIO_UPLOAD_URL honored) so the mirror works
WITHOUT jobs. No new deps. Test: cli/gpu_mirror_test.go (new/changed uploaded,
unchanged skipped, node+subpath+bearer carried).
2026-07-17 00:20:24 -07:00
antje 309c830abb agent: v0.1.2 — pass a completion billing refusal (402) through, not a 502
Bump github.com/hanzoai/agent v0.1.1 -> v0.1.2 and have the in-process completer
return the agent typed hz.UpstreamError{Status,Body} on a non-2xx completion. The
round then passes a caller-facing 4xx (402 insufficient_balance, 429, 403) through
verbatim so a no-credit user sees "add credits", not an opaque "agent: completion"
502. Proven live: POST /v1/agent with a real hk- key ran the round end-to-end and
the completion returned 402. Dropped the now-unused clip() helper. Simplified
commerce_errorscope_test to the real invariant (typed 403 never flattened to 5xx)
now that commerce v1.48.10 honors status itself; the scope stays as the boundary.
2026-07-17 00:01:18 -07:00
antje f4ab7e2bd3 deps: commerce v1.48.5 -> v1.48.10 — free $0 tiers stay self-serve (paid-tier gate keys on price, not includedCreditUsd) 2026-07-16 22:38:59 -07:00
zandhanzo-dev 94873e3e0c MountAll's doc outlived Typed
It still said the MountFunc takes the app as `any` and that in-repo subsystems
recover it via Typed. Neither is true: MountFunc names *zip.App and Typed is
deleted. The app is handed to each mount as itself.
2026-07-16 22:24:17 -07:00
antje 0e377c52ad feat(sync,git): Gitea-native sync provider + webhook reject parity; fix LoadConfig flag panic
CHANGE 1 — the /v1/sync git provider drives GITEA (the one git store), not the
retired cloud embedded store:
- clients/sync/gitea.go: a Gitea REST + go-git client (GIT_ADMIN_TOKEN, GITEA_URL).
  Inbound = fast-forward-only go-git fetch(source) -> push(Gitea), so a diverged ref
  is a conflict, never overwritten (split-brain guard, now on Gitea). Outbound = a
  Gitea push-mirror (sync_on_commit) so Gitea itself propagates every commit. Fails
  closed when GIT_ADMIN_TOKEN is unset.
- git_provider.go Reconcile and sync_api.go patch/delete now compose those Gitea
  primitives; the cloud embedded seams (InboundGitSync/ImportGitRepo/EnsureGitMirror)
  are retired from the sync path. resolve() decision, loop guard, cursor idempotency,
  and hop limit are unchanged.

CHANGE 3 — webhook reject parity + a pre-existing root test panic:
- Wrap /v1/git/webhook and the slack(events,commands)/discord/teams/telegram inbound
  webhooks in cloud.Terminal so a bad-signature 401 / malformed 400 survives the
  commerce /v1 500-flatten (uniform reject codes, matching /v1/sync and
  /v1/connector/github/webhook).
- config.go LoadConfig: guard the process-global flag registration with a sync.Once,
  so a re-entrant LoadConfig (many test callers in one binary) no longer panics
  "flag redefined: enable".

CHANGE 2 (retire the embedded git server) is NOT done: it is still a live dependency.
cloneURL resolves to api.hanzo.ai/v1/git (cloud's OWN embedded server) and the
coding-agent orchestrator clones from uploadPack, pushes to receivePack, and reads the
store via VerifyRef. Deferred — migrate coding to Gitea first.

Tests (CGO_ENABLED=0): clients/sync + clients/integrations green; new
clients/sync/gitea_test.go proves reconcile acts on Gitea and the fast-forward guard.
2026-07-16 22:20:41 -07:00
hanzo-dev 66e4999a44 Merge: Mount takes *zip.App — delete the Typed shim and its 85 wrappers 2026-07-16 21:57:01 -07:00
antje 1cf505ebd1 edge: scope commerce error envelope to its own routes (unblock release smoke — 14 endpoints 500→4xx)
commercemid.ErrorHandlerJSON() was installed as a /v1 GROUP middleware, but fiber
matches group middleware by PREFIX, not by the handle a route registered on. So on
the shared /v1 it wrapped EVERY subsystem mounted after commerce (projects, agents,
wallets, functions, integrations, marketplace, team, s3, analytics, knowledge,
automations, deploy, billing) and flattened their typed zip.HTTPError (403 "X-Org-Id
required", 400, …) into a blanket 500 — the store envelope always renders 500. The
authenticated release smoke (#322) correctly fails on 5xx, so this blocked every
release since it landed.

Fix stays cloud-side (no commerce dep bump, no money-path churn): commerceErrorScope
guards the envelope by commercePrefixes, so it stays on commerce and every other
subsystem renders its own status via zip default. Pre-commerce subsystems (kms,
o11y) already did; this makes the post-commerce ones match. Verified with the REAL
commerce middleware: /v1/projects 403 (was 500), /v1/store/current keeps the 500
envelope. Regression test added.
2026-07-16 21:50:00 -07:00
zandhanzo-dev 25fcaa4351 Mount takes *zip.App: delete Typed and the 85 wrappers
MountFunc took `app any` and cloud.Typed asserted it back to *zip.App on every
mount — a runtime check doing the type system's job, with a failure branch that
could not fire because the only value ever passed is a *zip.App. Every subsystem
paid for it: 85 call sites read cloud.Typed(x.Mount) instead of x.Mount.

The reason given was circular. cloud said `any` was load-bearing because an
external module (licensing) exposed func(any, Deps) error; licensing said it used
`any` to avoid an import cycle in pkg/cloud. Each pointed at the other, and the
cycle cannot exist: this package already imports zip (build.go), and zip does not
import cloud. The `any` was justified by nothing.

So name the type. MountFunc is func(*zip.App, Deps) error — what every subsystem
already exported and what licensing's own doc claimed all along. Typed is deleted,
the 85 wrappers are gone, and the three in-repo mounts that hand-rolled the same
assertion (mountZen, mountMetrics, MountO11y) just take the app.

The compiler immediately found what the `any` had been hiding: four mounts still
shaped func(any, ...), one of them across a module boundary. That is the point —
a signature drift is now a build failure instead of a runtime error nobody would
see until a subsystem mounted.

Also here, because the same rip surfaced them:

  - iam: v1.31.27-0.20260716191958-4400762928a2 -> v1.31.28, and the replace
    pinning a second pseudo-version is dropped. The required pseudo-version named
    a commit that no longer exists (it was rebased away), so `go mod tidy` could
    not resolve it; v1.31.28 is a real tag and a strict superset of what the
    replace pointed at. A version, not a coordinate, and no replace.
  - licensing -> v0.1.5, which is where the typed Mount ships.
  - cloud.OrgConfig is aliased next to LicenseEntitlement. Both are named by
    CommerceClient's methods, but only one was exported, so the exported
    interface could not be implemented from outside without reaching into
    cloud/types — an omission, not a boundary.
  - build_registration_test.go tested Typed and nothing else. "Recovers the
    *zip.App" proved an adapter passed through its argument; "fails closed on a
    wrong type" cannot be compiled now. What is left is the assertion that a
    subsystem signature IS a MountFunc — which the build checks.

No regressions: the failing set is byte-identical to origin/main (11 pre-existing
TestAudit_*).
2026-07-16 21:47:19 -07:00
zeekay f49d283282 build(iam2): bump embedded iam2 v0.1.1 → v0.14.0 (parity-complete surface)
The CLOUD_IAM_IMPL=iam2 identity fold (clients/iam2, identitySpec) was pinned
to iam2 v0.1.1 — an early cut missing the whole console-parity surface. Bump
to v0.14.0 so the embed actually serves what hanzo.id needs:

  - RFC/IETF surface (HIP-0111): OAuth2 code+PKCE/refresh/client_credentials/
    password, RFC 8693 token-exchange, 7662 introspection, 7009 revocation,
    8414 AS-metadata, OIDC UserInfo, SCIM 2.0 Users
  - Casdoor verb-alias compat (transitional cutover bridge) for every verb the
    live console/gateway hard-code: users/orgs/apps/providers/roles/projects
  - operator bootstrap upsert (IAM CR reconciliation), TOTP MFA enrollment,
    organization-scoped projects (ScopeSwitcher)

No wiring change — main's identitySpec + co-mingle iam2server.Mount(app, db)
compile unchanged against the v0.14.0 API. zip already at v1.8.3.

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 21:43:03 -07:00
antje f20e7679ef feat(connector,sync): /v1/connector/github/webhook namespace + reject paths survive the commerce /v1 500-flatten
CHANGE A — first-party vs external route naming. Rename /v1/github-webhook ->
/v1/connector/github/webhook, opening the external-platform namespace
/v1/connector/<provider>/webhook (github now; gitlab/others are sibling literal
routes later, each with its own signature scheme). /v1/git/webhook (first-party
Hanzo Git) and /v1/sync (the bridge) are unchanged. No live consumer breaks:
the GitHub App isn't created yet.

CHANGE B — 500 -> real 4xx on the reject paths. mountCommerce registers
commerce's ErrorHandlerJSON on app.Group("/v1"); that filter rewrites ANY error
a downstream /v1 handler PROPAGATES into a hardcoded HTTP 500. Every /v1
subsystem mounted after commerce is wrapped the same way -- git, sync AND
integrations alike. git does NOT escape it: its isolated tests read 401 only
because they don't co-mount commerce (its bad-sig path is never exercised in
prod, so the flatten went unseen). Add cloud.Terminal, which writes a returned
*zip.HTTPError in-band and returns nil, so the filter's c.Next() sees nil and
has nothing to flatten. Wrap /v1/sync (all verbs) and the connector webhook.
sync no-principal is now 401 (was 403) -- an authentication failure, matching
the webhook's bad-sig 401. The commerce filter is left untouched.

Tests reproduce the /v1 flatten filter and assert: sync unauth -> 401, connector
bad-sig -> 401, malformed body -> 400; connector resolves at the new path and
the old /v1/github-webhook 404s.
2026-07-16 21:32:46 -07:00
antje c93fd2c4dd edge: /v1/agent self-meters (fix 503 balance_unavailable on the agent orchestrator)
The global BillingGate priced /v1/agent/* at a flat 1c via a dead legacy
bot-reverse-proxy rule in DefaultPrice, so every agent request was gated: the
unauthenticated preset/conversation reads hit the balance check, failed closed,
and 503d before the orchestrator handler ever ran. The route was mounted and
winning precedence the whole time — the gate short-circuited ahead of it.

/v1/agent is self-metered: the reads are free and POST /v1/agent bills through
the /v1/chat/completions it runs in-process (gated + metered downstream), so the
edge must price it 0 or double-bill. Drop the legacy branch (and its now-unused
cloudEdgePriceCents const); price /v1/agent and /v1/agent/* at 0. Tests updated.
2026-07-16 21:06:09 -07:00
hanzo-dev 2f4095e68a Merge feat/openapi-spec: /v1/openapi.json generated from the live router
The spec IS the router, not a description of it: apps.Wire() -> MountAll ->
app.Fiber().GetRoutes(). 983 operations / 692 paths / 109 products, served beside
/zap so ZAP and OpenAPI are two projections of one route table rather than two
sources that can disagree.

A drift test proves the bijection and was proved to fire; it already caught
/v1/pricing-policy and /v1/pricing/policy collapsing onto one operationId.

# Conflicts:
#	serve.go
2026-07-16 20:42:42 -07:00
6233b3c805 fix(billing,smoke): usage reads the co-resident ledger (not a self-dispatch) + a real authenticated release smoke (#322)
A live authenticated smoke surfaced two production bugs; this fixes both and
adds the durable smoke that now guards every release.

BUG — /v1/billing/usage 500 for a valid caller. usage() proxied
"/v1/billing/usage" through commerceinproc, which re-dispatches BY PATH.
Commerce's own billing routes are behind //go:build cloud and never compiled
here, so the ONLY registration of that path is usage() itself — the S2S hop
re-entered the handler, which self-answered "sign in to view billing". This is
the SAME defect balance() was already fixed for. usage() now reads the usage
ledger DIRECTLY from cloud's own finance ledger (finance.ListUsage → the
wallet→revenue debits RecordUsage wrote), off the self-dispatching hop;
split-deploy falls back to the commerce S2S read, unchanged.

BUG — the balance gate 402'd read-only GETs (fixed in hanzoai/ai, pinned via
the go.mod bump). A $0-balance org could not VIEW its own resources. Fixed in
the ai module's BalanceGateFilter — reads never spend, so GET/HEAD/OPTIONS are
exempt; only writes/metered POSTs gate on balance.

SMOKE — cmd/smoke: a durable, authenticated per-subsystem prober. One
side-effect-free read per core subsystem; a read that 402s (balance gate) or
5xx-es (crash) fails the release. Baked into the image (Dockerfile) and wired
into release.yml as the functional gate after the boot check, so a release can
never ship with chat/billing/projects/kms/... down. The smoke token is
KMS/secret-sourced (never hardcoded); absent → the anonymous matrix still gates
public/authed and catches every 402-on-read / 5xx.

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-16 20:35:56 -07:00
hanzo-dev 52acb303c2 cli: multi-identity credential store with active-pointer switch
Store every logged-in identity in ~/.hanzo/identities.json keyed by a stable
<owner>/<name> key (admin/z, hanzo/z), with an Active pointer; mirror the active
identity into credentials.json so every legacy single-file reader is unchanged.
A second login as a different owner for the same email (privilege separation:
hanzo-admin-guard vs hanzo-console) is stored beside the first, not over it.

New: auth list (whoami --all), auth switch <owner|owner/name> (alias use),
logout [<owner>]. Token refresh writes through the store (SaveActive) so the
active identity stays fresh after rotation. All files stay mode 0600.

One credential store, active-pointer switch, backward compatible.
2026-07-16 20:20:53 -07:00
hanzo-dev 951703f486 dedup: fold hanzoai/o11y module wildcard into the one o11y subsystem
apps.Wire() had TWO {Name:"o11y"} entries: the in-repo read plane
(o11y.MountO11y) and the external hanzoai/o11y module wildcard
(cloud.Typed(o11ymod.Mount)). Fold the module wildcard in as the TERMINAL
sub-mount inside o11y.MountO11y (registered after every specific /v1/o11y/*
route, so Fiber in-order match still gives them precedence), delete the 2nd
Wire entry and the now-unused o11ymod import -> ONE o11y spec.

/v1/o11y/health is preserved exactly: the merged entry keeps OwnsHealth=false,
so the generic always-ok route is registered before MountAll (ahead of the
wildcard) — byte-identical to when the module co-entry, also OwnsHealth=false,
triggered it. Frozen wire order updated (two co-owned rows -> one); the
no-duplicate test no longer needs an o11y exemption.
2026-07-16 20:17:18 -07:00
hanzo-dev 7022064723 dedup: delete dead clients/session
Zero importers, no cmd/session, absent from apps.Wire(); its /v1/code/sessions
surface was never mounted (dark). Removes session.go, store.go, session_test.go.
2026-07-16 20:10:06 -07:00
hanzo-dev 8dabc5c469 fix(cloud): serve /v1/iam/* — the org-scoped edge to Hanzo IAM
The one-binary console (console.hanzo.ai — cloud serves console's static export)
reads org members + projects at /v1/iam/*, but cloud 404'd those (IAM isn't
folded in-process yet) and the old /org/iam BFF proxy is pruned from the static
export. So the browser got the SPA shell (HTTP 200 HTML), which the client
surfaced as "Request failed (HTTP 200)" — the Platform page died on "Could not
load".

iam_edge.go adds an org-scoped reverse edge at /v1/iam/* → the standalone IAM,
mounted when IAM is NOT folded in-process (else that subsystem owns the path — no
double-mount). The org is PINNED to the caller's validated, server-minted
X-Org-Id (never a raw client header) — load-bearing, since IAM's own authz is
permissive on the org-keyed routes, so without the pin one tenant could read
another's projects. A super admin may cross; a tenant may not; writes require an
org admin and must carry the caller's own org. Shares the ONE IAM identity
(iamHost/iamCred) with the API-key resolver (DRY).

Verified: 7 gate tests (pin, cross-tenant refuse, super-cross, allow-list, 401,
write-gate, own predicate) + go build clean.

Claude-Session: https://claude.ai/code/session_01SpMZ69ur3tjAXCiwaa7Wv2
2026-07-16 20:07:12 -07:00
zandGitHub ac65cf4ec3 chore(deps): bump hanzoai/tasks → v1.51.1 (fix api.hanzo.ai concurrent-map-writes crash)
Fixes the live recurring tasksd concurrent-map-writes fatal (hanzoai/tasks#18, v1.51.1). Build green; the failing 'Test' check is the pre-existing repo-wide LoadConfig flag-redefine panic (fails on main + all branches), unrelated to this go.mod-only bump.
2026-07-16 20:02:07 -07:00
hanzo-dev 5e06e29de5 Merge: tenant apps are App CRs — the last writer of the Service kind
clients/platform was the only thing still minting Service CRs; every other
declarer is already App. A role-less App dispatches to the operator's service
profile, the same reconcile the Service kind ran, so a tenant workload carries
over verbatim.

Existing tenant CRs still resolve (App first, Service second). A redeploy patches
the kind it IS rather than minting a twin — two CRs on one name is the
commerce-admin ownerRef flap, not a migration. Teardown deletes BOTH kinds:
either alone rebuilds the app the tenant just deleted, still billing.

113 tests pass, 7 new.
2026-07-16 19:40:04 -07:00
hanzo-dev 095e1cce4e platform: tenant apps are App CRs — the last writer of the Service kind
clients/platform was the only thing still minting Service CRs. Every other
declarer is already App: universe git has zero hanzo.ai/v1 kind:Service, the
operator calls App "the sole workload reconciler for the collapsed fleet", and 69
of the 80 live CRs are Apps. A tenant app was the exception for no reason — a
role-less App dispatches to the operator's service profile (controllers/app.rs
`classify("") => Dispatch::Service`), which is the same reconcile the Service kind
ran, so an App carries a tenant workload verbatim.

Nothing mints a new Service CR after this. What already exists still resolves:
reads, patches, scales and deletes walk crGVRs() — App first, Service second — so
the 3 live tenant CRs written before this keep working untouched.

A redeploy of a pre-collapse app patches the kind it IS rather than declaring an
App twin. Two CRs claiming one name is not a migration, it is the commerce-admin
flap: both kinds materialize the same children through the same materializer under
one field manager, so the Deployment's ownerRef just flips between them.

Teardown deletes BOTH kinds. Either kind alone re-materializes the Deployment, so
removing only the one that resolves first would rebuild the app the tenant just
deleted — running, and still billing, minutes after a successful delete.

Sequencing (deploy order matters): operator v0.7.7 carries the Claim guard that
makes App the deterministic owner when both kinds claim a name. This is safe
before it — the no-twin rule means a colliding pair is never created here — but
the guard is what makes an existing collision safe to clean up.

REMOVABLE once no Service CR remains in any tenant namespace: drop servicesGVR
from crGVRs() and the delete-both, and this file is App-only.

Tests: 113 pass; 7 new (kind is App, no twin on legacy redeploy, delete removes
both kinds, idempotent delete, resolution order, absence honest). The 10 tests
that asserted a Service CR is written now assert the kind we write.
TestMigrateOverLegacyPlatformApps fails identically on pristine main (sqlcipher
codec, environmental).
2026-07-16 19:39:56 -07:00
antje bffe597ff0 apps: frozen wire list — add sync entry (main added /v1/sync to Wire; frozen drifted, breaking TestWireOrderMatchesFrozen); fix agent route comment 2026-07-16 19:38:00 -07:00
hanzo-dev 601d5660b7 Merge: paas reads the kind the fleet runs on, and does not fight the git declarer
The PaaS control plane serves platform.hanzo.ai and read services only: 69 App CRs
run in the scanned namespaces against 7 Service CRs, so the SUPERADMIN drift board
rendered 7 rows for a 69-app fleet — 1 in production — and /v1/paas/health probed
the Service CRD, found it served, and reported ok over a blind board.

Reads now walk App first, Service second, deduped by name. Writes refuse a
git-declared App (Hanzo CD syncs it with selfHeal, so a patch is reverted on the
next sync) and name the file to commit to; a Service CR still patches.

35 tests pass, 0 fail.
2026-07-16 19:30:16 -07:00
hanzo-devandz 8bf2dda4d1 feat(shard): in-binary org→owner shard router for horizontal writer scale
Lifts the unified binary off replicas:1 on DigitalOcean (RWO-only block
storage, no RWX) WITHOUT any shared volume. Each org is pinned by rendezvous
hashing (ha.Owner over the static CLOUD_PEERS ring) to exactly one owner pod;
a request whose org this pod does not own is transparently forwarded to the
owner, so every per-org SQLite store (KMS, finance, and every org-keyed store),
audit append, per-org rate ceiling, and prepaid billing debit runs on ONE pod.

THE INVARIANT — no two pods ever write one tenant's SQLite file — is upheld by
two independent guarantees that compose: per-pod RWO PVC (different physical
files per pod) + org→owner routing (all of an org's writes on one pod).

- shardrouter.go: the middleware. Runs immediately after SanitizeIdentity so it
  keys on the VALIDATED, server-minted X-Org-Id (never a client header), hashes
  the SAME injective SanitizeOrg slug the on-disk path uses (routing key ≡ file
  key), and forwards via a fasthttp streaming proxy (SSE/chat pass through — a
  streaming chat still carries a per-org billing debit, so it routes too) with
  dial-only retry across an owner's roll gap and a 421 loop-guard on divergence.
  Static identical membership rules out dual-owner and routing loops.
- config.go: CLOUD_PEERS (id@addr ring) + POD_NAME (self). Sharding auto-enables
  only when >1 peer; Validate fails closed if self is not in the ring or if
  embedded iam (non-shardable process-local sessions) is co-enabled.
- serve.go: wires the middleware after IdentityMiddleware; shard-aware boot log.
- audit_serve.go: per-shard audit is automatic on the per-pod PVC; stamp the
  shard id on the AU-9 checkpoint stream so the tail-truncation monitor tracks
  N heads. writerpin.SingleWriter is correct PER SHARD (each pod sole writer of
  its orgs); the writer lease is pod-local under per-pod PVC and stays off.

No-op (byte-identical to today) when CLOUD_PEERS names ≤1 pod. N pinned at 3;
rebalance-on-N-change (a tenant-file move) is the documented follow-up.

Tests prove: exactly one owner per org (deterministic, total, evenly
distributed); all pods agree (no dual-writer); owned served locally, unowned
forwarded to the owner (local chain never runs, hop header set, response
streamed); org-less served locally; loop-guard 421; boot-gate fail-closed.
2026-07-16 19:28:27 -07:00
hanzo-dev db226b321b Merge: bill zen in the credit unit — FromInt(Minor()) understated every debit by 10^16 2026-07-16 19:26:12 -07:00
hanzo-dev f24596453e Bill zen in the credit unit, not the currency's minor unit
zen prices every SKU as an exact 18-dp value tagged money.USD. money.USD
declares 2 decimals, so Amount.Minor() rescales that value to CENTS, while
cloudmoney.FromInt reads its argument as 18-dp. Composing the two divided
every zen debit by 10^16: a $17.376 charge debited $0.000000000000001738,
and any charge under half a cent folded to a zero that metering.Record drops
before it reaches the ledger — no debit row, call served free.

The spend gate read the same composition. FromInt(est.Minor()).Cents() is
always 0, and AuthorizeVerdict only compares balance against size when
AmountCents > 0, so the size check was dead code and any org with a positive
balance could draw a request of any size. The dust debits never accumulated,
so the cap could not trip either.

Route the seam through one conversion. credit() carries the exact decimal
across and changes only the minor-unit convention — no rescale, no rounding,
no factor — because the decimal is the value and a currency's Decimals is a
rendering convention. cloudmoney.FromDecimal is the typed counterpart of
ParseUSD that makes this expressible without a string round-trip. nano()
takes the typed Amount rather than a bare *big.Int, so a cents integer can no
longer reach the warehouse fold.

The tests asserted Amount.Int() against Charge.Minor() — the same integer on
both sides — so they proved a round-trip and were blind to the unit. They now
assert against known dollar values built through a different constructor: a
$17.376 charge debits $17.376. Reintroducing Minor()-into-FromInt fails all
of them, including a gate test that admits an over-cap request.
2026-07-16 19:24:29 -07:00
hanzo-dev 185cca68f2 Forward only the billing paths the console reads
The /v1/billing/* bridge attaches the commerce service token, and that token
satisfies commerce's MayMintMoney. The subpath was checked for traversal but
not against a set, so POST /v1/billing/deposit forwarded a mint for any
signed-in user — pinned to their own subject, which aims the mint rather than
stopping it. Commerce closed this on its direct path the day after the bridge
reopened it, and wider: the bridge needs only a validated principal, never an
admin bit.

The forwardable set is now a per-method table, consulted before the token is
attached, 404 on anything else. Per-method because payouts is a GET read and a
POST mint on one path — a method-blind set hands the mint to every reader.

Nothing reachable today: commerce's mint is not compiled into this binary and
commerce.hanzo.svc resolves here. But devnet runs a real mint-capable commerce
and points cloud-api at it under a second name for the same thing; unifying
those names would arm it. The gate should exist before that cleanup does.
2026-07-16 18:54:20 -07:00
blue db4801d787 Gate the billing bridge on an allowlist: the service token is authorization
/v1/billing/* forwarded any subpath to commerce carrying the admin
COMMERCE_SERVICE_TOKEN, validated only against path traversal. Forwarding IS
authorization there: commerce gates money-mint on
MayMintMoney = IsServiceToken || IsSuperAdmin, so every forwarded path ran with
platform authority. Commerce 403s an org admin who POSTs /v1/billing/deposit
directly; through this bridge the same person was handed the platform's own
credential, and the subject-pinning aimed the credit at their own account.
Pinning is an IDOR control, not an authority control.

Add billingForwardable: a per-method allowlist of the endpoints the console
actually calls, enforced before the token is attached. An unlisted path 404s.
Allowlist, not denylist — a mint route commerce adds tomorrow is unreachable
with no change here. GET and POST are separate sets because `payouts` is a read
AND a mint-gated write; one method-blind set would hand the mint to every reader.
The POST set holds nothing that creates balance from a client-named amount.

Not exploitable in the current topology: commerce is co-resident in cloud, whose
build never compiles mount.go (//go:build cloud), so no api.Route billing bundle
is reachable and the forward loops back to this bridge. It is one COMMERCE_URL
away from live — devnet already runs a standalone commerce.

Tests: an ordinary org user's deposit/credit/refund/credit-grants/husd/allotment
now never reach commerce; the console's 12 real calls still forward; the store
bridge still cannot tunnel into billing.
2026-07-16 18:36:07 -07:00
hanzo-dev 337c159db0 Embed zen v1.4.0 so the prompt-cache fix reaches production
zen v1.4.0 bills the prompt cache: cache_read was priced in the catalog,
published in /v1/models, and never charged. cloud pinned v1.3.11, so the
fix could not reach api.hanzo.ai, where the traffic lands.

The module graph cannot move: zen's own go.mod is byte-identical between
v1.3.11 and v1.4.0 (same sha256), and cloud holds exactly one zen edge.

NOTE: this is necessary but NOT sufficient. hmoney.Minor() returns cents
while cloudmoney.FromInt expects atto, so apps/zen.go understates every
debit by 1e16 and the spend gate reads AmountCents 0. Correct pricing is
still zeroed downstream. Tracked separately; that fix is what makes cache
billing real.
2026-07-16 18:21:12 -07:00
hanzo-dev 20e7591f53 openapi: serve GET /v1/openapi.json generated from the live router
The route table gets a third projection. /zap replays the /v1 handlers, the
console renders them, and GET /v1/openapi.json now describes them — all read
from the ONE router after MountAll, so none can drift and none holds a second
copy. There is no checked-in spec file and no second registry.

openapi.Live(app) reads app.Fiber().GetRoutes(true) (fiber's own filter drops
Use() middleware); every other function is pure over that []Route. Each
operation is tagged with its product — the first path segment after /v1/ —
so a CLI can build `hanzo <product> <resource> <verb>` with no judgment.

Reading the LIVE router is the only total source: POST /v1/kms/auth/login is
registered as Group("/v1/kms/auth").Post("/login") and no grep can find it,
and the route set is a function of deployment config, so the document varies
per deployment — correctly. Unauthenticated: it grants no capability, every
route it names stays auth-gated, and `hanzo --help` must build its tree
before login.

The drift guard (cmd/cloud/openapi_test.go) is a bijection over the fully
mounted apps.Wire(): 983 operations / 692 paths / 109 products, every live
route present, no operation invented. Shown to fail on a broken translation
(353 routes reported missing) before being restored.

Honest boundaries, asserted rather than papered over:
  - No schemas. The router holds func(*zip.Ctx) error; the request type is a
    local inside the handler (var req secretPutRequest; json.Unmarshal(...)),
    unreachable by reflection. cloud.Handle[S] is generic over the SERVICE,
    not the payload. The path to schemas is zip's typed ops, which today
    number zero — which is why zip's own generator emits nothing here.
  - No responses block. OpenAPI 3.1 makes it optional; fabricating 200/ok on
    ~900 routes would assert what nothing knows.
  - HEAD/CONNECT excluded — forced, not taste. CONNECT has no OpenAPI field;
    fiber auto-generates HEAD in startupProcess(), so including it would make
    the document depend on lifecycle stage.
  - Catch-alls are opaque: POST /v1/billing/deposit is not a route here.

Corrects LLM.md, which the code contradicted: Wire() does exist (apps.go:188),
MountAll does not sort, and byte-identical patterns MERGE rather than panic.
A high handler count is not a collision — app.Post(path, mw1, mw2, mw3, h) is
one registration with four handlers (apps/commerce.go:151), and 34 live routes
are that shape, so the generator never reads the count.
2026-07-16 18:14:23 -07:00
antje 9d5d51936a cloud: mount hanzoai/agent /v1/agent (no-shim); delete dead clients/chat
clients/agent adapter injects the ai completion (in-process, billed) + tools.Default()
into github.com/hanzoai/agent; POST /v1/agent live path. Dispatch resolves the caller
via the ONE canonical tools.PrincipalFrom — no reconstructed principal. Builds green
on the v1.801.35 base. DEPLOY-BLOCKED: go.mod uses a local replace for hanzoai/agent
(CI needs a fetchable release + the local module-cache shallow-clone bug resolved).
2026-07-16 18:00:50 -07:00
hanzo-dev c5cefc39a6 Bill the prompt cache in production: zen v1.3.11 -> v1.4.0
cache_read was priced in the catalog and published in /v1/models, but never
charged: on an openai upstream every cached input token billed at the full
`in` rate, and on an anthropic one it left the bill entirely. zen v1.4.0
normalizes both dialects into one tally over three disjoint classes
(fresh + cached + cacheWrite == the whole prompt) and derives once per
response. cloud embeds zen via apps/zen.go, so the fix is inert at
api.hanzo.ai until this pin moves.

zen v1.4.0's go.mod is byte-identical to v1.3.11's, so the require edit and
the two go.sum lines are the whole change: no transitive pin moves, and
nothing else in the graph names zen.
2026-07-16 17:49:16 -07:00
hanzo-dev 7f6b3a4cfe Merge: fix the zen margin test's decimal + money types (unblocks CI on main) 2026-07-16 17:48:36 -07:00
z e538ae0b7f apps: price the zen test with the decimal money actually uses
The zen margin test never compiled, so CI has been red on main since it landed:
it parsed prices with shopspring/decimal and handed the result to hmoney.New,
which takes hanzoai/decimal. Two identically-named types, one of them wrong.

    vet: cannot use d (struct type "github.com/shopspring/decimal".Decimal)
         as "github.com/hanzoai/decimal".Decimal value in argument to hmoney.New

Money has exactly one decimal. A second one that merely LOOKS like it is how a
price silently becomes a different number, which is why the compiler is right to
refuse. Parse with hanzoai/decimal (decimal.Parse — the same call zen itself
prices with); this was the only file in cloud importing shopspring.

Read the debit through Amount.Int(), not Amount.Minor(). The test held two money
types at once: zen's hanzoai/money.Amount (Charge/Cost) has Minor(), but
meterUsage returns cloud's clients/money.Amount, whose accessor is Int() — it
wraps Minor() and returns the identical *big.Int, so the assertions are unchanged.

The tests themselves are worth keeping: they prove the debit is the retail Charge
and never the upstream COGS, that a 3x-margin tier collects 3x, and that a
sub-cent call does not floor to zero. They just could not run.

Not run locally: ./apps links a prebuilt Rust staticlib (libhanzo_flags.a) that
is built in CI, not here. vet — the step CI actually failed — passes, and the
package builds.
2026-07-16 17:48:26 -07:00
hanzo-dev 2593b1b18e GOPRIVATE names the namespace that is actually private
GOPRIVATE named zap-proto/*, which is public -- all 55 repos, all 6 modules
cloud needs served anonymously from the public proxy. The namespace that is
private went unnamed: github.com/hanzoai/* (467 private repos incl. ai,
account, commerce, orm, xorm, beego, csqlite). It resolved only by falling
through GOPROXY's direct fallback, and passed checksums only because go.sum
already pins everything.

containment.yml then set GOSUMDB=off to compensate. GOSUMDB does not scope to
a namespace: that disabled checksum verification for every module in the
build, public ones included, in the image that handles payments -- breaking
the invariant the Dockerfile three files away states and honors.

Public modules keep proxy and sumdb immutability; private ones go direct and
authenticated. Verified under the CI and Dockerfile env with -mod=readonly and
sumdb on: build 0, go mod verify all verified.
2026-07-16 17:33:16 -07:00
hanzo-devandantje 40ca6a48a8 feat(sync): universal /v1/sync engine — GitHub/GitLab ⇆ native Hanzo Git
One reconcile loop, one place a sync happens. clients/sync owns the Sync
record (source/target/direction/trigger/cursor), a per-org sqlite `sync`
table, /v1/sync CRUD + /v1/sync/:id/run, and a kind→Provider registry with a
single Reconcile(sync,event) contract. Git is the first provider, composing the
existing git object-plane seams (InboundGitSync inbound, ImportGitRepo reconcile,
EnsureGitMirror outbound) — no second copy of any git op.

Triggers resolve to Syncs and enqueue the engine (cloud.Sync), never sync
directly: the GitHub App webhook now serves the path it actually fires at
(/v1/github-webhook, was a prod 404 at /v1/integrations/github/webhook) and hands
the verified push to the engine; the Gitea push webhook gains a loop guard
(skip pusher == GIT_SYNC_ACTOR). Loops break on the engine cursor (identical
fingerprints are a no-op) + actor guard; chained propagation (a sync's target is
another's source) is bounded by a hop limit.

Seams (root cloud): SyncFunc + RegisterSync/Sync, GitMirrorController +
EnsureGitMirror. Fail-closed on unmounted engine / missing secret. Tests
(CGO_ENABLED=0): engine loop-guard/idempotency/chain/hop-limit, git resolve,
CRUD+patch+run, webhook signature/isolation/enqueue, gitea loop guard.
2026-07-16 17:26:06 -07:00
hanzo-dev 2cc52957b4 build: GOPRIVATE names the namespace that is actually private
GOPRIVATE listed github.com/zap-proto/*. Every zap-proto repo is public — all 55
of them — and every zap-proto module this build needs is served by the public
proxy anonymously. It was never the reason anything resolved direct.

The namespace that IS private went unnamed: github.com/hanzoai/* — ai, account,
commerce, orm, xorm, beego, csqlite and ~30 more. Those only ever built by
falling through GOPROXY's `direct` fallback after the proxy 404'd them, and only
kept passing the checksum step because go.sum already pins them, so no sumdb
lookup happens. It worked by accident, one added dependency away from failing.

containment.yml compensated for that unnamed namespace with GOSUMDB=off, which
does not scope to hanzoai — it disables checksum verification for EVERY module in
the build, the public majority included. The Dockerfile's comment reasoned the
same way inverted ("hanzoai/* and luxfi/* are PUBLIC ... only zap-proto/* is
exempt"); hanzoai/* is largely private and luxfi/* (all 37 deps here) is public.

Naming github.com/hanzoai/* is what the off switch was standing in for. GOPRIVATE
implies GONOPROXY+GONOSUMDB for exactly that namespace, so the private modules go
direct+authenticated and skip the sumdb that cannot see them, while zap-proto and
luxfi keep the public proxy + checksum db — the immutable hashes that make a
force-moved tag unable to break or poison the build. GONOSUMDB and GOSUMDB=off
are dropped: scoped by GOPRIVATE, they are redundant, and blanket-off is a
supply-chain regression in a money image.

hanzoiam/* is not listed: a74b7de reverted the scim/saml/ldap embed, so nothing
in go.mod requires it. It goes back when the modules resolve, named as private.

Verified under the exact CI/Dockerfile env (GOPRIVATE=github.com/hanzoai/* only,
GOSUMDB=sum.golang.org, GOFLAGS=-mod=readonly): build exit 0, vet exit 0,
`go mod verify` = all modules verified, and `go mod download` resolves both a
public module (zap-proto/zip) and a private one (hanzoai/ai).
2026-07-16 17:21:31 -07:00
antje 28aaa39d56 deps: ai v1.816.0 -> v1.817.0 — global auto-routing switch is the '*' settings row, not ROUTER_ENABLED env (config-as-Base)
Runtime routing policy now sources from the GlobalDefaultOwner OrgSettings
row (admin.hanzo.ai-editable SQLite), env demoted to deprecated fallback.
Per-org override unchanged.
2026-07-16 17:16:33 -07:00
hanzo-dev dfe30a3883 paas: read the kind the fleet runs on, and don't fight the git declarer
The PaaS control plane serves platform.hanzo.ai and read `services` only. The
fleet collapsed onto `kind: App` and this reader never followed: 69 App CRs run
across the scanned namespaces against 7 Service CRs, so the SUPERADMIN drift
board rendered 7 rows for a 69-app fleet — 1 row in `hanzo`, production, and that
row is a duplicate CR. It was not an error anyone could see. The board looked
plausible and was blind to 68 of 69 services; every read of an App-declared
service 404'd; and /v1/paas/health probed the Service CRD, found it served, and
reported ok — status theater over a blind board. clients/deploy already solved
this with an App-first/Service-second read order; this gives the same order to
the reader that needed it.

Both kinds are listed and deduped by name: one workload is one row even when an
App CR and a Service CR both claim the name, because a Deployment has one
controller ownerRef and the operator's Claim guard gives it to the App.

The write path is the harder half. Hanzo CD syncs 68 of the 69 App CRs from
universe `infra/k8s/operator/crs/` with selfHeal on, so patching an App CR here
is reverted on the next sync — the deploy would report success and silently roll
back. That is worse than refusing, so deploy and release now resolve which kind
holds the workload and refuse a git-declared one, naming the file to commit to.
A Service CR has no git declarer (cloud and kubectl write them directly), so it
still patches exactly as before — the tenant plane and the untransitioned CRs are
untouched. release.go's "no ArgoCD" claim was true when written and is not now.

This does not restore an admin deploy button for the git-declared fleet. Under
GitOps that button belongs in git, and ImageUpdate already names that seam
(registry→git→cluster). Whether /v1/paas/deploy should commit to universe or be
retired is a CTO call, not one to make silently inside a read fix.

Tests: 35 pass, 0 fail, including the pre-existing release suite. The fleet-sees-
App-CRs case is seeded to the shape of the real `hanzo` namespace.
2026-07-16 17:12:40 -07:00
antje a74b7de5c4 revert(iam2): back out scim/saml/ldap embed — hanzoiam repos do not resolve
Reverts e4b3c88f. go.mod pinned github.com/hanzoiam/{ldap,saml,scim}, but none
of the three repos exist: https, ssh, and API all return not found, and ldap
was never fetched by any proxy or cache. Cold machines — including release
runners — fail go mod download, so main could neither build nor release.
Local builds passed only on module caches warmed 21:36-21:48 UTC today.

iam2 restored to v0.1.1, the state prod v1.801.38 ships. Re-land the embed
unchanged once the hanzoiam repos exist and resolve from a cold GOMODCACHE.
2026-07-16 17:01:45 -07:00
hanzo-dev f662973eb2 Merge: one name for the account, one for the org — and the last copy of the payer rule deleted 2026-07-16 16:38:08 -07:00
z e72d77b21b billing: one name for the account, one name for the org
Two functions were called Payer and returned different things: account.Payer
returns the ACCOUNT that pays, principal.Payer returned the ORG whose ledger
holds it. Those are different values on the same request — a person in the shared
signup org pays from account "hanzo/alice" held in ledger "hanzo" — and one name
for both is how the gate came to key the pool while the debit spent the person.
Rename it to what it returns: principal.HomeOrg. An org names a ledger; an
account names a wallet within it.

Fix the last copy of the rule with it. clients/metering is cloud's vendored
metering client, and its IdentityFromGatewayHeaders still hardcoded `user := org`
under the same false premise, while its doc claimed cloud "mirrors" the module
"exactly so every product keys the SAME ledger entry" — a promise two independent
copies cannot keep. Both now call hanzoai/account.Payer, so they agree by
construction and the comment is true for a reason.

Its test asserted the divergence in words — "want hanzo (per-org billing key, not
org/sub)" — which is how a premise outlives the code that disproved it. It now
asserts equality with the rule.
2026-07-16 16:37:43 -07:00
hanzo-devandz b2c5b4f81e build(cloud): mirror base images to ghcr.io/hanzoai/mirror/* (kill public.ecr.aws 429s)
public.ecr.aws (ECR Public) rate-limits anonymous pulls with HTTP 429 on shared
CI runners; a 429 on any base pull aborts the release (a release died pulling
python:3.12-alpine). Repoint all five FROMs to 1:1 linux/amd64 mirrors in our
own GHCR namespace, pinned by digest for immutability:

  node    ghcr.io/hanzoai/mirror/node:24-alpine@sha256:0cb0e7c3195bce740b6c8d8b27432c92360e3b7f1528087f2c50640b177950c6
  python  ghcr.io/hanzoai/mirror/python:3.12-alpine@sha256:aa679aa4eed6eb56c1dc6ad3f1b98b7d2d788fd961596779d188fdedad97fb38
  rust    ghcr.io/hanzoai/mirror/rust:1-alpine3.22@sha256:b348cb409ac0a73de15065997a360063cf87465574a15e3e4469862cb8996f02
  golang  ghcr.io/hanzoai/mirror/golang:1.26-alpine3.22@sha256:47d47cb5cc3c7dac409dcb6c3a98a6263571218046cd02d709527feef804a77c
  alpine  ghcr.io/hanzoai/mirror/alpine:3.22@sha256:7c8cb692ae09657cbc4a3f3cbd0e8d5a2690ba38386aaaf252dbb060bf5eb2e6

The four the task named plus alpine:3.22 (the final-stage base — same registry,
same 429 exposure) so no FROM still hits public.ecr.aws. release.yml already
logs the build into ghcr.io (GH_PAT, docker/login-action) before building, so
buildx resolves these private mirrors today with no new plumbing. Only the five
FROM lines + one rationale comment change; nothing else in the Dockerfile.

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-16 15:48:48 -07:00
hanzo-dev 6c77cfccab feat(ai): bump ai v1.814.0 → v1.816.0 — router self-probe, flywheel trainer, casibase metering
Ships the full router flywheel into the cloud binary: the self-probe
(continuous tagged auto traffic → reward ledger), the fit→gate→auto-deploy
→publish trainer, the routing-latency guard (~0.68us heuristic), and
casibase-chat usage/o11y metering. Also carries the zen warehouse+span
wiring already on main.

Migrates the billing-subject callers (balance.go, account/billing.go +
tests) from the ai/object.Payer that v1.816.0 REMOVED to the extracted
github.com/hanzoai/account.Payer — the same rule in its new home (the
concurrent decomplect). Same replace directive for the force-pushed iam
pseudo-version account v0.2.0 pins.

Claude-Session: https://claude.ai/code/session_018PmFAHZvbBSTsuWyebwMra
2026-07-16 15:32:35 -07:00
hanzo-dev 34800f6991 ci(cloud): GOPRIVATE += github.com/hanzoiam/* (enterprise IAM modules)
The iam2 embed pulls github.com/hanzoiam/{scim,saml} (+ ldap under -tags iam2_ldap).
hanzoiam is a distinct org from hanzoai, so hanzoai/* did NOT cover it — the test
phase would route these private modules through the public proxy/sumdb and 404.
Git auth is already handled by the reusable CI's GH_PAT insteadOf (covers any
github.com private repo the PAT reads).
2026-07-16 15:04:30 -07:00
zeekay e4b3c88f82 feat(iam2): wire SCIM + SAML into the cloud embed; LDAP GPL-isolated behind -tags iam2_ldap
Last code step of the iam2 migration. clients/iam2 blank-imports the Apache-2.0
enterprise features so their init() self-registers into iam2's feature registry;
iam2server.Mount -> feature.MountAll auto-mounts them under CLOUD_IAM_IMPL=iam2.
ONE mechanism (database/sql driver pattern) — no feature.Register call in cloud,
which (feature.Register appends with no dedup) would double-mount and collide routes.

  _ github.com/hanzoiam/scim   SCIM 2.0 provisioning  (/scim/*)
  _ github.com/hanzoiam/saml   SAML IdP + SP SSO      (/v1/iam/saml/*, /v1/iam/acs, /v1/iam/get-saml-login)

LDAP is GPL-isolated: hanzoiam/ldap links goldap (GPL-2.0), so it is opt-in only via
clients/iam2/ldap_enabled.go (//go:build iam2_ldap). The DEFAULT cloud binary stays
copyleft-free — proven: `go list -deps ./clients/iam2/` has no goldap; only under
-tags iam2_ldap does it pull github.com/lor00x/goldap + hanzoai/ldapserver.

deps: hanzoai/iam2 v0.1.1->v0.1.4; + hanzoiam/{scim,saml,ldap}; go mod tidy.
2026-07-16 14:59:47 -07:00
hanzo-devandz 6a47436062 feat(kms): one-time legacy ZapDB -> per-org SQLite migration (deploy-safe cutover)
Without this, deploying the per-org store over live data boots an EMPTY store and
orphans every secret — cloud KMS is the authoritative source the kms-operator syncs
out to every service, so that is a cluster-wide outage. New() now runs a one-time,
writer-only, keyed, FATAL-on-error migration BEFORE serving: it opens the legacy
{DataDir}/kms ZapDB (encrypted at rest with the master key), streams every SEALED
secret (kms/secrets/ prefix; the JSON value carries the full coordinate + AES-GCM
ciphertext + ML-KEM wrapped DEK) verbatim into its per-org SQLite file via store.put
— NEVER unsealing, so no plaintext is exposed and the AAD path-binding survives —
then archives the legacy dir to {DataDir}/kms.migrated so the OS lock is released for
good. Idempotent (prior .migrated marker or absent store = no-op; put upserts).

Tests: migrate roundtrip (opens to same plaintext), no-legacy-store no-op, and the
cross-org relocation defense still holds after migration. Full kms suite green (2
pre-existing admin-edge fails only).
2026-07-16 14:55:16 -07:00
hanzo-devandz b31c642959 feat(kms): per-org SQLite store — replaces OS-locked embedded ZapDB, lifts replicas=1
The embedded luxfi/kms ZapDB (a Badger fork) held an exclusive OS lock on ONE dir
for ALL orgs — the hard reason cloud ran replicas=1 behind a cross-process writer
lease. This replaces it with per-org encrypted SQLite ({DataDir}/orgs/{org}/kms.db
via cloud.OrgDB->cek, per-db DEK), which has no exclusive-opener lock, so distinct
tenants never contend and different pods can serve different tenants.

Crypto stays in the client (Seal/Open AES-256-GCM envelope, AAD-bound to the FULL
/orgs/{org} path): plaintext never reaches the file, and a record physically moved
into another org's file still fails to Open (cross-org swap defense preserved).
Adds cloud.PlatformDB for the reserved non-tenant (_platform) partition.

Verified: 54 PASS / 2 FAIL in clients/kms; the 2 fails (admin-edge dualmount/authz)
are PRE-EXISTING — proven failing identically on origin/main. concurrent_open_probe
proves per-org SQLite has no exclusive lock. Build + finance (pure-Go) green.

Branch only — NOT for main/deploy until red review passes.
2026-07-16 14:55:16 -07:00
zandhanzo-dev 2ac7f835e2 billing: the edge gate keys the account the debit spends
The gate keyed `user := home` — the org pool, always — on the premise that
prepaid billing is per-org. That premise is false. A person in the shared signup
org holds their OWN account: its members are strangers, not a team, and a shared
org is not a shared wallet. That is what IAM's signed billing_account claim states
and what ai's meter debits.

So the gate authorized against a balance nobody drained. Fund the pool and a
signup-org person still 402s, because their usage comes out of their own account;
fund the person and an empty pool blocks them anyway. Two layers, two answers, one
request.

Resolve through hanzoai/account.Payer — the same function ai debits with, on the
same credential — so the gate and the debit cannot name different accounts. The
premise is removed rather than restated.

The masquerade split is preserved by construction, not by care: the account is
resolved WITHIN the home org, so Account.Org IS the home org and a SuperAdmin
acting in another org still bills their own ledger. A claim naming a foreign
ledger is refused, so it cannot redirect a debit into the org being acted on.

Tests assert against the rule rather than a constant, so they cannot drift the way
the premise did: the signup-org person keys their own account, a real org pools,
the claim wins for a person and a project, and every case is checked equal to what
the debit computes.
2026-07-16 14:42:34 -07:00
hanzo-dev c563d8a4a6 merge: iam2 embed subsystem — CLOUD_IAM_IMPL selects beego (default) or iam2
clients/iam2 mounts the clean-room zip+orm IAM at /v1/iam when CLOUD_IAM_IMPL=iam2,
else beego, byte-for-byte unchanged. Flag OFF by default → inert. iam2 v0.1.1 seam.
2026-07-16 14:38:03 -07:00
hanzo-dev 724d011417 feat(iam2): select /v1/iam impl via CLOUD_IAM_IMPL (default beego, unchanged)
apps.Wire's identity slot now calls identitySpec(): CLOUD_IAM_IMPL=iam2 mounts the clean-room iam2 (zip+orm), anything else — including unset, the production default — keeps the legacy beego Casdoor embed byte-for-byte. The two impls own the SAME absolute prefixes (/v1/iam/*, /login/oauth/*) and cannot co-mount, so exactly one occupies the slot per boot and mount order is preserved. Off by default => completely inert until a canary flips the flag; selection (this) stays orthogonal to activation (cfg.Enabled).
2026-07-16 14:32:15 -07:00
hanzo-dev 53e22f0875 feat(iam2): clean-room IAM v2 embed subsystem (zip+orm, beego-free)
clients/iam2 folds the beego-free Hanzo IAM v2 into the unified cloud binary as an in-process identity plane — the either/or twin of clients/iam. Matches the cloud.Typed contract func(*zip.App, cloud.Deps) error: cloud hands subsystems a cloud.Deps (not an orm.DB), so Mount opens its OWN embedded SQLite ({DataDir}/iam2/iam.db, mirroring the beego embed's {DataDir}/iam layout), seeds config new-only+idempotent from the SAME init_data.json the beego iam uses (non-fatal, honest degrade), then iam2server.Mount registers the whole surface at the canonical absolute paths.

Fail-closed like clients/iam: a store-open or mount failure serves 503 on the identity prefixes while every co-resident subsystem stays up; iam2server.Mount's only panic path (a registered enterprise feature) is recovered in safeMount so it never crashes the shared binary. A TODO marks where the parallel-lane hanzoiam/{scim,saml,ldap} feature.Register lines land.

Pins github.com/hanzoai/iam2 v0.1.1 (seam held stable across the parallel internals refactor); transitive MVS bumps are all patch-level within v1.x (zip 1.8.3, orm promoted to direct, luxfi/crypto 1.20.1, argon2id 1.0.0, pgx 5.9.2). Inert until wired — see the apps.Wire gating follow-up.
2026-07-16 14:32:06 -07:00
hanzo-dev 7b63b49324 fix(ci): bound the SECOND version scan too (compute step) — same unbounded --paginate
The compute-next-version step had the same full-registry --paginate as the tag
step (fixed in f0abd21). It ran first, so it could hang before the build. Bound
it to one page too. Both version scans are now O(1 page), not O(registry).
2026-07-16 14:28:00 -07:00
hanzo-dev 0494a6d3c7 feat(zen): warehouse + gen_ai span emission with exact margin — ai v1.814.0
zen's commerce Meter now also calls ai's TraceServedUsage (recordTrace
WITHOUT recordUsage — the commerce debit stays the ONE billing source,
never doubled), carrying zen's exact per-tier retail (Charge) and upstream
COGS (Cost) folded atto→nano, so zen* traffic in the unified binary lands
in hanzo.cloud_usage + the o11y span plane with TRUE margin instead of
being warehouse-blind. Rides the ai v1.813.1→v1.814.0 bump; balance.go
(+ its drift-guard test) migrated to the renamed Payer/PayerOf API —
same subjects, one rule.

Claude-Session: https://claude.ai/code/session_018PmFAHZvbBSTsuWyebwMra
2026-07-16 14:26:17 -07:00
zandGitHub 27cc091884 Merge pull request #315 from hanzoai/cloud-zen-family-events
feat(zen): embedded-zen meter writes the family RoutingEvent (last link) + ai v1.813.5/zen v1.3.11
2026-07-16 14:08:50 -07:00
hanzo-dev 64b0d1f8a1 feat(zen): embedded-zen meter writes the family RoutingEvent (the last link)
The embedded zen mount serves the zen catalog in-process and never reaches ai's
pipeToFamily, so zen* calls produced ZERO routing events — starving stats, world,
spark retrain, and /v1/feedback joins. Wire cloud's zen Meter to ALSO write the
RoutingEvent through the ONE shared writer object.RecordFamilyRouting (source="family",
served arm = zen.Usage.Upstream, join key = zen.Usage.ResponseID — the client-visible
response id, new in zen v1.3.11 — tokens + retail cost), fire-and-forget beside the
existing debit. Bumps zen v1.3.7 → v1.3.11 (Usage.ResponseID); ai already v1.813.6
carries object.RecordFamilyRouting.

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-16 14:08:28 -07:00
antje 54b8bae797 git: Gitea push-webhook ingest (POST /v1/git/webhook)
The external Hanzo Git server (Gitea fork, git.hanzo.ai) POSTs push events
here so a push landing on it drives the SAME push-to-deploy core the embedded
smart-HTTP receive-pack path drives: fireBranchBuild -> cloud.OnGitPush deploy
trigger + EmitLifecycle. One code path, no duplication.

HMAC auth: X-Gitea-Signature is hex HMAC-SHA256 of the raw body, verified
constant-time against GIT_WEBHOOK_SECRET (KMS-synced hanzo/prod:/git/webhook-secret).
Fail-closed 401 on unset secret or mismatch. Only X-Gitea-Event: push acts;
others 204. Zero-SHA / non-branch refs are no-ops.
2026-07-16 12:05:08 -07:00
zandGitHub 5fb8f50e0a Merge decomplect/account-payer: migrate to ai.Payer — unbreaks main, ends the self-serve 402
main pinned ai v1.813.6 (which deletes billing_subject.go for the Payer/Account
refactor) without migrating the call sites, so main did not compile:
  clients/billing/balance.go:59: undefined: aiobject.BillingSubject

This migrates the call sites to the ONE rule: Payer(Credential)->Account
(owner = Person|Org|Project). Ends the live 402 where a self-serve signup's top-up
minted to the shared org pool 'hanzo' while the gate debited 'hanzo/alice' ($0) --
customer paid, locked out, money in a pool their org-mates could spend.

Green: go build -tags 'libsqlite3 sqlite_fts5' ./clients/... rc=0;
go test ./clients/billing ./clients/account rc=0. go.mod/go.sum identical to main.
2026-07-16 11:51:27 -07:00
hanzo-dev bd520de13f fix(billing): migrate off deleted BillingSubject → ai.Payer/PayerOf — unbreaks main
main pins ai v1.813.6, which contains the Payer/Account refactor (billing_subject.go
and its PERSONAL_BILLING_ORGS/ORG_BILLING_ORGS lying default are deleted). But the
call sites were never migrated, so main does not compile:
  clients/billing/balance.go:59: undefined: aiobject.BillingSubject
  clients/billing/balance.go:61: undefined: aiobject.BillingSubjectFromUserKey

Migrates balance.go + finance.go + billing.go to the ONE rule —
Payer(Credential{Owner,Name}).Subject() / PayerOf(org,key).Subject() — and DRYs the
duplicate subject resolvers. This is the cloud half of the fix that ends the live
self-serve 402 (top-up minted to the shared org pool 'hanzo' while the gate debited
'hanzo/alice' = $0).

go.mod/go.sum untouched vs main. Green: go build -tags 'libsqlite3 sqlite_fts5'
./clients/... rc=0; go test ./clients/billing ./clients/account rc=0.
2026-07-16 11:50:51 -07:00
hanzo-dev 65e782a855 refactor(billing): route top-up + console subject through ai.Payer, one rule
The console top-up (clients/account/billing.go) and the finance read
(clients/billing/finance.go) each re-implemented the billing subject as "always
the org" — the reverted lineage's rule. Against ai's gate, which bills a signup
person per-person, that is the split: money minted to subject "hanzo" (the pool)
while the gate debited "hanzo/alice" ($0) → the paid-up member 402'd.

Delete both twins; resolve the subject through the ONE rule, ai/object.Payer,
keyed on the IAM username (X-User-Name) the gate also keys on. Top-up credits and
console reads now land on the SAME account the gate debits — they cannot drift
because there is one function. The killed PERSONAL_BILLING_ORGS / ORG_BILLING_ORGS
env is inert here too (test proves hostile values change nothing).

Requires ai v1.809.5, which must be tagged FROM ai main after decomplect/account-payer
merges — NOT off a branch. The prior one-rule fix was tagged off an unmerged branch
(v1.806.8/.9), main never got it, and every later tag resurrected the allowlists;
that is why this bug is live. go.sum refreshes via `go mod tidy` once the tag exists.
Verified locally via a replace to the ai branch: clients build + twin tests green.
2026-07-16 11:47:10 -07:00
antje 74d94d1f3e ci(release): retire notify-universe — Hanzo CD owns git→cluster sync
The repository_dispatch deploy hub is gone (universe image-update.yml
removed in universe d07cf945; the dispatches were silently suppressed by
the flagged sender account regardless). Deploys are declared-tag bumps in
universe crs/, synced by Hanzo CD (ArgoCD, ns hanzo-cd) and reconciled by
the operator. [skip ci]
2026-07-16 11:36:10 -07:00
antjeandGitHub ce6c4dc374 deps: hanzoai/ai v1.813.1 -> v1.813.6 (balance-exempt routing config + enso family helper) (#314)
ai#102: /v1/get-routing-defaults + org-settings CRUD + routing-ledger
export are configuration metadata, never wallet-gated — unblocks reading
org routing defaults for $0-balance orgs and the operator platform flip.
Edge auto-routing billing tests green.
2026-07-16 11:28:33 -07:00
antje 2134876826 platform: allow the self-hosted fleet registry in the native build lane
registry.hanzo.ai/{hanzoai,luxfi,zooai}/ join the /v1/runner push allowlist —
Wave 0 of the native CI/CD migration. Until now only release.yml's crane
mirror could reach the fleet registry; the native BuildKit lane was
ghcr-only by policy.
2026-07-16 11:13:07 -07:00
hanzo-dev f0abd2116e fix(ci): version-assignment scanned the WHOLE registry — livelocked releases
The "atomic free-version assignment" step paginated every container version
(`gh api --paginate .../versions`) to find the max release number. As the
registry accumulated tags this grew unbounded and hung the step for 30+ min,
livelocking every cloud release. Container versions are created newest-first and
version tags are monotonic, so the max is always on the newest page — query one
bounded page (?per_page=100) instead of the full history. Fast + correct.
2026-07-16 11:11:39 -07:00
hanzo-dev ebf267908c refactor(ledger): drop redundant "core" — the ledger adapter is apps.ledger
Values, not places: the finance-backed credit-ledger adapter is qualified by its
namespace (apps.ledger), not a braided ledgercoreCredit compound. Rename the type
ledgercoreCredit → ledger, the file commerce_ledger.go → ledger.go, and scrub
"ledgercore" from prose (the ledger IS the core — "core" adds nothing). No behavior
change; admin/core tests green, changed packages build.
2026-07-16 10:18:47 -07:00
antje 4a64ef568b feat(chat): clients/chat — one /v1/chat tool-calling orchestrator
POST /v1/chat runs one LLM tool-calling round that lets a model manage a system
via tools. Composes existing cloud pieces, reinventing nothing:
- LLM routing + per-org reserve/settle billing: the ai subsystem's
  /v1/chat/completions, invoked in-process (Fiber Test) — the only path that
  both returns tool_calls AND carries the billing gate.
- tool plane (clients/tools): the org's registered MCP/registry tools are
  offered to the model and dispatched server-side (activation + price gated).
- capabilities: graph (advisory node-ops -> ops the client applies) and create
  (server-executed, tools = the org's registered MCP render services).
Returns {reply, actions, ops}. chat mounts before ai so /v1/chat resolves here
(the ai /v1/chat alias is shadowed); ai keeps /v1/chat/completions.
2026-07-16 10:02:29 -07:00
hanzo-devandantje 73632723f6 feat(ai): bump ai subsystem v1.813.0 → v1.813.1
Carries the PAID-Enso revert + the family learning loop: per-family-call RoutingEvents
+ shadow A/B (records what the learned engine would have picked), /v1/feedback signal
contract (up/down/regenerate/switch/abandon/accept/revert/rating/dismiss) with the
online reward forward to the engine's /route/observe, ROUTER_ADMIN_TOKEN service-auth
on the training-data exports, and Zen/Enso provider branding. Lights up /v1/router/stats
+ world.hanzo.ai (shadow-vs-served agreement).

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-16 09:53:56 -07:00
hanzo-dev f5d57e35f1 feat(ai): bump ai subsystem v1.812.0 → v1.813.0 — router policy, rewards, margin, DO backfill
Ships the per-org router policy (get/update-router-policy + the org > '*' >
conf fold on every auto route), the routing-reward ledger, the nano margin
ledger (costNano/billedNano/marginNano + unpriced flagging), and the
gaps-only DigitalOcean usage backfill (POST /v1/admin/usage/backfill-do,
dry-run default). The release image also re-embeds console@main
(CONSOLE_REF=main), picking up the console Router page (v8.4.137+).

Claude-Session: https://claude.ai/code/session_018PmFAHZvbBSTsuWyebwMra
2026-07-16 09:28:20 -07:00
hanzo-dev 8f61d57963 feat(credit): ONE ledger seam — commerce credit + admin grant mint into finance.Current()
The last mile of "one way to grant credit": cloud implements commerce's
creditledger.CreditLedger (v1.48.5) over the native finance ledger and injects it
at mountCommerce (EmbedConfig.Ledger). Now commerce's POST /v1/billing/credit AND
the admin.hanzo.ai grant (/v1/admin/customers/:org/credit) both mint into the SAME
per-org finance wallet the ai prepaid gate reads — a granted credit is immediately
spendable, no split ledger. The admin path drops its parallel finance.Deposit for
the one creditledger.Credit call (idempotency key rides through; commerce HTTP
deposit remains the split-deploy fallback).

- apps/commerce_ledger.go: ledgercoreCredit adapter (compile-time asserted against
  commerce's exported interface); org-pool wallet (Subject==Org); fails closed with
  no co-resident finance.
- apps/commerce.go: inject Ledger: ledgercoreCredit{} at mountCommerce.
- clients/admin/core/grant.go: grantDeposit prefers creditledger.Get() (the one
  ledger) over its own finance.Deposit.

Verified: changed pkgs build green on commerce v1.48.5 + ai v1.812.0; admin/core
grant tests pass. Ships with the ai free-tier removal (v1.811.0+) already on main.
2026-07-16 09:14:59 -07:00
antje 5bfe2842a1 ci(release): pass GIT_AUTH_TOKEN build secret — Dockerfile renamed the id from gh_token (46081689) but the workflow still passed gh_token, so the private console clone ran credentialless and the release failed 2026-07-16 01:50:00 -07:00
antje 4608168991 build: consume the standard GIT_AUTH_TOKEN build secret (was gh_token)
One secret id everywhere: BuildKit's gitsource convention (GIT_AUTH_TOKEN,
which the fabric's buildFrontendCmd already attaches) is also what the
Dockerfile's console-embed and go-mod fetch stages mount. gh_token was a
second name for the same credential.
2026-07-16 01:19:03 -07:00
antje a74c95abc2 deps: hanzoai/ai v1.812.0 + commerce v1.48.5 — reward ledger, router policy, connections import reach prod
ai v1.809.4 → v1.812.0: RoutingEvent reward ledger (/v1/add-routing-reward,
/v1/export-routing-rewards), per-org router policy + observability, Enso
public arms + retrain-status, connected-provider usage import (OpenAI/
Anthropic), own-brand god-view gate (TokenIsOwnBrand), Bearer-aware
get-cloud-usages, billing nano margin ledger, unpriced-model flagging.

commerce v1.48.2 → v1.48.5: mint-gated org-keyed credit primitive +
injected-ledger seam; fixes the phantom luxfi/cevm test import that broke
go mod tidy for every consumer (this repo included).
2026-07-16 01:16:12 -07:00
antje b7e4843cd7 feat(fabric): GIT_AUTH_TOKEN build secret — private-repo fetches for the build Jobs
The buildkit Job now surfaces the console-git-token Secret (optional) as the
GIT_AUTH_TOKEN env, and buildctl attaches it as the same-named build secret;
BuildKit's gitsource presents it as the HTTPS credential for the git context.
Fixes the fabric's inability to build PRIVATE repos (github.com/hanzoai/cloud
itself: 'could not read Username' — the rel_HvInGKU failure). Public repos and
Secret-less clusters fetch anonymously exactly as before.
2026-07-16 01:15:07 -07:00
antje 9b97ca9164 feat(git): public repos — anonymous read for the build fabric
A repo gains a visibility bit: PATCH /v1/git/repos/:name {"public":true}
(or create-time "public"). Public grants ANONYMOUS upload-pack/info-refs
only — receive-pack and the whole control plane stay org-authed, and a
private or missing repo answers the same uniform 404 so anonymous probing
cannot enumerate.

This is what lets the credential-less buildkit build Job (launchDirectBuild
git context) fetch from the embedded git server — the same reason public
GitHub repos build with no env. Private-repo builds remain a later
GIT_AUTH_TOKEN feature.

resolvePackRepo grows the allowPublic branch (fetch-side only): anonymous
callers address org-level repos by the orgRE-validated :org path segment;
the path-vs-identity guard for authenticated callers is unchanged.
2026-07-16 01:05:30 -07:00
antjeandGitHub 4b255e8e9a test(platform): end-to-end git push -> buildFromPush enqueue proof (#311)
Wire a REAL smart-HTTP git push through the actual production seam
(cloud.RegisterPushBuilder <-> cloud.OnGitPush) into the real platform
push builder, and assert the matching app's build is enqueued (a
building deployment for the pushed commit). The two halves were covered
in isolation (clients/git TestPushFiresBuildTrigger; platform
TestBuildFromPush_LaunchesMatchingApp) but nothing connected a live push
to the real builder end to end. Pure-Go dev build (CGO_ENABLED=0).
2026-07-16 00:45:07 -07:00
hanzo-dev 41be25c713 Merge land/slack-on-bridge: Slack chat path onto the generalized bridge — one chat code path 2026-07-16 00:15:57 -07:00
hanzo-dev 301706dd54 refactor(integrations): Slack chat path onto the generalized bridge — one chat code path 2026-07-16 00:13:59 -07:00
zandGitHub 746b42209f Merge feat/bots-control-plane: decomplect the bot plane, proxy instead of duplicate
Deletes clients/bot — a place-name that had collected three concerns (a mount, a
transport, and two unrelated domain wire protocols). One value per module:
  run       -> clients/bots      /v1/bots (no store)
  dispatch  -> clients/coding    /v1/coding-tasks
  transport -> clients/runtime   address, identity, framing, cleartext policy
  machine   -> clients/visor     /v1/compute/bots (moved off /v1/bots)
  session   -> clients/agents    the one registry (reverted to main)

Fixes a live route collision: visor's listBots silently won GET /v1/bots (the
router merges byte-identical patterns, first wins), so cloud served machine rows
as runs and orgs' real runs were invisible.

POST /v1/bots/run now returns 501 instead of charging $1.00 for a bot that never
booted -- the runtime has no launch endpoint. Stop fails closed: a bare 404 is
502, only a structured error body means already-stopped.

Net -613 lines. runtime never imports bots/coding; the reverse is a compile-error
cycle, so the one-way dependency is structurally enforced.
2026-07-15 23:27:48 -07:00
zandGitHub 58d39546b1 Merge fix/billing-balance-collision: read prepaid balance from the finance ledger, not a self-call
Cloud's /v1/billing/balance proxy was the only handler registered (commerce's
GetBalance is behind //go:build cloud, never compiled in) so it called itself,
depth 2. Reads the finance ledger via the existing finance.Current() seam and
single-sources the subject from aiobject.BillingSubject so console and gate
cannot drift.
2026-07-15 23:27:02 -07:00
zandGitHub a7fcf77247 Merge pull request #310 from hanzoai/bump/ai-v1.809.4
chore(ai): bump embedded ai v1.809.3 -> v1.809.4 (enso comp cold-cache fix)
2026-07-15 23:07:00 -07:00
hanzo-dev e324fdb236 chore(ai): bump embedded hanzoai/ai v1.809.3 -> v1.809.4 (enso comp cold-cache fix)
Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-15 23:06:41 -07:00
hanzo-dev d678ba2f6b bots: proxy the runtime instead of copying its state; name the transport
Red found the substrate was wrong: cloud kept its own registry of runs. It minted
an id the runtime had never heard of, so /v1/bots listed runs that did not exist,
stop closed records for runs that were never started, and run charged $1.00 for a
bot that never booted — the runtime has no launch operation at all, and nothing
in run ever contacted it. The registry that exists is the runtime's own tenant
store; it is the only thing that knows whether a sandbox is alive.

So cloud owns policy and the runtime owns the run:
  - GET /v1/bots and POST /v1/bots/:runId/stop proxy the runtime, gated by the
    validated principal and org. The org is cloud's, never the client's, and the
    runtime keys every run under tenants/{org}/ — so a foreign run resolves under
    the caller's org, where it does not exist, and 404s.
  - POST /v1/bots/run returns 501. There is no launch operation to call, so the
    honest answer is that it is not implemented. It no longer charges.
  - The agents session plane is reverted verbatim: no surface column, no Agent
    filter, no SessionOpen, no in-process stop. It never should have carried a
    second copy of the runtime's state.

Absence is only meaningful from a callee that could have said otherwise, so the
transport separates ErrNotFound (the operation ANSWERED absent) from ErrNotServed
(no such operation). A runtime without the stop route reports absent for every
run; treating that as "already stopped" made a stop that cannot fail. It is 502.

Decomplect the transport: clients/bot was named for the host it dials and braided
three concerns — an ops face plus two unrelated domain protocols. It is now
clients/runtime, a domain-free transport (address, identity, framing, cleartext
policy, /v1/bot/* ops face) that must not import bots/coding. Each domain owns its
own wire stub (bots/wire.go, coding/task.go), so the ZAP swap per HIP-0106/0120 is
a seam swap. Wire spec bot -> runtime; cmd/bot -> cmd/runtime.

The duplicate-route guard was a no-op: the router MERGES byte-identical patterns
into one route with chained handlers, so counting entries never saw the collision
it guarded. It now asserts one handler per route, and a test proves it fires on
the original bug. Fiber's Test() defaults to a 1s wall-clock deadline, which made
the isolation guards flake under load; they now pass an explicit timeout.

Route table unchanged: /v1/bots (runs), /v1/compute/bots (machines), /v1/bot/*
(runtime ops).
2026-07-15 22:52:24 -07:00
hanzo-dev c24b601825 feat(git): JSON read/browse surface for the console repo-browser
The console repo-browser (hanzoai/console products/git) needs machine-readable
refs/tree/blob/commits/readme, but git only served those as HTML (ui.go) + the
repo-CRUD control plane. Add the JSON twin, reusing ONE set of go-git read
helpers so the HTML + JSON surfaces can never drift:

  GET /v1/git/repos/:name/refs                   → { branches, tags, default }
  GET /v1/git/repos/:name/tree?ref&path          → { entries:[{name,path,type,size,mode}] }
  GET /v1/git/repos/:name/blob?ref&path          → { path,size,encoding,content,binary,truncated }
  GET /v1/git/repos/:name/commits?ref&path&limit → { commits:[{sha,shortSha,message,author*,date}] }
  GET /v1/git/repos/:name/readme?ref             → { path, content, encoding }

- browse.go: the handlers + DTOs (mirror the console GitApi normalizers verbatim).
  ref+path ride as ?ref=&path= query params (the UI's own convention) so a slashed
  branch is unambiguous. Reuses org()/findRepo()/openGit()/resolveRef()/
  cleanTreePath(). Org-scoped (X-Org-Id); a repo outside the caller's org 404s.
  Distinct trailing segments — never shadow the :org/:repo smart-HTTP routes.
- ui.go: findReadme → readmeAt (returns filename+content); the ONE readme scan now
  backs both the HTML repo home and the JSON /readme (DRY, no duplication).
- browse_test.go: seeds a nested tree + README + binary file, asserts every endpoint
  + org isolation + honest 404/403 + empty-repo refs.

CGO_ENABLED=0 go test ./clients/git/ green (full package); go vet + build clean.
Stays v1.x.x (Go module). Ships with console@main on the next cloud release.
2026-07-15 22:23:09 -07:00
hanzo-dev 3d2b7c87b5 fix(billing): read the prepaid balance from the finance ledger, not a self-call
GET /v1/billing/balance and /v1/finance/balance proxied to commerce at the SAME
path they are registered on. commerceinproc publishes the shared zip app and
re-dispatches by path, and commerce's own /v1/billing/* routes are never
registered in this binary (api.Route runs only from commerce's mount.go, which
is //go:build cloud; cloud ships -tags "libsqlite3 sqlite_fts5"). So the proxy
re-entered itself, hit its own sign-in gate with no principal, and reported
"billing upstream status 500".

Co-resident, the prepaid wallet is cloud's own finance ledger: wireFinance points
the ai gate's balance read at it, the edge meter debits it (metering.fetchAvailable
already resolves finance.Current() first), and an admin grant credits it
(core.grantDeposit already prefers it). Read it directly through that same seam.
The commerce S2S read stays as the split-deploy fallback.

The subject comes from ai/object.BillingSubject — the function the ai prepaid gate
itself resolves — instead of a re-implemented copy. cloud and ai each keeping their
own copy of that rule is what let them drift: the console scoped to the org while
the gate scoped to "org/user", so the view showed a funded org while the gate
refused the member.

Fail posture unchanged: a balance that cannot be read is UNKNOWN and surfaces as
502 — never rendered as a zero balance. The sign-in gate and org scoping are
untouched; the org still comes from the validated principal only.

Tests: self-dispatch pinned at depth 2 (the seam's real mechanics, which the
existing SetHandler-stub test cannot see); router semantics probed (byte-identical
patterns MERGE and silently shadow; equal-specificity param-name conflicts PANIC at
registration; most-specific wins over registration order); balance regression,
gate-subject parity, unreadable-is-not-zero, sign-in gate, and cross-org isolation.
2026-07-15 22:16:46 -07:00
antje 7dd7a9b4dd feat(insights): /v1/insights — the unified native surface on the ONE analytics engine
A wire adapter, not a second pipeline: POST /v1/insights/e accepts PostHog-
shaped payloads (single or {batch}) from @hanzo/insights and any compatible
SDK, maps $-properties onto the native CaptureEvent, and rides the SAME
capture path (tenant gate -> normalize -> scrub -> hanzo.events). GET
/v1/insights/events is the console's tenant-scoped recent-events read; GET
/v1/insights/health reports the surface. Flags deliberately stay at /v1/flags.

Scale path stays stateless: accept on any replica, pooled batch INSERT sink;
the queue-buffered (mq/pubsub -> Datastore consumer) upgrade swaps the exec
behind buildEventsInsert with no handler changes.
2026-07-15 21:35:30 -07:00
zandGitHub 8d719c9821 Merge pull request #309 from hanzoai/bump/ai-v1.809.3
chore(ai): bump embedded ai v1.809.2 -> v1.809.3 (comped preview balance fix)
2026-07-15 21:30:55 -07:00
hanzo-dev f58f0b7c2a chore(ai): bump embedded hanzoai/ai v1.809.2 -> v1.809.3 (comped preview bypasses enforceBalanceGate)
Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-15 21:30:09 -07:00
hanzo-dev 94ec6ecbb9 Merge land/hybrid-connectors: injective tenant S3 key (close cross-tenant collision) + orgPathSafe guard 2026-07-15 21:21:56 -07:00
hanzo-dev f7fd44618c fix(projects): injective tenant S3 key via verbatim principal.Org (close cross-tenant collision) + orgPathSafe traversal guard 2026-07-15 21:21:25 -07:00
hanzo-dev 3ddbe91e63 bots: state the list cap explicitly
The published contract has no pagination, so the list is capped either way; set
it at the store maximum here rather than inherit the store's 100-row default.
2026-07-15 20:52:36 -07:00
hanzo-dev 8360315345 bots: give the three "bot" values one namespace each; make the run control plane native
GET /v1/bots was registered twice: clients/visor (bot machines) and clients/bots
(bot runs). The router resolves byte-identical patterns by first-registration
without panicking, and visor mounts first, so visor's machine list answered the
console's run list and clients/bots.list was unreachable. The console normalized
machine rows into run rows, yielding one blank-runId row per kind=bot machine
with a dead sessionUrl, and hid the org's real runs.

Name the values apart, one home and one route namespace each:
  - bot run     -> clients/bots  /v1/bots            (unchanged; the console + CLI contract)
  - bot machine -> clients/visor /v1/compute/bots    (moved; a machine is compute)
  - bot runtime -> clients/bot   /v1/bot/*           (passthrough for runtime-owned ops)

Make the run control plane native. clients/bots holds no store: a run is recorded
on the agents session plane under agent label "bot", so the run id is the session
id and one registry serves every kind of agent work. list reads it org-scoped;
stop resolves (org, runId) against that record and drives the runtime only after
ownership is proven, so a run of another tenant is a 404 the runtime never hears
about. An unreachable runtime is a 502 with the record left live.

Two seams (Runs, Runtime) are injected in adapters.go, the only file in
clients/bots importing agents/bot, so handlers unit-test against fakes.

agents: sessions carry a surface (the modality a session runs on, matching the
runtime's own origin.surface) via the established additive-column migration;
SessionFilter gains Agent so a product face reads only its own sessions;
OpenSession takes SessionOpen; StopSession is the single-session twin of
StopSessions and shares its one write path (stopOne).

Contract change: a run id is now the session id, not bot_<hex>. No bot_ id was
durable anywhere -- the old run handler minted an id and stored it nowhere -- so
there is nothing to migrate. Ids stay opaque to clients.
2026-07-15 20:38:54 -07:00
antje 6781eed94f cli/gpu: heartbeat the claimed activity + fleet presence DURING a render (goroutine in claimAndRun) — a >120s render no longer drops the machine offline mid-render; fixes BYO-GPU fix/compose/render hitting the deadline + going offline 2026-07-15 20:21:31 -07:00
zandGitHub cd082ca1cb Merge pull request #308 from hanzoai/bump/ai-v1.809.2
chore(ai): bump embedded hanzoai/ai v1.809.1 -> v1.809.2 (Enso limited-preview gating)
2026-07-15 19:19:07 -07:00
hanzo-dev 6c7a89f8d9 chore(ai): bump embedded hanzoai/ai v1.809.1 -> v1.809.2 (Enso limited-preview gating)
Lands the Enso limited-preview gating into the live api.hanzo.ai binary
(cloud embeds ai in-process via ai.Mount). v1.809.2 adds ai's Enso family
routing (ENSO_URL -> enso pod) + waitlist gating: ModelAccess visibility in
/v1/models, 403 request-access for ungated SKUs, comped bypass of the balance
gate for granted callers, POST /v1/models/:model/access, org `hanzo` seed.

Independent of the concurrent zen v1.3.0 -> v1.3.7 bump (#307), which this
branch is based on top of.

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-15 19:16:00 -07:00
hanzo-dev b5b1a09952 Merge land/chat-connectors: generalized ChatBridge + Discord/Teams/Telegram adapters for hanzo.chat 2026-07-15 19:11:41 -07:00
hanzo-dev 767e089410 land(chat): generalized ChatBridge + Discord/Teams/Telegram adapters for hanzo.chat 2026-07-15 19:09:52 -07:00
zandGitHub 5cbf1ed90e Merge pull request #307 from hanzoai/fix/zen-bump-clean
fix(zen): bump embedded hanzoai/zen v1.3.0 → v1.3.7 (1M ladder fix)
2026-07-15 19:04:13 -07:00
hanzo-dev 9d8f86d191 fix(zen): bump embedded hanzoai/zen v1.3.0 -> v1.3.7 (1M ladder need() fix)
The cloud binary serves the zen* family IN-PROCESS via zen.Mount, so the
embedded module version — not the zen pod image — is what serves zen5. v1.3.0
sized the ladder rung by the byte estimate alone: a ~230K-token prompt with a
32K max_tokens budget estimated ~258K (under glm-5.2's 262144 cap), stayed on
glm-5.2, which then saw prompt+output = 262145 and 400'd. v1.3.7 sizes the rung
by need() = messages + tool schema + max_tokens, overflowing a >262144 total to
the 1M deepseek-v4-pro rung. Brings the Enso family + gating in-binary too.

Claude-Session: https://claude.ai/code/session_015Z1iLf7QBrq1LhignJrzDw
2026-07-15 19:03:37 -07:00
antje f49a6ac2b2 fix(image): runtime needs libgcc — the flags staticlib references _Unwind_*
The hanzo-flags Rust staticlib compiles with unwinding (panic-guarded FFI);
its _Unwind_* references resolve from libgcc_s, which the alpine runtime did
not carry — /cloud failed relocation at exec ('Error relocating /cloud:
_Unwind_GetIP: symbol not found') and smoke red-gated the release. Add libgcc
to the runtime apk set.
2026-07-15 18:47:52 -07:00
hanzo-dev 92004893be Merge land/agent-deploy-sites: agent AI-brief site build+deploy to <slug>.hanzo.app, metered per deploy 2026-07-15 18:41:36 -07:00
hanzo-dev 3d294ce07c land(sites): agent AI-brief site build+deploy to <slug>.hanzo.app, metered per deploy 2026-07-15 18:40:05 -07:00
antje 1b552d890c feat(flags): native flag engine — stateless Rust FFI + SQLite per project, /v1/flags
native/flags: hanzo-flags, a stateless Rust staticlib with PostHog-compatible
evaluation — the exact Insights rollout hash (sha1 first-15-hex / LONG_SCALE,
pinned by test vectors), the full vendored property-operator set (exact/regex/
semver/date/relative-date...), condition groups (variant-override groups first),
multivariate cumulative selection, payloads. Pure (defs JSON, ctx JSON) ->
response JSON behind a panic-guarded C ABI: hanzo_flags_evaluate/_free.
65 tests green.

clients/featureflags becomes the NATIVE engine (no external evaluator, no KV,
no network): definitions in per-(org, project) SQLite via cloud.OrgDB
(encrypted at rest via cek), hot in-memory platform snapshot (TTL 15s),
evaluation over cgo. The INSIGHTS_FLAGS_URL HTTP proxy is gone. Bool/Int/
String and the admin Board keep their shapes; sources are flags -> env ->
default (first cockpit write creates the definition — env fallback intact
until then, zero regression). engine_stub (!cgo) degrades loudly, fail-safe.

/v1/flags (org-scoped via principal, project via X-Project-Id): POST /v1/flags
(+/decide alias) evaluate; GET/PUT/DELETE /v1/flags/defs[/:key]; GET
/v1/flags/activity; GET /v1/flags/health. PUT /v1/admin/flags/:key (SuperAdmin)
is the cockpit write path through SetPlatformSwitch — flips apply immediately
in-pod, peers converge within one TTL.

Build: Dockerfile flagslib stage (rust:1-alpine musl staticlib, --locked) copied
to the exact ${SRCDIR}-relative cgo link path; make native; hanzo.yml
native-flags step + clients/featureflags in the hermetic unit gate.
go test ./clients/featureflags ./apps green (FFI live).
2026-07-15 18:38:01 -07:00
zeekayandClaude Opus 4.8 23d9c4809a fix(console): white-label the embedded console <title> by request Host
The console SPA shipped in the unified cloud binary is a STATIC export of
hanzoai/console whose <title> is baked to the default (Hanzo) brand at build
time. The embed cannot read the request Host, so every host — including
console.lux.cloud and console.zoo.cloud — served "Hanzo Cloud Console" in the
browser tab, a white-label violation. (The standalone Next.js app is host-aware
via generateMetadata, but it is retired from this serving path: cloud serves
the console in-process from the go:embed static export.)

Rewrite the SPA shell's <title> at the serving layer (serveIndex/indexFor) to
the request host's brand, reusing the existing brands registry (BrandForHost):
console.lux.cloud -> "Lux Cloud Console", console.hanzo.ai -> "Hanzo Cloud
Console" (unchanged), console.zoo.cloud -> "Zoo Cloud Console". Matches
hanzoai/console's own `${brandName} Console` output — one source of truth. The
Hanzo/default host returns the embedded bytes unchanged (no regression); a shell
with no <title> is never altered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 18:25:22 -07:00
hanzo-dev 9c2eb2cf64 Merge land/featuregate: per-service waitlist-mode control plane 2026-07-15 18:10:27 -07:00
antje 0414fe2975 deps: bump ai v1.808.1 -> v1.809.1
Brings live: get-cloud-usages Bearer + balance-exempt (usage panel works at
$0), the /v1/ai/connections usage-import endpoint. Console changes ride the
same release via CONSOLE_REF=main embed. Build green.
2026-07-15 17:38:07 -07:00
hanzo-dev 6529cf7d3e land(featuregate): per-service waitlist-mode control plane
Global SQLite registry {service, hosts, waitlistMode} + admin board/toggle
(/v1/admin/services*, /v1/featuregate/mode) + native Enforce middleware and
IAM-backed per-user approval resolver. Ported from recover/featuregate; dropped
the init()/cloud.RegisterWithShutdown self-registration in favor of the explicit
apps.Wire() MountSpec (order after admin, before tasks) + frozen wire_test row.

Distinct from clients/featureflags (a global read-only Insights waitlist_open
switch); this is the per-host launch lever with in-binary enforcement.

Claude-Session: https://claude.ai/code/session_01SpMZ69ur3tjAXCiwaa7Wv2
2026-07-15 13:20:25 -07:00
z 33072f27b3 platform: guard IAM object-store against a nil engine + commerce v1.48.2
Two co-residence fixes surfaced by the live founder-journey e2e:

1. /v1/platform/projects (authed) returned 500 'runtime error: invalid memory
   address' — iamobj.GetProjects/AddProject deref the package-global ormer.Engine,
   nil until the co-resident IAM subsystem initializes it. A nil store must fail
   cleanly: the iamStore() guard converts a nil-deref into a typed 503. (The store
   is initialized once iam co-mounts — v1.801.21 embedded-SQLite isolation.)
2. Bump commerce v1.48.1 -> v1.48.2: ErrorHandlerJSON preserves a downstream
   typed HTTP status, so a co-resident subsystem's 401/403/404 (e.g. platform's
   'X-Org-Id required') is no longer flattened to 500 by commerce's /v1 mount.

Regression tests: nil-store -> 503, success + real-error passthrough.
2026-07-15 13:11:54 -07:00
hanzo-dev ea3ccdbccd controlplane seam (c): R1 — first-writer-wins registry + self-authorized Rekey (RED R1)
The ValidatorRegistry is the trusted key source for the whole cert, so key binding must be rogue-key-resistant BEFORE the driver sources idVerifier into the cert verifier. Register is now first-writer-wins: a node already bound to one ML-DSA key may not be silently re-bound to a DIFFERENT key (ErrIdentityKeyConflict); idempotent re-register of the identical key stays allowed. The ONLY sanctioned rotation is Rekey(node, newPub, authSig) — self-authorized by a signature under the node's CURRENT key over rekeyTBS under a DISTINCT rekey context (not popContext/certContext); an attacker without the current secret key cannot rotate. This is the registry action a consensus-ordered OpRekeyValidator applies (op plumbing lands with the RSM rewire).

5 R1 tests green; existing OnePodOneShare + full suite unaffected.
2026-07-15 12:41:21 -07:00
hanzo-dev 8417cba676 controlplane seam (c): two-threshold self-guard + raw-craft verify tests (RED findings 1,3)
Finding 1: guardBFTFloor(len(keys), quorumWeight) fails closed unless the floor is the byzantine-safe BFT quorum (2n/3+1) for the validator-set size — so a mis-wired wallet-custody t (=3 for n=5) can neither compose nor verify a cert even if a future driver passes it. Called at the top of ComposeControlPlaneCert and VerifyControlPlaneCert. This is the exact two-threshold trap inc-1 hit (cluster.go wiring Pulsar threshold = quorum), now impossible in the cert core.

Finding 3: three raw-craft verify-side tests drive hand-built malicious certs (bypassing the honest composer) straight at VerifyControlPlaneCert — sub-quorum threshold-lie (ErrQCThresholdBelowFloor), attacker-key stuffing (ErrQCMerkleInclusion), weight inflation (ErrQCAggregateWeight) — plus a self-guard test (t=3 refused). 14 cert tests green.

Flag still false; ceremony untouched; existing byzantine suite green.
2026-07-15 12:41:21 -07:00
hanzo-dev 493d4ef01a controlplane inc-2 seam (c): real independent-sig ConsensusCert crypto core
The shipped Gen-3 weighted-quorum cert the design chose over the blocked threshold-Pulsar path. Each pod signs the canonical quorum message INDEPENDENTLY with its seam-a ML-DSA-65 key under a DISTINCT cert context (RED R4: certContext != popContext); the cert is a quasar.ConsensusCert carrying one EvidenceWeightedSigSet leg (a WeightedQuorumCert of N independent FIPS-204 sigs + weighted-Merkle quorum). Verification is quasar.VerifyConsensusCert under a control-plane ConsensusCertPolicy that requires the weighted-sig-set PQ leg — the shipped, audited verifier; NEVER the structural QuasarCert.Verify. No DKG, no threshold aggregate, no unshipped luxfi/pulsar core: soundness rests only on stock FIPS-204 verify + the weighted-validator-set Merkle commitment. Composes against luxfi/consensus v1.35.32 (BuildWeightedValidatorSet / BuildWeightedQuorumCert / VerifyConsensusCert).

VerifyControlPlaneCert binds the cert to the caller's expected position before the cryptographic verify (VerifyConsensusCert pins validator-set+policy but not the caller's height/round/block).

10 standalone crypto tests green: real cert verifies under policy; below-quorum / missing-leg / forged-sig / rogue-signer / wrong-position / wrong-validator-set all REJECTED with exact typed errors; R4 proven (a popContext sig is rejected as a cert sig); deterministic composition. Self-contained (does not touch the ceremony); existing suite stays green. Flag NOT yet flipped — ceremony rewiring + the ProductionBCCSigningReady() flip + stub deletion follow.
2026-07-15 12:41:21 -07:00
hanzo-dev fb5a9024db deploy: rename the CD surface gitops -> /v1/deploy
The ArgoCD fork now lives at hanzoai/deploy (hanzoai/gitops redirects to it), so
the cloud CD control plane takes the matching single-word name: clients/gitops ->
clients/deploy, /v1/gitops/* -> /v1/deploy/*, and the subsystem name (Wire entry,
enablement key, health surface) is 'deploy'.

Same plane, same ArgoCD-grade fleet view over our own App CRs — applications,
resource tree, live manifest + diff, logs, sync, rollback.
2026-07-15 12:30:57 -07:00
antjeandGitHub fbf347d851 cloud(cmd): generate standalone connectorruntime binary
Completes the per-app-binary invariant: connectorruntime (HIP-0126) is in apps.Wire() but its generated cmd stub was dropped by a stale reconciliation merge. go generate ./apps restores it. cicd green.
2026-07-15 11:18:51 -07:00
hanzo-dev 3322f7377f Merge fix/iam-coresidence-db-isolation: isolate embedded IAM SQLite (unblock iam+ai) + CLOUD_ENABLE_STAGED
# Conflicts:
#	clients/iam/iam.go
2026-07-15 10:40:00 -07:00
hanzo-dev a389074817 Merge chore/regen-cmd-link: generate cmd/link standalone binary 2026-07-15 10:33:42 -07:00
antje 83d7e65e8f cloud(ci): fix test gate path ./subsystems/ -> ./apps/ (main was red)
The subsystems/ -> apps/ rename merge (345264d2) missed hanzo.yml's test
gate, which still ran `go test ./subsystems/` — a directory that no longer
exists — so every main CI run failed "./subsystems [setup failed]". Point
it at ./apps/ (the renamed composition root). Unbreaks the release gate.
2026-07-15 10:21:30 -07:00
hanzo-dev cb579a8a79 Merge origin/main (agents oversize-target fix) into branch integration 2026-07-15 10:19:28 -07:00
hanzo-dev 3662f6982d Merge fix/402-credential-ordering: prefer fresh login JWT over stored hk- key in hanzo code 2026-07-15 10:18:18 -07:00
hanzo-dev 8813dd68c5 Merge feat/connector-runtime-land: native in-process connector runtime (goja) 2026-07-15 10:17:08 -07:00
hanzo-dev a5f94b0ef2 fix(agents): reject an oversize target GPU array at the handler
Red LOW-2: body.Spec.GPUs was only truncated post-decode by Sanitize
(cap 32). register + PATCH now return 400 for a GPU array larger than the
cap instead of silently truncating, so an absurd payload is refused up
front and the client learns the bound. The 4MiB body limit already caps
the transient decode allocation; a normal-sized list still registers.
2026-07-15 10:14:47 -07:00
antje 935974d230 cloud(cmd): generate missing standalone link binary (go generate ./apps)
The link app (unified AI login-manager registry, /v1/links) landed in
apps.Wire() without its generated cmd stub. Regenerating reconciles the
per-app-binary invariant: every Wire() app builds standalone via
apps.ServeSingle AND mounts into the unified binary. Idempotent.
2026-07-15 10:02:13 -07:00
hanzo-dev 4d42d6719e Merge origin/main (agents run-target) into apps/ rename integration 2026-07-15 09:49:42 -07:00
hanzo-dev c093a93d34 feat(agents): carry machine capability + live metrics on a run-target
A linked computer now reports what it IS (os/arch/cpus/memory/gpus, "spec")
and what it is DOING now (loadavg/memory/gpu-util, "metrics") so mission-
control can show which machine an agent runs on and whether it can take more
work — without copying the fact onto every session.

- targetspec.go: Spec/Metrics/GPU value types, JSON column codecs, and a
  total Sanitize that bounds strings/counts/sizes and coerces floats finite,
  so a hostile client can neither bloat the row nor smuggle a NaN/Inf.
- agent_targets gains spec/metrics/metrics_at (crashloop-safe addColumns,
  PRAGMA-guarded, no new index); register + PATCH accept them; a metrics
  PATCH is a heartbeat and the server owns the staleness clock (a client
  can't forge At).
- register upserts by (org, host) so re-linking the same machine refreshes
  one target instead of piling up duplicates.

Tests: sanitize bounds, store round-trip, GetTargetByHost org-scope, HTTP
capability+heartbeat, upsert-by-host. Existing target tests stay green.
2026-07-15 09:45:44 -07:00
hanzo-dev 68eebac230 fix(apps): add link mount to frozen wire-order fixture (main was red)
The feat/link-registry merge (669fee5) added the `link` mount to Wire() —
{Name:"link", after agents} — but never updated the frozen mount-order fixture,
so TestWireOrderMatchesFrozen failed on main (84 specs vs 83 frozen). This merge
inherited that break; adding the missing frozen entry (link, no health, has
shutdown) at its Wire() position makes apps green again.

Claude-Session: https://claude.ai/code/session_01SpMZ69ur3tjAXCiwaa7Wv2
2026-07-15 09:43:55 -07:00
hanzo-dev 345264d2f5 Merge feat/per-app-cmd-binaries: subsystems/ -> apps/ rename + per-app cmd binaries
# Conflicts:
#	apps/wire_seams.go
2026-07-15 09:39:39 -07:00
hanzo-dev 888d265469 fix(link): scope login-out session stop to the revoking user
A link revoke tore down live sessions by matching only {org, host,
provider, account}. Those fields come from a link row the caller sets at
upsert, so any org member could stop another member's sessions by
registering a wildcard link (e.g. provider-only) and revoking it.

Make Actor mandatory in agents.SessionMatch and AND it into the query.
The link adapter derives it from the revoking user's subject
(agents.BillingActor), the single place that binds a stop to the caller's
own sessions, so a stop/count can only ever reach that user's sessions.
A match with no actor stops nothing (fail-closed).

Tests: agents.TestStopSessions_ActorScoped (wildcard, host-forge,
no-actor fail-closed, count scope, own-account teardown) and
link.TestRevokeCannotStopCoTenantSessions (full stack through the real
adapter, co-tenant survives). TestRevokeStopsSessions stays green.
2026-07-15 09:31:20 -07:00
hanzo-dev e4a80c7de6 Merge branch 'feat/link-registry' into _mergetmp 2026-07-15 03:32:21 -07:00
hanzo-dev 669fee5cba feat(link): unified AI login-manager registry (/v1/links)
The org+user-scoped registry of which provider accounts (Claude Max, ChatGPT
Plus, a Hanzo/api key) a developer has signed into, on which machines, with each
account's latest usage snapshot — the cross-machine view console renders and the
source the redundancy route policy reads.

- clients/link: the Link atom (no secret — metadata + usage snapshot only),
  per-org SQLite store (org+subject leading-bound, upsert-on-identity, revoke),
  the /v1/links surface, and a pure RoutePolicy (Plan) that orders a user's linked
  accounts for redundancy (two Claude Max, then the metered API backstop) carrying
  the billing mode per candidate. The store holds no metering client — a
  subscription's usage is metered for visibility only and never charges commerce.
- clients/agents: a session now carries the linked account it ran under
  (Provider/Account tag), and StopSessions/CountActiveSessions expose the
  in-process action a link revoke takes to stop the sessions under a revoked
  account/device. Backward-compatible session migration (addColumns).
- subsystems: mount link after agents so a revoke can stop its sessions.

Org+user fail-closed isolation, subscription-vs-api-key billing distinction,
and revoke-stops-sessions are all tested (build/vet/gofmt clean; race+CGO green).
2026-07-15 03:31:37 -07:00
hanzo-dev 0b69af3e62 chore(cloud): bump hanzoai/ai v1.808.0 → v1.808.1 (relay reasoning normalization)
Pulls the DeepSeek <think></think> strip into api.hanzo.ai: reasoning-inlining
upstreams (zen5-pro/zen5-flash → deepseek-*) no longer leak the </think> template
token into the visible answer via the Anthropic-translation path that `hanzo code`
uses. Also carries the hk-key 402 tenant-gate fix. Builds clean (server + hanzo CLI).

Claude-Session: https://claude.ai/code/session_01SpMZ69ur3tjAXCiwaa7Wv2
2026-07-15 03:09:00 -07:00
zeekay 78d299e6b4 release: mirror via crane — IAM token realm rejects buildx's multi-scope request (crane single-scope proven E2E) 2026-07-15 02:59:17 -07:00
hanzo-dev f766c8aec1 feat(cloud): per-app standalone cmd binaries via apps.ServeSingle + generator
Each app now builds as its own standalone binary AND still mounts into the
unified cloud binary — one source of truth (apps.Wire()). Two pieces:

1. apps.ServeSingle(name) — the ONE way to run a single app standalone: validate
   the name against Wire(), then cloud.Serve(Wire(), []string{name}). It is the
   path cmd/hanzo's 'hanzo <name>' already uses; promoting it to apps (which
   already imports cloud, so no cycle) lets every cmd/<app> stub reuse it instead
   of re-implementing the dispatch. Adding an app in Wire() is still the one edit.

2. cmd/gen-app-cmds — a tiny generator (go:generate directive in apps/apps.go)
   that parses Wire()'s {Name: "..."} literals and writes one cmd/<app>/main.go
   stub per app (apps.ServeSingle("<app>")). Generated, not hand-maintained; a
   re-run is idempotent (writes only on content change). 80 unique apps today.

Verify: go build ./apps/... green; apps.ServeSingle added; go generate ./apps is
idempotent; go test ./apps/... green (TestWireOrderMatchesFrozen at 84 specs); a
sample of generated cmd stubs (kms/account/agents/platform/storage/audit/
analytics/ads/ingress/billing/o11y) build standalone green. The full ./cmd/...
build is heavy (80 binaries x the cloud tree) and needs CI parallelism; the
stubs themselves are sound.
2026-07-15 02:46:42 -07:00
zeekay 0a41f07085 Merge remote-tracking branch 'origin/main' into ci-finish 2026-07-15 02:43:03 -07:00
zeekay bb3eb01f5e ci: mirror uses direct REGISTRY_USER/PASSWORD secret (Free plan hides org KMS secrets from private repos); test gate skips the cek env-gated test 2026-07-15 02:42:50 -07:00
hanzo-dev cabbfa297a refactor(cloud): rename subsystems/ -> apps/ (the composition root)
The cloud binary mounts ~84 'subsystems' into one unified binary; they read as
apps, so the package follows. Purely internal: dir subsystems/ -> apps/, package
'subsystems' -> 'apps', the one file subsystems.go -> apps.go. Three import sites
updated (cmd/cloud, cmd/hanzo). Broken path/filename references in comments
(subsystems.Wire, subsystems/commerce.go, subsystems.go) -> apps.*; the package
doc + LLM.md/docs paths follow.

No external breakage: the package is same-module (never in go.mod), no external
module imports it. The frozen-order test TestWireOrderMatchesFrozen compares
MountSpec.Name strings, not the package name — passes unchanged at 84 specs.

Standalone via 'hanzo <name>' and per-app cmd binaries are unchanged by this
rename (D2 adds the cmd binaries on top).

Verify: go build ./... green; go vet ./apps/... ./cmd/... clean; go test ./apps/...
green; TestWireOrderMatchesFrozen green. cmd/cloud TestMountAllAndServeHealth
fails identically on clean main (needs CLOUD_KMS_MASTER_KEY_REF), not this change.
2026-07-15 02:31:45 -07:00
hanzo-dev 0964d4f4d8 fix(agents): build session target/host indexes after addColumns
migrateSessions created ix_sessions_org_target and ix_sessions_org_host in
the table DDL, which runs before addColumns adds target/host to a
pre-existing table. On a fresh DB the CREATE TABLE carries the columns so
the indexes build; booting over the prior release's agent_sessions table
the CREATE TABLE IF NOT EXISTS no-ops and the index references a
not-yet-added column ("no such column: target"), failing the release
migration smoke. Build the two indexes after addColumns so the columns
exist first on both the fresh and upgrade paths.

TestMigrateOverLegacySessionsTable locks it over the pre-target schema.
2026-07-15 02:24:57 -07:00
hanzo-dev bb9bcbf307 fix(cloud/code): prefer the live login JWT over the hk- key to unblock 402
hanzo code 402s ('a billable tenant is required') on a deployment without
IAM_MINT_CLIENT_*: codeToken() preferred the hk- API key, but an hk- key only
mints a billing principal when the server can resolve it (iamKeys.resolve is a
no-op without the mint credential) — so the request arrives anonymous and zen's
/v1/messages billing gate refuses it. The /v1/models catalog call is loosely
gated, so the launcher banner still printed, masking the cause.

Reorder codeToken to prefer a FRESH hanzo login JWT, which carries the caller's
owner/project/sub claims verbatim and mints a billing principal on EVERY
deployment, then fall back to the hk- key chain (still works on mint-credentialed
servers). HANZO_API_KEY stays the deliberate operator override at the top.

freshAccessToken() is a new expiry-guarded accessor (decomplected from
accessToken, which whoami keeps expiry-agnostic): an EXPIRED jwt must not win —
it would 401 a session a valid hk- key would serve — so it falls through to the
key. No expiry record (a raw HANZO_TOKEN) is trusted as-is.

Pinned by TestCodeTokenPrecedence (fresh jwt beats hk-, expired jwt falls
through, HANZO_API_KEY overrides all). Structural hanzoai/jwt extraction is a
follow-up PR.
2026-07-15 02:19:47 -07:00
hanzo-dev 9347a5671f git: make the mounted service pointer atomic (fix -race)
The lifecycle reactors (notify / mirror-out / index-on-push) read the package
'mounted' var in DETACHED EmitLifecycle goroutines while Mount/Shutdown write it;
a reactor goroutine outliving a Shutdown (or a test Mount<->Shutdown cycle) tore
against the write. Convert 'mounted' to atomic.Pointer[cloud.Service[state]] —
Store on Mount/Shutdown, Load in every reader (reactors, export CloneURL/VerifyRef,
index-on-push, the GitHub importer) + the tests. Behavior unchanged (production
sets mounted once); the data race the -race detector flagged is gone.
2026-07-15 02:19:15 -07:00
hanzo-dev a4cb8e9305 feat(cloud/connectorruntime): native in-process connector exec (HIP-0126)
Lands clients/connectorruntime — the native replacement for the standalone
ActivePieces Node engine: an ActivePieces JS connector action runs in goja
in-process (no auto pod, no in-cluster HTTP hop, no shared X-Piece-Run-Secret).
Same {action,auth,props} -> {ok,output,error} contract; org-gated via
principal.Org; the caller's credential travels in the request auth.

POST /v1/automations/connectors/:id/run  run one connector action in-process

Wired into the composition root (subsystems.Wire) the one way main does it —
an explicit MountSpec after automations (it pairs with the catalogue) — not the
old self-registering cloud.Register init (removed; main is explicit-Wire).
frozen order sequence updated to 84 specs.

Re-derived from the cloud-cr worktree's uncommitted work against current main:
the package's principal.Tenant -> principal.Org, the cloud.Register init -> the
explicit Wire() entry, and the go.mod esbuild dep flipped to direct. The
kb/sync_piece.go refactor that originally accompanied this is NOT carried —
clients/kb was removed on main since the branch forked, so there is nothing to
refactor; connectorruntime stands on its own (imports only cloud + principal).

Build green; go test ./clients/connectorruntime/... green (registry + runtime);
TestWireOrderMatchesFrozen green at 84 specs.
2026-07-15 02:13:38 -07:00
hanzo-dev c24364985a Merge feat/ai-obs-attribution: o11y trace attribution + annotation queues
Trace attribution, per-project metrics, sessions, and annotation-queue routes
on the o11y plane (clients/o11y annotation store + queues, clients/eval
attribution/telemetry, principal scope). Genuine new feature (not on main),
rebased clean onto current main; builds and race tests green.
2026-07-15 02:07:08 -07:00
hanzo-dev 3f31ac709d Merge feat/github-app-sync: GitHub App bidirectional repo mirror + sync
Install the Hanzo GitHub App -> list org repos -> import into git.hanzo.ai ->
bidirectional sync (outbound mirror already exists; inbound = HMAC-verified
webhook, fast-forward-ONLY, never force-overwrites native). Inert until the App
creds land in KMS.
2026-07-15 02:07:05 -07:00
hanzo-dev 663571f690 Merge fix/affiliates-topup: accrual tops up the open period (month-to-date converges); link clicks off the money-DB write path 2026-07-15 02:05:26 -07:00
hanzo-dev c29d96a70c fix(affiliates): accrual tops up the open period so month-to-date spend converges
The monthly accrual latched once on the FIRST sweep's PARTIAL month-to-date spend
and no-oped every later sweep, so an affiliate whose dashboard swept early in the
month froze its share near zero (underpaid, though platform-safe). Store.Accrue now
inserts the period row on first sweep and, for the still-open period, TOPS IT UP
toward the current (higher) month-to-date reading in one transaction — adding only
the positive delta, so accrued_cents converges to the month-end value, never
decreases, and never overshoots. The per-event money invariant is untouched: each
row keeps margin + share from ONE reading (share <= margin) and the level-schedule
cap keeps sum(share) <= margin at every step.

Public link clicks move off the money-DB write path: clickLink folds pings into an
in-memory coalescing buffer (bounded), flushed batched on the next links read and on
shutdown, so a click flood can never contend with the accrual/payout writes.

Tests: TestAccrualConverges + TestAccrualConvergesAtMaxRate prove the share tracks a
growing month-to-date and sum(share) <= margin at every intermediate sweep; existing
invariant/idempotency/isolation/links tests stay green (26 pass, -race).
2026-07-15 02:05:08 -07:00
hanzo-dev f36c99a109 code: index on push via durable hanzoai/tasks workflow
A push to a repo's default branch enqueues a durable IndexRepoWorkflow on
the embedded tasks engine (workflow id keyed by commit = idempotent per
push); a worker reads the tip tree from the object plane and folds its
text files into the org's code index, retried on failure. Fail-soft:
before the engine is wired the reactor indexes inline on its detached
lifecycle goroutine (the ai-ingest contract), so push-index is always live.

git and code never import each other — the reactor is git's third
lifecycle subscriber, the index reached through the SetIndexer func seam
wired once at the composition root.
2026-07-15 02:04:02 -07:00
hanzo-dev cabe44f5df feat(o11y): trace attribution, per-project metrics, sessions + annotation-queue routes
eval telemetry (Trace): add ProjectID, SessionID, APIKeyHash (SHA-256 ref, never
plaintext), and StartTime/EndTime latency; DDL columns + additive migrations +
write/read paths. A run stamps its project (principal.ProjectScope), groups its
item-traces under the run as one session, times the model call, and records a
non-reversible ref of the caller credential. Trace list narrows by the caller's
project (default == whole org).

evals/metrics: thread the server-minted project scope into MetricsFilter,
usageWhere (AND project = ?) and the latency span filter. The default-project
(whole-org) board queries the ledger today; a named-project board is honest-empty
until cloud_usage carries a project column (ai write path) — activation is one
guard flip, the query plumbing is project-aware and tested.

principal.ProjectScope: the ONE helper for "default project == "" == whole org";
eval + o11y both read it.

o11y: explicit org-gated GET /v1/o11y/sessions pinning the runtime /api/sessions
route; native annotation-queues surface (SQLite metastore, org+project scoped) at
/v1/o11y/annotation-queues* — list/create/detail/update/delete, items add/list/
complete — returning the console {data,meta} envelope.

Tests: trace attribution (latency, session grouping, hashed-not-plaintext key),
per-project + cross-org trace isolation, usageWhere project predicate, annotation
queue lifecycle + org/project isolation + validation + principal gate.
2026-07-15 02:03:55 -07:00
hanzo-dev d5c3688eef GitHub App: bidirectional repo mirror + sync (git.hanzo.ai)
integrations (github.go/github_app.go/github_webhook.go): App install ->
installation-token mint (ghinstallation), list granted repos, background import,
inbound push webhook (HMAC-verified, fast-forward-only). Inert until
GITHUB_APP_{ID,PRIVATE_KEY,WEBHOOK_SECRET,SLUG} land.

git (github_import.go + cloud.GitImporter seam in git_import.go): import =
fast-forward mirror-in per branch; inbound = fast-forward-ONLY advance where
native is canonical, so a divergence is a recorded conflict and never a
force-overwrite; loop-prevention via the Origin stamp; per-repo status. Outbound
mirror uses the org installation token for github.com targets, shared-token
fallback otherwise (no regression).
2026-07-15 02:02:49 -07:00
hanzo-dev 7f2584cd4e code: add tree + file endpoints (zread contract over the index)
GET /v1/code/tree?repo=  → get_repo_structure: the repo's files + per-file
  symbol counts, ordered, per-org isolated.
GET /v1/code/file?repo=&path= → read_file: the INDEXED content (the symbol
  chunks the search tiers hold), for fast context. NOT byte-verbatim — inter-
  symbol lines a parser did not chunk are absent; the S3-backed git object
  plane (clients/git) is the source of record for exact bytes, history, and
  blame. Comments say so; a follow-up routes byte-fidelity read_file/blame at
  the git plane.
Store.tree + Store.fileContent read the existing files/symbols/chunks tiers —
no schema change. Test covers tree structure, indexed-file read, 404 on an
unindexed path, and per-org isolation (org B sees an empty tree).
2026-07-15 02:01:18 -07:00
hanzo-dev 4a3bd68917 Merge feat/hanzo-agent-keystone: @hanzo Slack coding agent (ships INERT)
The coding-agent code lands fail-closed and INERT: no sandbox runs until an
operator provisions docker and sets HANZO_CODING_* env. The coding sandbox
stays DISABLED until the default-deny-egress + container resource-limit
hardening lands and red re-clears. Do NOT provision docker / set HANZO_CODING_*
until then.

Native coding tasks from Slack over the shared object plane: clients/coding
dispatcher, in-process agents session bus, tracker agent PR, bot NDJSON client,
git export seam, slack coding trigger.
2026-07-15 01:57:17 -07:00
hanzo-dev 6ac6ece3bf Merge feat/mission-control-sessions: agent session execution-context + targets
Mission-control backend over /v1/agents/sessions: sessions carry host/cwd/
repo/target and a compact last-event; new /v1/agents/targets registry
(register/list/detail/patch/delete) with live session-load, org fail-closed,
in the same agents.db. Composes with the compute fleet at the view layer.
2026-07-15 01:49:51 -07:00
hanzo-dev b81a0fbdb7 agents: session execution-context + targets (mission-control)
Sessions gain host/cwd/repo/target so mission-control can show where a
session runs and map sessions to a machine; the list projection carries a
compact last-event preview. Add /v1/agents/targets — register/list/detail/
patch/delete a dispatch destination (laptop|cloud|gpu|cluster|machine) with
a live session-load rollup — in the same agents.db, one tenancy column, org
fail-closed. A session's target resolves same-org at register/patch (#48).

Composes with the compute fleet (/v1/fleet/workers, /v1/clusters) at the
view layer rather than duplicating it.
2026-07-15 01:48:51 -07:00
zeekay c94dba9794 release: fix step splice — buildx keeps its with: block 2026-07-14 23:38:51 -07:00
zeekay 14034b7b41 release: dual-host — mirror release tags to registry.hanzo.ai
Server-side copies alongside the ghcr retag; the cluster deploys from OUR
registry, ghcr stays the public identity. Best-effort by contract — a mirror
hiccup never blocks the tag-receipt.
2026-07-14 23:38:27 -07:00
zeekay f269f3156a Merge remote-tracking branch 'origin/main' into unfork-commerce 2026-07-14 23:19:49 -07:00
zeekay c6b31666d1 ci: canonical hanzo.yml test gate + hanzoai/ci caller on the arc pool
release.yml keeps sole ownership of the image + v* tags (tag-is-a-receipt);
this adds the vet/unit gate on every push/PR, on our own runners.
2026-07-14 23:19:38 -07:00
hanzo-dev 986dc9d58e fix(cli/code): give Claude Code its true 1M context on zen models
Claude Code sizes a model's context window only from ids it recognizes.
An unknown gateway id like `zen5-pro` gets a hardcoded 128K budget and is
rejected client-side above it ("maximum context length is 131072") — even
though api.hanzo.ai and the DeepSeek-V4 upstream serve the full 1M window
fine (verified live: 140K-token prompts return 200).

Bridge each CC tier through a recognized carrier id (claude-opus-4-8[1m]
etc.) that unlocks the 1M budget, then rewrite it back to the served zen
alias via settings.json modelOverrides before the request leaves the
client — the carrier never reaches the server, so real claude-* routes are
untouched and responses stay branded/served as zen. One source of truth
(zenTiers) drives the wire env, picker branding, and overrides. The fast
tier stays direct (never needs >128K; SMALL_FAST_MODEL isn't override-
rewritten, so a carrier there would leak raw).

Verified end-to-end with Claude Code v2.1.210: the wire model reaching
api.hanzo.ai is zen5 / zen5-pro carrying context-1m-2025-08-07, with zero
raw claude-* leaks.

Claude-Session: https://claude.ai/code/session_01SpMZ69ur3tjAXCiwaa7Wv2
2026-07-14 23:15:24 -07:00
zeekay 8477d02e37 merge main: /v1/store owner carried onto the NATIVE mount
The store surface registers natively (api/store.Route on a group-scoped chain
mirroring the standalone /v1 bundle) instead of re-adding the gin AdaptNetHTTP
prefix; commercePrefixes keeps /v1/store pinned so store reads can never fall
through to the AI /v1/* balance gate again.
2026-07-14 23:03:43 -07:00
zeekay f601ae8885 commerce v1.48.1 NATIVE co-residence — routes on the shared zip app, AdaptNetHTTP gone from the commerce path
- subsystems/commerce.go: commerce.Embed(App: app) — the SharedApp contract;
  commerce registers /v1/commerce/* + /_/commerce/* directly on cloud's router
  (one specificity space, no second engine, no net/http adaptation)
- live wire paths registered natively with commerce's own gates:
  /v1/billing/webhooks/:provider (HMAC-is-auth) and
  /v1/billing/auto-recharge/run-all (service-token + PlatformOnly) —
  commercePrefixes contract test pinned and passing
- commerceinproc.SetApp: S2S byte-stream enters the shared app's pipeline;
  RoundTrip normalizes client-style RequestURI at the ONE seam;
  entitlements + BalanceCents stay pure direct-Go (commerceclient)
- zip v1.8.2 (union tag: v1.8 features + the v1.7.4 chain-order fix + v1.7.5
  empty-leaf normalization — v1.8.1 was missing both)
- metering dispatch e2e ported to the zip harness and green
2026-07-14 23:01:39 -07:00
hanzo-dev 21bf5c8e43 fix(commerce): own /v1/store/* so store reads reach commerce, not the AI /v1/* balance gate
The bare storefront surface api.Route(Group("/v1")) registers on the commerce
gin engine — GET /v1/store/current (the org-scoped default store the admin
dashboard AND the content storefront edge resolve), the /v1/store/:id/listing
upsert the publish edge writes, and the public /v1/store/:store/listing reads
karma.style serves at runtime — was dropped from commercePrefixes by the unfork.
Unowned, /v1/store/* fell through to the bare /v1/* AI catch-all, whose prepaid
LLM balance gate 402'd every store read for an org funded in commerce but $0 in
the ai ledger (org karma: $999.99 credit, GET /v1/store/current -> 402
insufficient_balance, blocking store provisioning + the storefront image fan-out).

Restore the /v1/store prefix so /v1/store/* routes to the commerce handler, which
resolves the org from the gateway X-Org-Id (TokenRequired -> ensureIAMOrg) and
lazily provisions the org's store — standalone-commerced parity. A store-metadata
read never requires an LLM balance. Per-route permission masks are unchanged
(money paths stay publishedRequired); gin still 404s an unknown /v1/store/* path.

Guarded by TestStoreSurfaceRoutedToCommerceNotAIGate (store read resolves on
commerce, never 402 at the catch-all) + the extended commercePrefixes pin test.
2026-07-14 22:55:03 -07:00
hanzo-dev f9ec50bbc3 feat(social): optional media[] URLs on posts
Add an optional media field (JSON array of URLs) to the social Post store,
additive and idempotent exactly like the marketing scheduled_at fix:

- store: media TEXT NOT NULL DEFAULT '[]' column + addColumn upgrade for
  pre-existing prod DBs (migrate-on-open, the only upgrade path for the
  encrypted single-file store); JSON encode/decode helpers; Post.Media []string
  always serialized as [] never null.
- api: normMedia bounds each URL to maxField and the list to maxMedia (10),
  the one sanitization seam on create + update (mirrors content/channel).
- tests: media round-trip in TestPostCRUD (create sets, update replaces) and
  TestMigrateAddsMediaColumnToOldPosts — old-schema DB gains the column and a
  media write no longer 500s; legacy rows default to [].
2026-07-14 22:51:48 -07:00
hanzo-dev f36732c507 Merge feat/affiliate-profit-share-dashboard: OSS-dev affiliate profit-share + dashboard
Margin-based accrual (share = rate x Hanzo's margin, share <= margin invariant),
derived share ledger that never mutates the cost-of-record, shareable links with
click/signup/conversion, per-period earnings, opt-in privacy leaderboard, and the
SuperAdmin set-rate. Tenant-isolated, fail-closed.
2026-07-14 22:31:52 -07:00
hanzo-dev 6cb081127f affiliates: profit-share (margin-based accrual) + dashboard (links, earnings, leaderboard)
Switch the affiliate accrual from revenue-share (spend x rate) to PROFIT-share
(margin x rate), where margin = a referred org's gross spend x the platform
gross-margin fraction (AFFILIATE_MARGIN_BPS, default 40%). The share is a rate
OF Hanzo's margin, never the customer's bill, so a payout can never exceed the
margin earned. The L1 rate is capped (maxL1RateBps=9300) so the whole L1+L2+L3
schedule stays <= 100% of the margin: total share <= margin, always.

The derived share ledger (affiliate_accruals) now records the margin base
alongside the gross spend and the share; it never mutates the cost-of-record
(commerce/cloud_usage) - it is a pure projection keyed by referrer.

Dashboard surface (all org-scoped, fail-closed):
- GET  /v1/affiliates/me/earnings   per-period + per-direct-referral aggregate
- GET/POST /v1/affiliates/me/links  shareable links + click/signup/conversion
- POST /v1/affiliates/me/handle     opt-in leaderboard display name
- POST /v1/affiliates/click         public click ping (vanity counter)
- GET  /v1/affiliates/leaderboard   opt-in handles + aggregate + your own rank
- POST /v1/admin/affiliates/:id/rate SuperAdmin set L1 rate (capped)

Tests: margin invariant (share <= margin per level + summed; charge unchanged),
set-rate cap, links lifecycle, cross-affiliate isolation (earnings + links),
leaderboard privacy (no org identity leaks, own rank always visible).
2026-07-14 22:31:21 -07:00
hanzo-dev 19371b7a8f Merge fix/prod-headers-followups: brand-only Server fallback (zip v1.8.1) + trailing-dot brand resolution 2026-07-14 21:56:26 -07:00
hanzo-dev 3f8afeb5e9 fix(headers): brand-only Server fallback + trailing-dot brand resolution
Address Red's LOW-1/LOW-3 on the production-header posture:
- serve.go sets zip.Config.ServerHeader=cfg.Brand so the responses the
  ProductionHeaders middleware can't reach — the fasthttp transport's OWN
  pre-routing errors (431/400) — read Server: <brand> instead of the framework
  default. Requires zip>=v1.8.1 (transport now propagates ServerHeader). Repin
  v1.8.0->v1.8.1; go.mod diff is only the zip line.
- BrandForHostOK strips a trailing FQDN dot so api.lux.network. resolves to lux
  (fails safe to neutral before, never a wrong brand — brand-fidelity fix).
2026-07-14 21:56:15 -07:00
hanzo-dev 73ffedd136 deps(commerce): v1.47.2 -> v1.47.3 — tier gate counts granted credits as spendable (fixes 402 for grant-funded orgs)
Claude-Session: https://claude.ai/code/session_01Gq8suw7uuodAMPDRpo6iAB
2026-07-14 21:47:20 -07:00
hanzo-dev 72ffc555b7 Merge feat/prod-response-headers: inherit zip ProductionHeaders posture (brand-by-host Server, X-Api-Version, HSTS/nosniff) 2026-07-14 21:07:29 -07:00
hanzo-dev 16c6d300da feat: inherit zip ProductionHeaders — brand-by-host Server, X-Api-Version, HSTS/nosniff
Wire the shared production response-header posture (zip v1.8.0) into the edge,
right after RequestID so it covers every response — success, error, 404, and
the public-site static bytes:

- Server is the white-label brand of the request Host via BrandForHostOK (cloud's
  own registry), so a lux/zoo caller is never served "hanzo" and no response
  leaks the framework name. An unmatched Host falls back to this deployment's own
  brand (cfg.Brand), never a framework or hardcoded single brand.
- X-Api-Version carries the build version (Config.Version <- CLOUD_VERSION env,
  else the link-time cloud.Version default) under a brand-neutral key.
- HSTS + nosniff are the always-safe security floor; the console SPA keeps its
  own framing rules (no X-Frame-Options/CSP forced here).

Bumps zip v1.6.0 -> v1.8.0 for middleware.ProductionHeaders. X-Request-Id stays
owned by middleware.RequestID.
2026-07-14 21:07:18 -07:00
hanzo-dev 9db9c53d89 cli: auto-wire Hanzo MCP into hanzo code claude (port Rust resolve_mcp)
The Go hanzo code wired zero MCP — subagents got a bare model, no Hanzo tools.
Port the Rust CLI's resolve_mcp: resolve hanzo-mcp (installed → PATH, else uvx
hanzo-mcp), write an --mcp-config stdio document scoped to the cwd into the
isolated config dir, and pass --strict-mcp-config so the Hanzo server is the sole
MCP source (a repo .mcp.json is ignored — it can ship a bearer-exfiltrating stdio
server). A missing hanzo-mcp warns and continues (MCP is an enhancement, never a
blocker). So hanzo code claude now starts with the Hanzo tool lattice — code
search over the cloud index, web search, vision, fs/exec/git. Test covers the
opt-in, the config shape, and the not-found warn path.
2026-07-14 20:12:25 -07:00
hanzo-dev 2fa922250b code+knowledge: default embed model to zen-embedding SKU (fix semantic tier)
Both indexers defaulted CLOUD_EMBED_MODEL to bge-m3 (the raw upstream), which
the gateway rejects (400) — only the zen-embedding SKU is served. Result:
index-time embeds failed silently, semantic code + KB search returned nothing
(vectors:0, degraded:true). Default to the served SKU. Pairs with the zen
bge-m3->zen-embedding alias so both the name and the SKU resolve.
2026-07-14 20:04:19 -07:00
hanzo-dev 64b233dfe1 integrations: GitLab OAuth provider (login + repo sync, KMS-env creds)
Adds the gitlab provider on the same OAuth registry as slack/google/github.
Reads GITLAB_CLIENT_ID/GITLAB_CLIENT_SECRET from ENV (KMS-synced, never in code);
Configured() is false until both are present so it ships INERT and fails closed
(honest 503 / failure redirect, never a fake OK). Callback = the app's
/v1/integrations/gitlab/callback; the generic dispatcher seals the access+refresh
tokens into the org KMS namespace.

Least-privilege by construction: requests only openid/profile/email/read_api/
read_repository/write_repository — the token receives the intersection of
requested + app-allowed, so we never request api/sudo/admin_mode/k8s_proxy/
*_runner/*_registry even if the app was provisioned with them (tested).
GITLAB_URL supports self-hosted GitLab. 5 tests: registration, least-privilege
authorize URL, exchange seals both tokens + resolves account, missing-secret
fails honestly, error body surfaced.
2026-07-14 18:19:52 -07:00
hanzo-dev 3cdcf062c0 deps(commerce): v1.47.1 -> v1.47.2 — org-scoped /v1/store/current + lazy store provisioning
commerce v1.47.2 fixes GET /v1/store/current returning the phantom shared
"default" store: it now resolves the caller org's namespace and lazily,
idempotently provisions the org-scoped store (store.EnsureDefault) on first
authenticated hit — the store id the content storefront edge needs to publish
Listing.headerImage. Round-trip + cross-tenant tests ship in the module.

Claude-Session: https://claude.ai/code/session_01Gq8suw7uuodAMPDRpo6iAB
2026-07-14 17:59:51 -07:00
hanzo-dev 54657f5da1 fix(marketing): additive ALTER so old prod campaigns tables gain scheduled_at
POST/GET /v1/marketing/campaigns 500'd on prod with "table
marketing_campaigns has no column named scheduled_at": migrateCampaigns()
uses CREATE TABLE IF NOT EXISTS, which NEVER alters an existing table, so a
prod DB created before scheduled_at was added to the DDL was frozen at its
original schema and every campaign write (INSERT/UPDATE name it) 500'd. The
store is an encrypted single-file SQLite only the binary can open, so a
hand-patch is impossible — the upgrade MUST happen in migrate-on-open.

- migrateCampaigns: after the CREATE, run an idempotent additive column
  upgrade — ALTER TABLE marketing_campaigns ADD COLUMN scheduled_at
  INTEGER NOT NULL DEFAULT 0 — swallowing SQLite's "duplicate column name"
  (the only error) so it's a no-op on a fresh DB.
- addColumn helper mirrors clients/social/store.go exactly (the ONE way we
  do additive migrations), keyed by an extensible {table,col,def} list.

Tests (store_migrate_test.go, CGO_ENABLED=0 pure-Go cek): a from-OLD-schema DB
(marketing_campaigns without scheduled_at + a legacy row) opens, migrate ADDs
the column, a scheduled_at write succeeds, and the legacy row survives with
scheduled_at defaulted to 0; plus a fresh-DB idempotency re-open. Without the
ALTER the old-schema test reproduces the exact prod 500.

Claude-Session: https://claude.ai/code/session_01Gq8suw7uuodAMPDRpo6iAB
2026-07-14 17:56:36 -07:00
hanzo-dev ca78743549 fix(commerce): restore /v1/billing/auto-recharge prefix dropped by the unfork — pin test moves beside the canonical list
The unfork (6a071d2) rebuilt commercePrefixes in subsystems/commerce.go from a
pre-fix snapshot, dropping /v1/billing/auto-recharge (landed as #274/6dc3c6b)
and deleting its pin test with the old clients/commerce tree. Without the
prefix the durable cron's quarter-hour billing-autorecharge poke lands on the
account-bridge /v1/billing/* session gate and 403s — verified live before
6dc3c6b shipped in v1.801.1 (poke 200, 311 orgs swept, 23:45:05Z).

Same one-line-family fix, new canonical location; TestCommercePrefixesPinned
now lives beside the list it pins so a future rewrite can't silently regress
the wire path again.

Claude-Session: https://claude.ai/code/session_01XptqW83ZLpqyGBENc1wAQz
2026-07-14 17:51:13 -07:00
hanzo-dev 4e88b76672 fix(zen): resolve upstream provider keys env-first, then KMS
zenKeyResolver read the embedded KMS store ONLY. The operator injects the
provider keys (DO_AI_API_KEY, ANTHROPIC_API_KEY) as env from the KMS-synced
K8s secret cloud-api-llm-keys, but that value is not seeded into the embedded
ZapDB KMS store — so GetSecret missed, the resolver returned an empty key, and
zen's upstream call to DO GenAI answered 401 'Unable to authenticate you'.
Every zen chat failed while ai (which reads the key from env) worked.

Read env first, then KMS — the same order ai uses (object/kms.go). One key
source of truth shared by both zen and ai. Empty on both still returns '' so
the call fails fast, never silent free usage.
2026-07-14 17:24:48 -07:00
zeekay 6a071d2a52 unfork(commerce): import hanzoai/commerce v1.47.1 — delete the 1,397-file inlined fork
One canonical commerce repo, one-way dependency (cloud → commerce), no more
monorepo-split force-pushes to keep two trees in sync.

- clients/commerce/ (fork, no go.mod) DELETED; cloud imports the module
- subsystems/commerce.go: the ONE adapter — narrows cloud.Deps, boots
  commerce.Embed, mounts the gin handler at the commerce prefixes, wires the
  two in-process seams; luxfi/log imported plainly as log
- consumer bridges move cloud-side (they read cloud seams, not commerce):
  clients/metering    ← fork metering (finance-coupled billing-gate client)
  clients/commerceclient ← in-process entitlement client + BalanceCents
  (separate from commerceinproc: the entitlement client imports clients/plan,
  which imports cloud — commerceinproc must stay stdlib-only for build.go)
- commerce API path: api/api flattened to api (module v1.47.1)
- middleware precedence regression tests moved INTO the module beside the
  accesstoken fix they pin; the in-proc dispatch e2e stays in clients/metering
- subsystems/wire_test: freeze gitops (main had 83 specs vs 82 frozen)

Test surface green: subsystems, commerceclient (real embedded-ledger money
tests), commerceinproc, metering, catalogsync, bots, admin/finance, ml; root
package fails ONLY the 11 pre-existing env-gated tests (cek master key),
identical to origin/main.
2026-07-14 17:08:40 -07:00
hanzo-dev 14e9c32c4f cli: map Claude Code Fable tier to zen5-max (top SKU)
Fable is Claude Code's top model tier; it was pinned to zen5-pro, the
same as Opus. Point it at zen5-max (the largest zen5 SKU: Qwen3.5-397B ->
1M overflow) so the CC tier ladder is monotonic: Haiku->zen5-flash,
Sonnet->zen5, Opus->zen5-pro, Fable->zen5-max.
2026-07-14 16:20:45 -07:00
hanzo-dev 12f60dfed3 deps: o11y v1.5.28 + otel-collector v1.2.0 — evict koanf v1 monolith
Bumps the embedded o11y (v1.5.26->v1.5.28) and otel-collector
(v0.144.13->v1.2.0) to their koanf-v2 releases and drops the obsolete
otel-collector v0.144.10=>v0.144.13 replace. Removes the ambiguous
github.com/knadh/koanf/maps import (bundled v1.5.0 monolith vs split
module) that broke 'go build ./cmd/cloud'. Cloud builds green.
2026-07-14 16:20:45 -07:00
hanzo-dev 7e6a580cab P2: /v1/gitops deploy dashboard API (clients/gitops)
The ArgoCD-grade GitOps control plane over the operator App CRs, native to the
cloud binary and parallel to /v1/git. SuperAdmin-only, fail-closed, Secrets never
surfaced. The console dashboard consumes these shapes:

  GET  /v1/gitops/applications        list: name, role, version(declared),
                                      runningVersion, health, sync, phase, endpoints
  GET  /v1/gitops/{name}/tree         flat node list (ArgoCD ApplicationTree) with
                                      ownerRef parentRefs + per-node health
  GET  /v1/gitops/{name}/resource/{ref} live manifest + desired-vs-live diff
                                      (ref = group:kind:namespace:name from a node)
  GET  /v1/gitops/{name}/logs         newest app pod logs (tail/container bounded)
  POST /v1/gitops/{name}/rollback     pin CR image tag to a prior semver — REUSES
                                      the P1 release seam (cloud.OnServiceRelease)
  POST /v1/gitops/{name}/sync         request an operator reconcile now

- health.go: per-resource health in the ArgoCD vocabulary (Healthy/Progressing/
  Degraded/Suspended/Missing), pure — P2b swaps to gitops-engine pkg/health.
- CR kind-collapse compat shim: reads BOTH apps.hanzo.ai (kind App, forward) and
  services.hanzo.ai (kind Service, live) — App wins the dedupe; removable
  post-cutover. spec.role surfaced.
- Wired into subsystems.Wire after paas (so the release seam is registered before a
  rollback delegates to it).

TODO seam (follow-on, noted): true GitOps on git.hanzo.ai — RegisterPushBuilder
commits the CR change to the manifest repo and the engine syncs repo→cluster;
desiredSource flips last-applied → git with no shape change.

Tests: health matrix, sync, ref-parse, membership, diff, observe, App-first/Service
-fallback resolution, list dedupe, tree ownerRef+selector. go build + test green.
2026-07-14 16:20:45 -07:00
hanzo-dev e76f1b3185 ci(release): make the migration-smoke shared volume writable (fix baseline INFRA fail)
The two-boot migration smoke shares a docker named volume across boots, but a fresh
named volume is root:root 0755 while the cloud image runs non-root — so the baseline
(v1.799.19) could not create cek's <db>.cek.lock under /data and aborted before
"listening" ("cek: open lock ... permission denied"), failing the gate on infra, not a
regression. The single-boot smoke only passed because --tmpfs is world-writable.

chmod the shared volume 0777 via a root helper before the baseline boot, and again
between boots so the candidate can read the baseline's files even if runtime UIDs differ.
2026-07-14 16:20:09 -07:00
hanzo-dev 6dc3c6bb1e fix(commerce): mount /v1/billing/auto-recharge as a commerce prefix — unbreak the durable-cron sweep poke
The durable platform cron (clients/cron) fires cron-billing-autorecharge every
15m as a poke: POST cloud.hanzo.svc:8000/v1/billing/auto-recharge/run-all with
the COMMERCE_SERVICE_TOKEN bearer. That path was not a commerce prefix, so it
fell through to the account-bridge /v1/billing/* catch-all, whose session gate
403s a service token ("sign in to view billing"). Live fires have been failing
on exactly that — verified in-pod: the poke returns 403 on v1.799.13.

Add /v1/billing/auto-recharge to commercePrefixes alongside /v1/billing/webhooks
— same class of route (token/signature IS the auth, no session possible).
commerce mounts at Wire order 100, ahead of the bridge, so the poke reaches gin
where commerce's own TokenRequired service-token branch + PlatformOnly gate
authenticate it. No other /v1/billing/* route changes owner.

TestAutoRechargePrefixMounted pins both prefixes so a future edit can't silently
re-break the sweep. Landed directly on main: the identical change merged four
times (#274/#275/#277/#280) and was each time force-pushed off main or closed +
branch-deleted; a PR is not a durable landing surface here.

Claude-Session: https://claude.ai/code/session_01XptqW83ZLpqyGBENc1wAQz
2026-07-14 16:17:24 -07:00
hanzo-dev ab58eb4de2 Merge fix/release-migration-smoke: index-after-ADD-COLUMN store migrations + regression harness 2026-07-14 16:04:56 -07:00
hanzo-dev cef39aacfe fix(stores): create indexes over ALTER-added columns after the ADD COLUMN pass
tracker.migrate() indexed issues(org, repo) and issues(org, kind) in the base
DDL, but repo/kind are ALTER-added. On a legacy tracker.db (CREATE TABLE IF NOT
EXISTS no-ops) those indexes fail "no such column", migrate() fails, mount
fails, and the pod crashloops on deploy — the same class already fixed in
wallets and affiliates. Move both indexes after the ALTER pass.

Prevent recurrence with a shared regression harness (internal/migratetest):
each store contributes a legacy-DDL case that seeds its pre-migration schema and
asserts migrate() succeeds and is idempotent, proving migration-correctness as a
pure test over schema epochs instead of at prod boot. Cases added for tracker
(with a scoped-insert probe) plus the other ALTER+index stores — agents, social,
platform, provisioning, projects — which audit clean and are now locked.
2026-07-14 16:04:49 -07:00
hanzo-dev 5fe4b68a33 ci(release): migration smoke — boot candidate over the prior release's on-disk schema
The plain smoke boots on a fresh /data, so every migrate() takes its CREATE-TABLE
path and no forward-migration runs — an index over a not-yet-ADDed column is valid
on a fresh store yet crashes on a pre-existing one (affiliates referrer_org in
v1.800.1, wallets project/agent before it), which is how a boot-crash reached prod
and took api.hanzo.ai down while every smoke stayed green.

Reproduce the real upgrade path: boot the prior released image (default
ghcr.io/hanzoai/cloud:v1.799.19, override via SMOKE_MIGRATION_BASELINE) to lay its
cek-encrypted on-disk schema into a persistent volume under one shared throwaway
master key, then boot the candidate over the same volume and require "listening". A
migrate() that assumes a fresh store fails the gate before any image is pushed.
2026-07-14 15:46:42 -07:00
hanzo-dev 3f349107e4 P1: native release seam — RegisterServiceReleaser patches services.hanzo.ai CR
Close push→build→image→CR: a proven, clean-semver image rolls live by patching
the matching operator hanzo.ai/v1 Service CR's spec.image directly, so the
operator reconciles the Deployment. This is the in-cluster, direct-CR replacement
for universe's image-update.yml GitOps hop (repository_dispatch → PR → ArgoCD),
with the same determinism (clean-semver only; resolve CR by metadata.name) and no
git round-trip.

- build.go: RegisterServiceReleaser / OnServiceRelease / ServiceReleaserRegistered
  inversion seam (mirrors RegisterPushBuilder), so a build-completion path rolls a
  proven image with no cloud⇄paas import cycle.
- clients/paas/release.go: releaseService — resolve CR by name (main-first),
  clean-semver gate (IsSemverTag), idempotent merge-patch of spec.image; registered
  at Mount as the releaser impl (paas owns the first-party Service CR plane).
- clients/platform/release.go: rolloutRelease — native CR patch primary, universe
  image-update dispatch kept as an additive GitOps mirror during cutover.

Tests: split/gate, patch, idempotent, reject-floating, unknown-service, main-first,
fail-closed, seam dispatch/no-op. go build + go test green (paas, platform, root).
2026-07-14 15:45:02 -07:00
hanzo-dev e49eada0f2 Merge: fix affiliates migrate index order (cloud boot crash) 2026-07-14 15:22:16 -07:00
zeekay 874a6f63b6 fix(affiliates): create referrer_org index AFTER ADD COLUMN (boot crash)
On a store whose affiliate_referrals table predates referrer_org, CREATE TABLE
IF NOT EXISTS is a no-op, so 'CREATE INDEX ... ON affiliate_referrals(referrer_org)'
in the same DDL batch failed with 'no such column: referrer_org' BEFORE the
ALTER ... ADD COLUMN pass ran — crashing cloud on boot (v1.800.1 CrashLoopBackOff,
api.hanzo.ai down). Move the index creation after ADD COLUMN so it is valid on
both a fresh store and a migrated one. Regression test seeds the old schema and
asserts migrate succeeds + backfills (it fails with the exact prod error when the
index is moved back into the DDL batch).
2026-07-14 15:22:16 -07:00
hanzo-dev 81b6fc8df8 Merge: hanzo code claude self-identifies as a Hanzo Zen model (--append-system-prompt) 2026-07-14 15:21:18 -07:00
hanzo-dev 9fb946ff96 feat(code): claude agent appends the Hanzo Zen identity to its system prompt
`hanzo code claude` already pins the model to a zen5 alias (default zen5, the
GLM-5.2-class tier) and forces it on argv so a persisted /model selection
("best") cannot override it — but Claude Code's base system prompt still tells
the model it is Claude, so a Hanzo-served model self-identifies as Claude when
asked. Append the Hanzo Zen identity via --append-system-prompt (an APPEND, not
--system-prompt: CC keeps its harness prompt for tool-use/safety/coding) so the
served model says it is a Hanzo Zen model. The identity is not a permission
bypass, so it is applied in --safe too (unlike --dangerously-skip-permissions).

codex/dev (OpenAI wire) are unchanged — the append is Anthropic-only.
2026-07-14 15:19:53 -07:00
hanzo-dev efd9f71cf6 Merge: bare hanzo + configurable default coding tool 2026-07-14 15:04:48 -07:00
zeekay 5b2d742a84 feat(cli): bare hanzo + configurable default coding tool
- `hanzo` (no args): log in if needed, then drop into the configured agent on
  a Hanzo cloud model — one word, billed to your account, all zen-native.
- `hanzo code` (no agent): runs the default agent instead of showing help.
- Default agent resolves HANZO_CODE_TOOL, then config `code_tool`, else dev.
- `hanzo config set code_tool claude|codex|dev` + `code_model` — git-style k/v,
  persisted to ~/.hanzo/config.
A named agent (`hanzo code claude`) still dispatches to its subcommand.
2026-07-14 15:04:48 -07:00
hanzo-dev 6a017c1f37 wallets: migrate columns before indexing them (fix deploy crashloop)
migrate() created ix_wallets_scope/ix_wallets_finance over project/agent/
finance_account inside the base DDL, before the idempotent ALTER TABLE that
forward-adds those columns. On a wallets table created before scoping (the prod
shape), CREATE TABLE IF NOT EXISTS no-ops, so the index build hit 'no such
column: project' -> migrate fails -> mount fails -> pod crashloop on any newer
image. Order by dependency: base tables, then ALTER-add every post-original
column (project/agent/chain/finance_account), then the indexes over them.

Regression test opens a legacy-schema wallets.db and asserts clean, idempotent
migrate + a fully-scoped insert.
2026-07-14 14:54:01 -07:00
hanzo-dev 3f24e1a81b Merge: resolve API keys to a principal at the identity edge (fixes zen 402) 2026-07-14 14:25:50 -07:00
zeekay 96b9915b07 feat(auth): resolve API keys to a principal at the identity edge
The identity boundary validated JWTs only; an opaque API key (hk-/sk-/pk-)
yielded no principal, so a subsystem that gates on the minted identity (zen's
billing gate) refused a key request as anonymous — the zen 402 'a billable
tenant is required' for a funded hk- key.

keyResolver turns a key into the SAME idClaims a JWT yields (via IAM's
authenticated get-user?accessKey, the confidential hanzo-console client), so the
ONE minting path serves both credentials and key auth and session auth can never
disagree on who a request is. An unresolved key stays anonymous — a bad key
never grants trust; an unconfigured resolver keeps keys anonymous rather than
mis-resolved. Brief generic TTL cache keeps the hot path off the network.
2026-07-14 14:25:50 -07:00
hanzo-dev 2fb181206a fix(coding): terminal ops outlive run ctx; cloud→bot POST refuses cleartext
Red LOW-6: a timed-out coding run must still close the session and mirror
its terminal result. Run terminal-side ops (fail/CloseSession/mirror/CreatePR)
under context.WithoutCancel so an expired run ctx cannot strand a session in
'running'.

Red MEDIUM-3: the cloud→bot coding POST carries the org hk- git credential and
the shared gateway bearer. Fail closed on a cleartext http:// target; a plaintext
in-cluster hop is allowed ONLY when the operator asserts mesh mTLS via
BOT_GATEWAY_ALLOW_PLAINTEXT=1. Error never echoes the credential.
2026-07-14 13:59:57 -07:00
zeekay 3c476cbd5d deps: bump hanzoai/zen v1.2.0→v1.3.0 (cost-basis + margin pricing) 2026-07-14 13:32:08 -07:00
blue 9bed31d068 style: gofmt coding orchestrator + tracker agentpr + slack_coding test 2026-07-14 13:22:13 -07:00
blue ce416c4798 feat(coding): @hanzo agent keystone — native coding tasks from Slack
Turn @hanzo from a chatbot into an engineer. A Slack message
`@hanzo code: <repo> <task>` branches off the chat-only reply into a
durable coding run: register a live agent session, dispatch to the
bot-gateway sandbox, mirror progress into the session live, verify the
pushed branch landed in native /v1/git, open a native PR work item, and
report the branch + PR back in-thread. Non-code mentions keep the
existing chat path unchanged.

- clients/coding: transport-agnostic orchestrator (Dispatcher over
  interface seams; unit-tested with fakes, org-isolated, no credential
  leak into session events/PR body). Cannot import git (cycle via
  integrations) so CloneURL/VerifyRef are injected at the composition root.
- clients/agents/inproc: in-process session API (Open/Log/Close) — the
  twin of the /v1/agents/sessions control plane, same store + live bus.
- clients/tracker/agentpr: in-process Kind:pr Source:agent work item,
  org-scoped, get-or-create repo board (KEY-N).
- clients/bot/coding: in-process NDJSON client for POST /v1/coding-tasks;
  credential travels in the body only, never argv/URL/logs.
- clients/git/export: CloneURL + VerifyRef seams (org-scoped ref check).
- clients/integrations/slack_coding: the code: trigger, credential fetch
  from KMS (fail-closed), ack, detached bounded run, result Block Kit card.
- subsystems/wire_seams: compose the Dispatcher (git seams + adapters)
  and inject into the Slack surface.

Tenant isolation fail-closed: org is the only tenant key on every seam;
sandbox pointed only at the caller org's clone URL with an IAM-scoped
credential; cross-org repo targeting is refused by git's path-vs-identity
guard. Tests: CGO_ENABLED=0 go test green across all touched packages.
2026-07-14 12:45:37 -07:00
zeekay 67b7cfcfdc deps: bump hanzoai/zen v1.1.0→v1.2.0 (coherent lineup + thinking effort)
Pulls in the reworked zen family (one SKU per capability, every upstream
verified on DO) and the hanzoai/thinking depth fold (effort → each upstream's
native reasoning shape). Adds hanzoai/thinking v0.1.0 as a direct require.
2026-07-14 12:40:54 -07:00
hanzo-dev 71c9611461 Merge: hanzo code claude defaults to zen5 (GLM-5.2) 2026-07-14 12:39:26 -07:00
zeekay dac8f15f6b feat(cli): hanzo code claude defaults to zen5 (GLM-5.2)
zen5 is the flagship GLM-5.2-class alias (1M ctx, tool-capable — the glm-5.2
upstream returns tool_use/stop_reason:tool_use, verified live). Matches the
intent to launch Claude Code on GLM-5.2 through api.hanzo.ai. Was zen5-pro
(DeepSeek). The four CC tier slots stay pinned to served zen5 aliases so the
classifier, subagents, and /compact never hit an unserved claude-* id.
2026-07-14 12:38:19 -07:00
hanzo-dev 4c0972a965 git lifecycle: escape branch name in Slack blocks (Red residual LOW)
ev.Branch was an un-escaped mrkdwn sink: git refnames allow < > & !, and the
receive-pack fire path (branchTips → for-each-ref) applies no branchRE, so a
hostile branch (e.g. x<!channel>y) flowed verbatim into the summary and the
*Branch* field of every subscribed channel. slackEscape it in both places, and
defensively escape the org/repo display text too (a deploy event's repo derives
from an unconstrained RepoURL, though it is subscription-gated to a valid name).

TestNotifyEscapesMrkdwn now also pushes a hostile branch through smart-HTTP with
the real git CLI (go-git rejects such a refspec) and asserts it is neutralized in
both the summary and the Branch field.
2026-07-14 12:06:41 -07:00
hanzo-dev 3fc3446bce git lifecycle: address Red review (fix-then-ship)
HIGH-1 mirror-out no longer starves the shared pack plane: dedicated mirrorSem
(separate from packSem), per-push context.WithTimeout, git http.lowSpeed abort,
and cmd.WaitDelay so a stalled downstream's network-helper child can't wedge the
slot past the deadline.

MED-2/MED-3 full (org,project,repo) identity: subscriptions + mirror targets key
on project too (DDL + every list/delete + the notify + mirror fire paths); deploy
emitters thread project (platform a.ProjectID normalized, projects org-level);
repo delete cascade-deletes its subscriptions + mirrors in one tx (no
exfil-on-recreate via an orphaned target).

MED-1 decouple allowlists: outbound mirror TARGET set = {github.com, gitlab.com}
only; the local git host is rejected as a target (no internal SSRF /
privileged-cred presentation). Inbound-fetch credential gate unchanged.

MED-4 Slack mrkdwn escaping of user-derived text (commit subject, pusher, deploy
detail) so a crafted commit subject can't inject <!channel>/disguised links.

LOW-1 keep the shared bot token least-privilege (no chat:write.public — it would
also arm the @hanzo assistant to post uninvited); notifications require the bot
be invited. INFO: reject non-deliverable build.started at subscribe time; DRY
repoFromURL into cloud.RepoFromCloneURL.

Re-verified: new tests for project-scoped routing, delete-cascade, mrkdwn escape,
and stalled-downstream isolation; suites green under -race; gofmt+vet clean;
go.mod untouched.
2026-07-14 11:49:03 -07:00
683e0e0045 test(subsystems): base gained Shutdown via per-org embed (#298) — sync frozen wire order (#300)
Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 11:23:45 -07:00
863f61e9a2 analytics: capture (write) plane — POST /v1/analytics + /v1/tracker → hanzo.events (#296)
* analytics: add capture (write) plane — POST /v1/analytics + /v1/tracker → hanzo.events

The analytics subsystem served only read lenses over hanzo.events; nothing
wrote the table, so the web/commerce lenses were permanently honest-empty. This
adds the symmetric ingest: products POST batches to cloud (the ONE native front
door) and cloud writes org-scoped rows into the datastore warehouse the read
side already queries.

- POST /v1/analytics, /v1/analytics/batch, /v1/tracker (beacon alias) — all
  tenant-gated in-handler; tenant_id is always principal.Org, never client input.
- Writes ride ai/object.DatastoreExec (the SAME pooled client the reads use).
- The writer owns the hanzo.events DDL (EnsureEventsTable, idempotent/latched).
- Privacy scrub: credential/PII-shaped property keys dropped, email values
  redacted, before any row is built.
- Pure core (normalizeEvent/scrubProps/buildEventsInsert) unit-tested; HTTP
  contract tests cover no-principal 403, forged-org 403, oversized 400,
  datastore-down 503; a build-tagged live test proves the full round trip
  against a real datastore.

* analytics: accept anonymous capture, attributed to the brand-public org

Marketing sites emit anonymous pageviews (no session). captureTenant now falls
back — when there is no validated principal — to the PUBLIC brand org derived
SERVER-SIDE from the request Host via the white-label registry (BrandForHostOK),
never a client-claimed org. A forged X-Org-Id is still ignored, and an
unrecognized Host is refused (anonymous events are never dumped into a default
org). Gated by CLOUD_ANALYTICS_PUBLIC_CAPTURE (default on, matching the existing
public insights-capture posture). Verified live: an anonymous pageview to
Host hanzo.ai lands under tenant_id=hanzo.

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 11:21:54 -07:00
478f784b34 marketing: grow /v1/marketing into the full GTM engine (#299)
Fold the remaining GTM subsystems into clients/marketing (native Go, per-org
SQLite, twin of clients/crm), so nothing Python is load-bearing in the mount
path:

- Email drip sequences on the embedded hanzoai/tasks engine (drip.go): a
  per-minute durable schedule sweeps due enrollments; each (enrollment, step)
  is claimed once so a step delivers at most once across restarts/redelivery,
  then the walk advances or completes. Mirrors clients/cron (engine owns time,
  SQLite owns the schedule) — no Redis, no bespoke ticker.
- The ONE send seam (suppress.go): every marketing delivery funnels through
  state.deliver, which enforces the per-org suppression/opt-out list and then
  hands off to the platform notify rail. Expose notify.Send so the existing
  sender is reachable in-process — one sender, not a second. Plus a signed
  public one-click unsubscribe.
- Audiences (audiences.go): cohort filters evaluated live against the org's
  hanzo.events analytics via the ai/object datastore, tenant_id-scoped and
  honest-empty when the warehouse is not wired.
- Promo codes (promos.go): the First-1,000 90%-off launch promo (discounts.md)
  realized as a non-cash wallet credit through the finance ledger, with the
  hard 1,000 cap, one-per-org, one-per-instrument and team-seat-cap guards.
- Content calendar (calendar.go): scheduled posts as documents published by a
  task-executed hook; social publish returns an honest 501 until a connector
  is wired (clients/social's push is fail-closed, the automations connector
  registry is package-private).
- Campaign scheduling (scheduled_at + the scheduled state).

Real tests: drip scheduling + per-step idempotence + tenant isolation,
suppression enforcement at the gate, promo eligibility math + abuse guards.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 11:21:24 -07:00
hanzo-dev ae4a9369a2 git lifecycle event stream + Slack-notify and outbound-mirror subscribers
Generalize the single-registrant git push→deploy hook into a many-subscriber
lifecycle stream without regressing push→deploy. RegisterPushBuilder/OnGitPush
stay exactly as-is (deploy is the subscriber-of-record); alongside them a new
RegisterLifecycleSubscriber/EmitLifecycle fans ONE LifecycleEvent out to N
reactors, best-effort, detached, on a cancel-immune context, panic-contained.

Emit points: PushLanded at the one branch-build funnel (covers HTTP/SSH/push,
now carrying before/after tips + pusher); BuildStarted/DeployLive/DeployFailed
at the platform (startGitBuild / applyLive / failDeploymentCtx) and projects
(deployGit / deployArtifact / completeDeployment) transitions.

Subscriber 1 — Slack notify: per-org repo→channel subscriptions
(/v1/git/repos/:name/subscriptions) stored in the existing per-org git.db,
delivered as Block Kit via the ONE integrations chat.postMessage path
(integrations.NotifySlack/PostSlackBlocks; the automations connector now shares
it). Adds chat:write.public so a freshly-subscribed public channel works
without a manual invite.

Subscriber 2 — outbound mirror: per-repo downstream targets
(/v1/git/repos/:name/mirrors) force-push ONLY the advanced branch to
allowlisted hosts (github.com/gitlab.com/git.hanzo.ai), token via env-only
http.extraHeader under the pack-slot semaphore. LifecycleEvent.Origin is the
loop-prevention seam for a future inbound sync.

All routes org-scoped + fail-closed; tenant isolation, injection, allowlist,
and loop-prevention covered by tests.
2026-07-14 11:17:52 -07:00
zandGitHub e622032d79 Merge pull request #297 from hanzoai/feat/company-formation
Hanzo Company — incorporation + fundraising state machine (/v1/company)
2026-07-14 11:17:14 -07:00
b6274fbef7 feat(base): per-org multi-tenant Base hosting at /v1/base/* (kill superbase wrapper) (#298)
Upgrade the in-process Base embed from the single-instance waitlist-only fold
(#193/#211/#248) into two orthogonal lanes on the ONE engine:

  - LANE 1 (unchanged surface): the platform waitlist app → public /v1/waitlist/*.
  - LANE 2 (new): managed Base hosting → ONE Base app PER ORG, opened lazily and
    LRU-pooled, each on its own SQLite under {DataDir}/base/{TenantSegment}/ (the
    HIP-0302 'SQLite per tenant' model the gojabase leaves use). Served
    authenticated under /v1/base/*, the org resolved from the VALIDATED cloud
    principal (principal.Org) — physical per-org isolation, the console Bases
    manager's backend and the in-binary replacement for the superbase pod.

Base serves under BASE_API_PREFIX=/v1/base so its collections API mounts natively
(self-URLs included) without colliding with cloud's other /v1 routes; the waitlist
plugin binds a FIXED /v1/waitlist regardless. Per-org apps validate bearers against
Hanzo IAM's JWKS as their exclusive auth source (apis.StoreKey{JWKSURL,
ExternalAuthOnly}) — ONE IAM, no second auth path. The cloud binary owns the ZAP
transport, so embedded apps set ZAP_DISABLED. Shutdown releases the platform app +
every pooled per-org app.

Reuses gojabase.TenantSegment (the ONE injective, traversal-safe org->path encoder).
Test: subsystem boots in the harness, a collection record round-trips per-org
isolated over the real HTTP path (acme's record invisible to globex; distinct
on-disk dirs).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 11:16:33 -07:00
hanzo-dev 57443cecee captable: harden the http_test fiber timeout (pre-existing flake); wire company after guide/x402 in the frozen order 2026-07-14 11:12:53 -07:00
hanzo-dev f10800c332 company: make genesis idempotent (no double share issuance) + propagate save error 2026-07-14 11:10:51 -07:00
hanzo-dev ae3edfbf2a feat(company): Hanzo Company — incorporation + fundraising state machine
Adds clients/company (/v1/company): one formation state machine per org
(structure → founders+KYC → $999 → documents → esign → on-chain equity
genesis → company), with a SKIP path for already-incorporated orgs that
imports corporate docs → data room and a cap-table sheet → captable.

- machine.go: pure transition table + per-edge guards; the payment gate,
  KYC gate, and skip path are unit-tested with no I/O.
- providers.go: narrow seams for billing/kyc/docs/esign/captable/anchor/
  filing/upgrade. Billing wires the shared ResourceMeter ($999). KYC and
  state filing are honest stubs (no fabricated verification/filing).
- genesis.go: KMS-signed Hanzo-L1 equity-genesis anchor mirroring
  clients/treasury; computes the root always, commits on-chain when wired,
  honest pending otherwise.
- adapters.go + captable.facade + dataroom.Ingest: new in-proc facades so
  company writes the cap table and data room without an HTTP hop.
- google provider completed in clients/integrations (OAuth + KMS token
  custody); the automations google_sheets/google_drive connectors are
  consolidated to one `google` connector sharing that token; company import
  reads Drive/Sheets through it.
- wired into subsystems.Wire() after referrals; docs/company-dogfood.md
  walks Hanzo/Lux/Zoo through the import path.
2026-07-14 11:10:51 -07:00
3f62dbfeb9 feat(guide): Business AI Guide — /v1/guide launch checklist + agent (#282)
clients/guide + /v1/guide/*: a per-org checklist engine over a
machine-readable curriculum (Step: id/title/why/how/done/dependencies/
signal/tool). Per-org progress on cloud.OrgStore; next-step + dependency
gating are pure functions; auto-detect reconciles a step to done when its
signal maps to real org state (acted = agent action ledger; analytics =
shared warehouse events). Business AI 'do it for me' drafts with deps.AI
then executes the step's bound MCP tool via automations.InvokeTool AS THE
CALLER — attributable, metered, audited, never exceeding the caller's
authorization. Built-in default.yaml (7 steps: positioning→landing→
analytics→waitlist→email→referral→launch) seeds it before marketing's
checklist.yaml; an org-custom PUT replaces it cleanly.

clients/automations: decomplect tool dispatch (dispatchTool) from its two
doors — the HTTP MCP handler and the new in-process InvokeTool/ToolExists
seam — so both share one dispatch, org-scoped credential, concurrency
bound, meter and audit.

Tests (pure-Go, CGO_ENABLED=0): validation/cycle-detection, next-step +
dependency gating, auto-detect reconcile (present/absent/error/terminal),
the acted detector end-to-end, the agent (tool success/failure/assisted/
unknown-tool), and the HTTP surface (403 gate, transitions, 409 gating,
curriculum replace/revert, per-org isolation, do-delegation).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 11:05:32 -07:00
36c56e7e51 feat(growth): multi-level referral upline + OSS-author royalties in one accrual walk (#295)
Extend the existing affiliate accrual into a depth-capped multi-level upline and
fold OSS-author royalties into the SAME per-org spend walk, over one attribution
spine.

Affiliates — multi-level upline (clients/affiliates):
- The referredBy graph is the existing affiliate_referrals edge made walkable
  (referred_org -> referrer_org, denormalized). referredBy is set-once/immutable
  (UNIQUE referred_org) with cycle detection at set time (wouldCycleOrg climbs the
  proposed referrer's upline and refuses a loop).
- Per-level schedule L1 20% / L2 5% / L3 2%, depth cap 3. L1 uses the affiliate's
  own negotiable rate (default 20%, preserving prior single-level behavior); L2/L3
  are platform constants. accrual rows carry the level for analytics.
- The admin sweep is source-centric: fold over every referred org, read spend ONCE,
  walk the upline and accrue to each ancestor's approved affiliate, latched
  at-most-once per (affiliate, source, period). The per-affiliate dashboard read
  walks the downline (same latch key, never double-accrues).
- User-level referredBy graph (user_referrals): set-once + cycle-checked, mirroring
  the org edge; recorded from the referee's user to the affiliate's owner user.
- Payout no-overdraw guarantee unchanged (pending-guard + treasury reserve backing).

Authors — OSS royalties (clients/authors):
- Default author share 25% (was 5%).
- GitLab provider alongside GitHub: host-aware repo canonicalization (github.com +
  gitlab.com), provider-dispatched forge seam (linkedAccount/repoAdmin/fetchFile).
- Append-only, on-chain-ready royalty ledger (author_ledger) with a nullable
  compute_proof column, written per accrual in the same transaction as the balance
  move. compute_proof stays NULL — the hanzod attestation is a follow-up, not faked.
- AccrueForOrg seam: the affiliate sweep drives author royalty for each source org
  with the spend it already read — one accrual walk. Nil-safe when authors is
  unmounted (mirrors treasury.Reserve).

Surfaces:
- GET /v1/affiliates/me — my code, link, downline by level (L1/L2/L3 with rates +
  counts), accrued/pending/paid, payouts.
- GET /v1/admin/referrals — unified SuperAdmin cross-tenant analytics (top referrers,
  conversion, accrual liability by level). The one-time-bonus board moves to
  GET /v1/admin/referrals/bonuses (referrals) so the two compose without colliding.

Tests: 3-level walk math + depth cap, cycle rejection (org + user), set-once
immutability (org + user), no-overdraw payout, GitLab verify + ledger row with NULL
compute-proof, both surfaces. Deterministic fiber test timeout (30s ceiling; the 1s
default flaked under machine load).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 10:53:48 -07:00
5aa185f4bb kb: wikilink graph — extraction, /v1/kb/graph, and vault import (#294)
Complete the native knowledge graph on the kb subsystem.

Wikilink edges: the kb-page after_save hook now extracts [[Page Title]]
references from the page body (the same flattened Lexical text the vector
indexer embeds) and reconciles them into kb-link edge documents — a Link
(source) + Data (target_title) reference, no parallel store. Index and link
maintenance run as one combined page hook so a vector outage never skips link
extraction. Targets resolve to a page by value at read time, so a rename or
trash of a target needs no edge rewrite; a page's own trash removes its
outgoing edges.

GET /v1/kb/graph: the org's knowledge as nodes (kb-page/kb-memory/kb-source,
plus connector and dangling-link endpoints) and edges (parent tree, wikilinks,
connector provenance), org/project scoped, shaped for a force-directed
renderer.

POST /v1/kb/import: an Obsidian-importer-equivalent that ingests an Obsidian
vault zip, Notion export zip (markdown/HTML), Evernote .enex, or Roam JSON as
a kb-page tree with links preserved. Each format is a pure normalizer package
(obsidian/notion/roam/evernote over vault + lexical), mapping to pages filed
through the same framework.Ingest path a connector sync uses — the after_save
hook then extracts their wikilinks, one link path for authored and imported
pages alike.

framework: add the in-process Delete (twin of the HTTP delete, runs on_trash)
used by edge reconciliation.

Tests: table-driven wikilink extraction; per-format normalizer tests with real
fixture files; end-to-end graph, import, and full edge lifecycle (extract,
reconcile-on-edit, source-trash cleanup, target-trash dangling) over the real
framework store.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 10:53:02 -07:00
bc3f8d1dc0 feat(wallets,x402): scoped custody {org,project,agent,account} + native x402 pay-per-use (#293)
Wallets custody scoping (clients/wallets)
- One Scope type {org, project, agent, account} is the ONE key both the KMS
  secret ref (keyRef) and the store lookup derive from. Org stays the hard
  isolation boundary; project/agent/account are optional narrowings within it.
- keyRef derives from the full scope, injection-safe (narrowings validated to a
  slash-free segment). An org-only wallet keeps its exact legacy ref, so scoping
  is additive, not a migration.
- listWalletsByScope is the one scope-filtered read path (org bound, narrowings
  filter within); create + list handlers thread the scope. Store gains project +
  agent columns (forward ALTER, dup-column tolerant).

Native x402 pay-per-use subsystem (clients/x402, /v1/x402)
- challenge (402 + PaymentRequirements) -> client signs ERC-3009 -> proof ->
  Verify (EIP-712 secp256k1 recovery via luxfi/crypto, the same primitive wallets
  signs with) -> settle -> serve. Enforce is a zip middleware a priced route
  group applies.
- Idempotent + replay-safe: settlement id is deterministic in (from, nonce); a
  spent nonce reused for different terms is a replay (402), a re-submitted
  authorization is an idempotent retry (settled + metered once). Two independent
  guards: the PK-atomic store claim and the ledger's own RequestID/Ref idempotency.
- Settlement wires into the metering spine: the payer's org is debited through
  metering so paid usage appears in billing/usage like any metered spend, and the
  recipient wallet's ledger is credited. Ledger settlement is LIVE; on-chain
  broadcast of the authorization is a seam (not wired).
- Marketplace seam: a Registry (Publish) maps resource -> Terms (price + recipient
  wallet ref); x402 resolves the recipient via wallets.ResolvePaymentTarget and
  enforces. The registry itself is another subsystem's work.

Removes the dead, unreferenced clients/commerce/payment/x402 (gin + btcec) so the
binary has exactly one x402.

Tests: scope derivation + injection + scoped seal/sign + scope lookup isolation;
EIP-712 verify round-trip/tamper/term-binding; challenge->verify->serve, nonce
replay rejection, settle-once on retry, free passthrough, payer-required, and
end-to-end ledger settlement (payer debited once, recipient credited once).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 10:51:18 -07:00
5d56acfb88 feat(tools): unified tool plane + marketplace (registry, activation, external-MCP, full-cloud-control, x402 seam) (#292)
* tools: unified tool-plane registry, activation, external-MCP + builtin sources

ONE registry where a tool is {name, source, schema, per-(org,project) activation,
optional price}. Sources register a Provider (List+Dispatch) into it; the registry
enforces the one policy: precedence dedup, activation gate (403), x402 Charger seam
(fail-closed for priced tools), then dispatch. Ships two package-owned sources:
external MCP servers (KMS-sealed auth, SSRF-guarded) and full-cloud-control builtin
(every /v1 route, dispatched in-process replaying the caller credential). Real
tests: precedence, activation 403 + cross-org isolation, priced fail-closed,
external-MCP dispatch, builtin route dispatch, SSRF guard.

* tools+marketplace: register sources, x402 price seam, wire subsystems

Sources register a Provider into the tool plane from their OWN Mount (no source
duplicates its listing logic): connectors (automations), functions, agents, and
skills (discovery-only). Adds the registry Pricer seam + public activation
pass-throughs (Activate/Deactivate/Activated/Exists) so marketplace install IS the
tool activation write and a published listing's price reaches per-call dispatch
enforcement.

clients/marketplace: /v1/marketplace listing/discovery/install over the plane;
monetized listings declare price + recipient wallet and settle through the tools
Charger (x402) seam — proven end-to-end (publish→install→dispatch charges the
seller). Wires tools + marketplace into subsystems.Wire() (frozen-order updated).

Tests: marketplace install==activation + cross-org isolation, phantom 422, publish
validation, monetized dispatch settlement, discovery overlay.

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-14 10:48:38 -07:00
hanzo-dev ef1b674bee feat(git): repo maintenance — bitmap + commit-graph for fast clones
A repo populated by fetch/receive-pack accumulates objects via index-pack,
which writes a pack but no reachability bitmap and no commit-graph — so every
upload-pack walks the whole object graph to build the clone pack (O(objects)
per clone). Add maintenance on the git-exec seam: repack -adb --write-bitmap-index
+ commit-graph write --reachable --changed-paths, under one pack slot with the
same memory bounds as every pack op (a multi-GB gc can't OOM the pod).

- POST /v1/git/repos/:name/gc — on-demand repack, org-scoped, 404 fail-closed.
- Post-push autoMaintain: fire-and-forget git gc --auto after every receive-pack
  (HTTP + SSH), slot-yielding (skips when clones are busy) so repos self-maintain
  as pushes accumulate packs, no scheduler.

Tests: runMaintenance writes bitmap + commit-graph and the repo stays clonable;
the /gc endpoint repacks (200 maintained) + 404s unknown/cross-tenant repos.
2026-07-14 08:50:26 -07:00
antje 728cb0a283 deps: bump ai v1.807.0 -> v1.808.0
Bearer-auth get-cloud-usages + brand-scoped god-view (one UsagePanel across
app/chat/billing). Blue+RED reviewed; build+tests green.
2026-07-14 08:32:16 -07:00
hanzo-dev bc94982a4c fix(git): read the framework-decoded pack request body, don't re-inflate
Fiber's Body() transparently inflates a Content-Encoding: gzip request per
its header (BodyGunzipWithLimit + SetBodyRaw), so c.Body() is already the
decoded pkt-line stream. packRequestBody inflated it a second time and
returned 400 "invalid gzip request body" for every compressed clone/fetch.
git gzips the ref-negotiation once a repo carries enough refs, so this broke
clone for all but trivially small repos — the small-repo round-trip tests
sent the request plain and never exercised the compressed path.

Read c.Body() verbatim (the framework owns Content-Encoding). Add a gzipped
upload-pack regression test through the live Fiber server that fails on the
double-decode and passes on the fix.
2026-07-14 08:16:46 -07:00
hanzo-dev 68a5546f52 deps(ai): bump hanzoai/ai v1.806.15 -> v1.807.0
Ships the zen consolidation: ai discovers the Zen family from the zen service
(GET $ZEN_URL/v1/models) and fronts it, holding no zen routing/pricing/identity
of its own. Pulls the corrected per-upstream reasoning vocabulary and the
money/decimal billing types transitively.
2026-07-14 07:43:32 -07:00
hanzo-dev c9a982a6ca feat(git): streaming git-CLI object plane — bounded memory, protocol v2 (red-reviewed GO) 2026-07-14 07:08:45 -07:00
hanzo-dev db4e6a18a7 chore(deps): fold released hanzoai/ai v1.806.15 (#290,#291) into main 2026-07-14 07:08:45 -07:00
hanzo-dev 60ba58ed55 git: harden the streaming object plane (red review deltas)
Address the red-team findings on feat/git-streaming-object-plane:

HIGH-1 mirror credential exfiltration: only attach GIT_MIRROR_TOKEN to hosts
on an allowlist (GIT_MIRROR_ALLOW_HOSTS, default {github.com, git.hanzo.ai});
any other https source fetches anonymously so a tenant-supplied URL can't
capture the shared token. Set http.followRedirects=false on the mirror fetch
so the token can't ride a cross-host redirect.

MED-2 pack RAM: add -c pack.threads=1 -c pack.windowMemory=64m
-c pack.deltaCacheSize=64m -c core.bigFileThreshold=16m to every pack/fetch
subprocess, and a concurrency semaphore (GIT_PACK_MAX_CONCURRENCY, default 2)
around all pack ops so concurrent large clones/mirrors can't multiply RAM in
the shared cgroup.

MED-3 org traversal: gate the org identifier through orgRE (alnum-led, no
'/'/'\\', no leading '.') in org(), so a SuperAdmin X-Org-Id switch to
"../../etc" is rejected at the git boundary before it reaches absRepoPath.

MED-4 mirror SSRF: resolve the source host and refuse loopback / private /
link-local / metadata (IMDS) / unspecified / multicast targets;
GIT_MIRROR_ALLOW_PRIVATE_HOSTS allowlists internal hosts for tests /
deliberate internal mirrors. Generic rejection message (no probe oracle).

MED-5 pack-to-disk DoS: -c receive.maxInputSize (GIT_RECEIVE_MAX_INPUT_SIZE,
default 2g) on receive-pack so a gzip-amplified or runaway push can't fill
the pod disk.

MED-6 disconnect reaping: gitPackStream.Close now closes the read pipe and
Kills the process before Wait, and runPackSSH Kills on a channel-copy error,
so an abandoned clone can't leave git blocked on a full pipe (leaked
proc/goroutine/FDs).

LOW-7 strip URL userinfo in mirrorSource (credentials via env only, never a
ps-visible argv). LOW-8 close std pipes on cmd.Start failure.

Tests: org-traversal rejection, disconnect-reaping (Close returns promptly +
process reaped + slot released), mirror credential host allowlist, and mirror
SSRF + userinfo strip; existing suites stay green.
2026-07-14 06:54:11 -07:00
hanzo-dev d30112bad7 git: back the object plane with the streaming git CLI for bounded memory
The heavy git paths buffered whole packs in RAM via go-git's pure-Go
server transport and FetchContext: a clone serialized the entire outgoing
packfile into a bytes.Buffer, a mirror indexed the whole incoming pack in
memory, and receive-pack read the full push body. Mirroring a multi-GB
repo OOM-killed the 1 Gi cloud pod.

Route the object plane through the streaming git CLI instead — the way
gitea/GitLab serve smart-HTTP — so packs stream to and from disk with
memory bounded by an OS pipe:

- clone/fetch serve: `git upload-pack --stateless-rpc`, git stdout streamed
  straight to the HTTP response (SendStream); no pack buffer.
- push receive: `git receive-pack --stateless-rpc`, request body -> git
  stdin -> index-pack to disk; only the small report-status is buffered.
- info/refs: `git <svc> --stateless-rpc --advertise-refs` + pkt-line header.
- mirror-in: `git fetch --prune --tags +refs/*:refs/*` against the on-disk
  bare repo; ls-remote --symref resolves the source default branch for HEAD.
- SSH: plain `git upload-pack`/`git receive-pack` over the channel.

One git-exec seam (gitexec.go) builds every subprocess with a hardened,
minimal env (GIT_CONFIG_NOSYSTEM, GIT_CONFIG_GLOBAL=/dev/null, no inherited
secrets, GIT_TERMINAL_PROMPT=0, GIT_NO_REPLACE_OBJECTS) and arg slices only.
Protocol v2 is forwarded from the client Git-Protocol header / SSH env
(validated). Mirror source credentials are injected only via env git-config
http.extraHeader (GIT_MIRROR_TOKEN), never argv or logs, under
GIT_ALLOW_PROTOCOL=http:https. Tenant isolation stays on the validated
absolute bare-repo path (storage.absRepoPath); the handler org/path guards
are unchanged.

Push-to-deploy is preserved via a branch-tip diff (before/after
for-each-ref) that fires cloud.OnGitPush for every advanced branch, and
metering (recordUsage) runs after every push. The go-git server transport
is removed; go-git remains only for bounded init/ref-read/object-building.

Runtime: add git to the alpine stage (upload-pack/receive-pack/http-backend/
git-remote-https).

Tests: real git-CLI clone+push round-trip, a 48 MiB clone proving the pack
streams with ~120 KB server heap growth, mirror from an external
git-http-backend source, and the existing tenant-isolation + push-to-deploy
suites, all green.
2026-07-14 06:12:40 -07:00
5c83e09cc7 fix(deps): correct hanzoai/ai v1.806.15 go.sum hash (#291)
The v1.806.15 tag was re-pointed to the current fix commit; a stale local
module cache wrote the previous tag content's hash into go.sum in #290, so
cloud CI's fresh download failed verification (checksum mismatch / SECURITY
ERROR). Re-fetched the module clean so go.sum records the actual v1.806.15
content hash. No code change; go.mod pin unchanged.

Verified: CGO_ENABLED=1 go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud → 0.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-13 23:37:21 -07:00
dc22bdfa66 fix(deps): bump hanzoai/ai v1.806.13 -> v1.806.15 (#290)
Carries the hanzo-code-claude corrections (ai 68be82cf, first in v1.806.14):
per-upstream reasoning-effort vocabulary (GLM/DeepSeek max|high, not OpenAI
low|medium|high) and round-tripping assistant thinking as reasoning_content
so DeepSeek/Kimi tool-call loops no longer 400/stall. v1.806.15 also carries
ai's luxfi/geth proxy-resolution CI fix and the native Responses work.

Prod (cloud v1.799.16) embedded ai v1.806.13, which predates these fixes.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-13 23:28:17 -07:00
zandGitHub f09ac084d7 Merge pull request #285 from hanzoai/fix/cloud-gomod-cache-v4
fix(ci): retry Zen resolution after publishing tag
2026-07-13 17:07:34 -07:00
hanzo-dev 1b302ebf57 fix(ci): retry Zen resolution after publishing tag 2026-07-13 17:07:28 -07:00
zandGitHub 9b6e53d03b Merge pull request #284 from hanzoai/fix/cloud-gomod-cache-v3
fix(ci): cold-bust poisoned Zen module cache
2026-07-13 17:04:49 -07:00
hanzo-dev 4dc06a9a30 fix(ci): cold-bust poisoned Zen module cache 2026-07-13 17:04:25 -07:00
zandGitHub b003a202b8 Merge pull request #283 from hanzoai/fix/code-full-auto-tool-default
fix(code): full-auto defaults on tool-capable model
2026-07-13 17:02:32 -07:00
hanzo-dev 3ec43678de fix(code): default agents to full-auto tool-capable model 2026-07-13 17:02:10 -07:00
hanzo-dev 4e3877cb8f git: serve smart-HTTP at the git-host root so git clone https://git.hanzo.ai/<org>/<repo>.git works
Add host-guarded root-level /:org/:repo/{info/refs,git-upload-pack,git-receive-pack}
reusing the existing handlers. onGitHost gates on the request Host == git host
(defaultSSHHost(Domain)); on api/console hosts the routes fall through (c.Next())
so a bare /:org/:repo never shadows another surface. Advertised clone URL stays
/v1/git until cutover. Test: TestRootSmartHTTP_HostGuard (git host → handler runs;
other host → 404).
2026-07-13 15:41:24 -07:00
hanzo-dev 23c2ba42d8 cloud: mount zen co-resident + 18-dp-native metering
zen mounts as a /v1-scoped Claim middleware BEFORE ai's /v1/* catch-all
(Wire position 100, ahead of ai at 150). Claim routes every request whose
model is a zen SKU to zen's serving layer in-process and c.Next()s the rest
to ai, so zen owns the zen family (identity, tools, 1M ladder, codec) and ai
owns every other model + /v1/models. The frozen wire sequence is updated.

Billing for zen* moves from ai's in-handler metering (skipped — zen claims
before ai's beego catch-all) to zen's own Gate+Meter wired to the same
commerce metering client the edge gate uses — ONE billing source for zen*,
never double-billed, never free. Granularity is org/project/user mirroring
the edge gate: home org (principal.BillingOrg) pays, project
(principal.ValidatedProject) scopes spend caps, user is attributed. An admin
acting in another org bills their own home org.

metering.Usage now carries a typed money.Amount (native 18-dp USD — the
finance ledger's own precision) as the canonical debit; Record passes it
straight to finance with NO flooring to cents or micros, so an exact
per-token cost from zen debits exactly. Legacy AmountCents/AmountMicros
reconstruct the same Amount for older callers. See hip-00NN.

Bumps hanzoai/zen v1.0.0 -> v1.1.0 (additive API: TenantResolver, ctx-aware
Meter/Gate, Tenant.BillingOrg/Project, Usage.RequestID).
2026-07-13 15:39:38 -07:00
hanzo-dev 1f25b417e5 fix(code): disable zen5-ultra (403s), Fable tier falls through to zen5-pro; bump ai v1.806.12->v1.806.13
zen5-ultra routes to anthropic-claude-opus-4.8, which 403s on this account.
Drop the ultra backend chain from the Fable tier so it resolves to zen5-pro
(the working heavy-reasoning tier) instead. Picks up ai v1.806.13:
upstream-429 surfacing (typed apiError, status reaches client) + the
Anthropic thinking-budget -> upstream reasoning-vocabulary adapter
(glm max|high, openai low|med|high) so deep CC thinking reaches the deep
tier and invalid vocab no longer gets GLM-5.2 429'd. See hip-00NN.
2026-07-13 14:47:11 -07:00
hanzo-dev c7c5c96a79 chore(deps): bump hanzoai/money v0.2.0 -> v0.2.1 (honest 18-dp decimal floor) 2026-07-13 12:46:06 -07:00
antje c99ea4afd4 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	go.mod
2026-07-13 12:34:25 -07:00
hanzo-dev 9fedec0c33 merge: git-native feature + de-gitea → main
# Conflicts:
#	go.mod
#	go.sum
2026-07-13 12:22:40 -07:00
hanzo-dev d317c8f4dd chore: de-gitea — scrub branding/docs, keep legal+provider 2026-07-13 11:54:03 -07:00
antje 6ed3b15685 Merge commit '615eceec' 2026-07-13 11:19:05 -07:00
antje 3909afd435 merge: restore force-push-clobbered lineage — CLI device login + gpu --studio-dir, atto-USD money, datastore debrand, deps
origin/main was rewritten (tracker/git work force-pushed over ~13 shipped
commits). This merge reunites both histories; go.mod resolved as the
highest-version union + go mod tidy.
2026-07-13 11:19:05 -07:00
antje 2fa5262532 refactor(money): delegate exact-money machinery to shared hanzoai/money + hanzoai/decimal
The big.Int 18-decimal fixed-point implementation lives ONCE in the shared
packages; cloud/clients/money becomes the thin policy layer that pins the
credit unit to 18-decimal USD. Finance/treasury/admin call sites unchanged
in behavior — money, ledger, sqlstore, finance, admin-core tests green.
2026-07-13 11:13:59 -07:00
hanzo-dev 697dcf677a tracker: narrow Kind to {issue,pr,epic}; contract draws the three-plane boundary
Correct the taxonomy after confirming the real architecture: helpdesk tickets,
CMS content, ERP docs and knowledge entries are framework.DocType records (Hanzo
Base), and CRM Company/Contact/Opportunity is a bespoke relational store — a
DIFFERENT plane from the tracker. The tracker Issue is the engineering/project
work-item primitive, not the universal record.

- kinds narrowed to issue|pr|epic (drop deal/ticket/doc = domain records; drop
  task = the async plane, hanzoai/tasks). sources kept (legit work-item origins).
- contract.go rewritten to THREE orthogonal planes — tracker Issue (work items),
  framework.DocType (domain records), hanzoai/tasks (async execution) — and the
  thin one-directional seams (ExtRef links, Issue<->task), never embedding.
- Issue/IssueFilter/field docs + test seed aligned to the narrowed set.
2026-07-13 10:44:51 -07:00
hanzo-dev 3d860256d1 tracker(contract): the Hanzo work-item contract — ONE Issue, every surface a filter
Pin the alignment law as in-repo design source of truth (doc-file, like the
git package doc and tasks/CONTRACT.md): there is ONE work-item primitive — the
tracker Issue — and no second issue table. Every product surface (hanzo.team
board, git Issues/PRs tabs, CRM pipeline, helpdesk queue, CMS task list, an
agent's work) is a FILTER over the one table, never a parallel store.

Documents: the four immutable discriminators (Kind/Source/Repo/ExtRef) and
their orthogonality; the surface->filter mapping; the two tenancy roots (IAM
project = physical file; tracker Project = KEY-N team within it; git repo bound
by the Repo discriminator, a third thing); and the tasks seam — tracking
(intent+state) is not execution (durable async = hanzoai/tasks), composing in
exactly two directions (Issue->enqueue task, task->patch Issue board state),
never inverted.
2026-07-13 10:38:58 -07:00
hanzo-dev d4613a1a97 tracker: ONE polymorphic issue primitive — git/CRM/helpdesk/CMS/team all compose
Extend the tracker Issue with four immutable discriminators (Kind, Source,
Repo, ExtRef) so a project task, a git issue, a pull request, an epic, a CRM
deal and a helpdesk ticket are ALL the same row. Every product surface becomes
a FILTER over this one table — never a second tracker:

  - hanzo.team board  = ListIssues(Filter{})            (or {Status})
  - git repo Issues    = Filter{Repo, Kind:"issue"}
  - git repo PRs       = Filter{Repo, Kind:"pr"}
  - CRM pipeline       = Filter{Kind:"deal"}
  - helpdesk queue     = Filter{Kind:"ticket"}

store.go: additive kind/source/repo/ext_ref columns (DEFAULTed so existing
rows read as native team issues; idempotent ALTER for pre-spine DBs) +
org_repo / org_kind indexes; ListIssues takes IssueFilter (status+kind+repo+
source, each an optional bound predicate).

tracker.go: closed kinds/sources sets, normKind/normSource, issueFilter() from
?status=&kind=&repo=&source=; create accepts + validates the discriminators;
billing category stays the constant "issue" row, decoupled from work-item Kind.

Discriminators are identity — set once at Create, immutable on Update — so a
row never migrates between surfaces. Tests: TestIssuePolymorphicSpine proves
the filter slices + defaults + cross-repo source view.
2026-07-13 10:32:00 -07:00
hanzo-dev b8d6d9ee0c git(ui): native Hanzo Git web UI — repo list, browse, blob, commits
The embedded git host gains its browser surface (ui.go + ui_templates.go),
server-rendered in the ONE cloud binary — the native replacement for the
standalone Gitea web app, so git.hanzo.ai can retire it. Routes at /git/*:
org repo list, repo home (branches/HEAD/tree/clone/README), tree browse, file
view (binary-aware), commit log. Reads the SAME org-scoped store + go-git object
storage the API uses; every page scoped to the IAM-validated X-Org-Id with the
path-vs-identity guard (no cross-tenant read). html/template auto-escaping is the
XSS boundary. Build+vet clean; all clients/git tests green.
2026-07-13 10:01:43 -07:00
hanzo-dev 4f00303e73 git(env): drop CLOUD_ prefix on embedded git SSH env — GIT_SSH_{HOST,ADDR,HOST_KEY}
The embedded Hanzo Git subsystem's env is now bare GIT_* (was CLOUD_GIT_*). Not
set in any prod deployment (code defaults), so the rename is behavior-neutral;
takes effect on next build. Cleaner + gitea-free naming.
2026-07-13 09:06:07 -07:00
hanzo-dev a272085354 fix(ci): bustable BuildKit cache ids — a poisoned module cache wedged the release
The release has been failing on:
  go: github.com/hanzoai/otel-collector@v0.144.10: unknown revision v0.144.10

That tag EXISTS on GitHub and resolves fine from a clean cache (verified:
go get github.com/hanzoai/otel-collector@v0.144.10 -> exit 0). The failure is
the BuildKit cache mount, not the pin: with no explicit id, BuildKit keys the
cache by target path alone, so a negative lookup recorded while the tag did not
yet exist is remembered FOREVER and there is no way to evict it.

Give every cache mount an explicit, bumpable id (cloud-gomod-v2 /
cloud-gobuild-v2). Bumping the suffix forces a cold cache. This unwedges the
release without touching the (correct) otel-collector pin, and gives us the
lever we were missing the next time a phantom pin poisons the cache.
2026-07-13 09:00:34 -07:00
hanzo-dev bc4e73f46a git: rebrand OUR embedded git = Hanzo Git; default provider = git (git.hanzo.ai)
Per directive: only OUR internal embedded git is rebranded (Hanzo Git), and the
default source provider is our own git.hanzo.ai ("git"). External providers
github/gitlab/bitbucket/gitea.com stay available as sources — gitea.com is fine
as an external source, we just never brand OUR host as Gitea.
2026-07-13 08:43:15 -07:00
hanzo-dev da909ee96b fix(edge): raise BodyLimit to 16 MiB — the 4 MiB default capped the context window
The context window is a BODY-SIZE fact, not only a model fact: a chat request
carries its whole prompt in the request body. zip/fiber defaults BodyLimit to
4 MiB (zip.go: 'if cfg.BodyLimit == 0 { cfg.BodyLimit = 4 << 20 }') and cloud
never set it — so a 1M-token prompt (~4.3 MB of JSON) was refused by fasthttp
BEFORE any handler ran, with the opaque 400 'Error when parsing request' that
reads like a malformed payload rather than a size cap.

Effect: the 1M-context routes were unreachable in practice. Measured on prod
(v1.799.10, direct to pod:8000, bypassing ingress+gateway):
  1.5 MB body -> 350,152 prompt tokens -> 200 (glm-5.2 correctly auto-rolled)
  2.0 MB body -> 466,148 prompt tokens -> 200
  4.0 MB+     -> 400 'Error when parsing request'
So the cascade logic was right all along; the transport silently capped it at
~900k tokens. 16 MiB gives a 1M-token prompt ~3.7x headroom. The edge is
authenticated + rate-limited and fasthttp streams, so this is not a memory
vector. Env GATEWAY_BODY_LIMIT, mirroring the GATEWAY_READ_BUFFER_SIZE
precedent (same class of bug one layer up: the 4 KiB header default).

Tests pin the invariant so it cannot silently regress to the framework default.
2026-07-13 08:26:57 -07:00
hanzo-dev 4d7f61327d chore(deps): re-pin ai v1.806.12 + iam v1.31.25 (de-mattn) — mattn/go-sqlite3 now 0 in go.sum AND build graph 2026-07-13 00:28:26 -07:00
hanzo-dev e8309cbcaa chore(deps): de-mattn — beego/v2 v2.4.2 + xorm v1.4.1 (sqlite v0.3.0 already) + drop the mattn/go-sqlite3 replace (go list -deps mattn=0) 2026-07-12 23:45:47 -07:00
antje 615eceec9c merge: karma storefront loop — published Asset → listing image; product.created → ecom render; Campaign→product integrity
# Conflicts:
#	build.go
#	go.mod
#	go.sum
2026-07-12 23:33:27 -07:00
hanzo-dev aab2e3298b content: reverse storefront loop (product.created → ecom render) + Campaign→product integrity
Closes the Studio→CMS→Commerce loop the other direction. The forward edge
(storefront.go) publishes a rendered Asset onto the product image; this adds the
REVERSE — a new catalog product triggers its ecom render — plus the join-key
integrity gate. Decomplected over the COMMERCE event stream so commerce and content
never import each other.

Reverse loop (B):
- events: SubjectProductCreated/Updated ("commerce.product.*", on the COMMERCE
  stream) + PublishProductCreated/Updated on the existing events.Publisher (nil-safe
  no-op when NATS is absent, mirroring the order publishers).
- commerce product REST: publishProductEvents middleware fires the catalog event after
  a successful create/replace, reading the process Publisher off the gin context
  exactly like the order publishers — a total no-op when unwired.
- clients/catalogsync: in-process consumer subsystem on the COMMERCE stream mapping
  product.created → content.EnsureCatalogAsset (design == slug). Inert until
  CLOUD_COMMERCE_NATS_URL names the NATS carrying the events.
- content.EnsureCatalogAsset: product slug → ONE ecom Asset draft, idempotent (skip if
  a non-archived ecom asset already exists) and quiet (errNotConfigured / lane not
  installed = skip, never an error loop).

Integrity (C):
- Storefront gains ProductExists (reusing the same commerce S2S seam, X-Org-Id-pinned);
  enforceCatalogRefs before_save on Campaign.product fails closed on a dangling handle,
  validates only on set/change, and skips when commerce is unconfigured or erroring.
  Campaign-only on purpose: Asset.design is authored render-first (before the product
  exists), so gating it would reject the loop's first step.

Wired after content in subsystems.Wire() (frozen order test updated). Tests cover the
EnsureCatalogAsset idempotency/skip paths, the Campaign dangling-handle rejection, the
ProductExists S2S wire, the catalog event envelope + no-op, the REST middleware
classification, and the consumer dispatch ACK/NAK semantics.
2026-07-12 23:13:07 -07:00
antjeandGitHub 77b1e1a4f1 refactor(datastore): cloud on hanzo-ds/go — kill datastore-go/v2 (#279)
swap the 3 remaining driver call sites (audit_mirror, commerce/db/
datastore, o11y/event_ingest) hanzoai/datastore-go/v2 -> hanzo-ds/go,
and take o11y v1.5.26 (fully driver-clean). cloud graph now has zero
hanzoai/datastore-* — the driver's one home is hanzo-ds/go.
2026-07-12 23:02:12 -07:00
hanzo-dev 3d93b17e79 deps: bump ai v1.806.9->v1.806.10 + fix phantom o11y v1.5.23->v1.5.25
- ai v1.806.10: gofumpt-clean CI (unblocks ai release pipeline) +
  deepseek-r1-distill context parity + swarm datastore standardization
  (hanzo-ds/go v1.0.1, datastore-go v2.47.2).
- o11y v1.5.23 was a PHANTOM pin (tag never published; graph jumps
  1.5.21 -> 1.5.25). Cloud only built via warm CI module cache; a fresh
  resolve failed 'unknown revision v1.5.23'. Repin to the real latest
  v1.5.25. Verified: go build ./cmd/cloud = exit 0.
2026-07-12 22:58:00 -07:00
antje 427e781149 feat(cli): hanzo login defaults to the RFC 8628 device flow — QR + link, approve from any device
The ONE interactive login: the CLI mints a device+user code from IAM
(hanzo.id /v1/iam/oauth/device, client hanzo-app — the first-party client
seeded with device_code), renders the verification link as text and a
terminal QR, and polls /v1/iam/oauth/token until approved. No password
ever touches the terminal; works headless (GPU boxes, ssh). Same endpoints
and client as hanzo-dev's live device flow, so one server-side config
serves both. --username/--password-stdin keep the password grant for
automation; --token unchanged.
2026-07-12 22:56:18 -07:00
antje dec8130df5 fix(cli): gpu connect detects Apple Silicon — report chip + unified memory
detectGPUs only probed nvidia-smi, so a Metal/MPS box registered as
CPU-only in the fleet. On darwin/arm64 report the Apple chip as one GPU
with hw.memsize unified memory, MiB-formatted like nvidia-smi.
2026-07-12 22:51:45 -07:00
antje ae4b6eb06b feat(cli): hanzo gpu connect --studio-dir supervises the local render backend
The gpu-jobs claim loop renders on the LOCAL studio server (127.0.0.1:8188);
naming a checkout makes connect own that server's lifecycle too — launch from
the venv, health-probe /system_stats, one grace re-check, free the port and
relaunch on death or hang. Replaces the GB10 watchdog script and hand-rolled
systemd units: the hanzo CLI is the one way a BYO box joins the fleet, render
backend included. --daemon bakes the flag into hanzo-gpu.service.
2026-07-12 22:23:42 -07:00
antjeandGitHub 99f6209a80 chore(o11y): consume Datastore() accessor — o11y v1.5.23 (#276)
renames the store call site DatastoreDB() -> Datastore() (redundant DB
dropped) and bumps hanzoai/o11y v1.5.19 -> v1.5.23, which also completes
the clickhouse->datastore debrand indirects and pins a valid module zip
(v1.5.21/.22 zips were case-collision-invalid; .23 verified downloadable).
CGO_ENABLED=0 go build ./... green.
2026-07-12 22:04:40 -07:00
antje a9337fcbcd feat(finance): exact 18-decimal (atto-USD) money — kill cents flooring
The double-entry ledger stored money as int64 cents, so every sub-cent AI
charge was floored to 0 (free AI) and every call skimmed the fractional
cent on rounding. Money is now EXACT to 18 decimals end to end.

- clients/money: new immutable big.Int Amount in atto-USD (1e-18) — the
  EVM/ERC-20 uint256 unit, so the off-chain ledger and an on-chain credit
  token are the SAME value with no boundary rounding. No float, no deps.
- ledger core + SQLite adapter: Posting/Entry/Balance int64 → money.Amount;
  amounts stored as TEXT (atto overflows SQLite INTEGER past ~$9.20) with an
  O(1) running-balance column and a one-time cents→atto ×1e16 rebuild
  migration (existing prefunds carry over exactly on first open). Anchor
  ComputeRoot hashes exact atto.
- finance wallet / types seam / Formance adapter / admin grant+deposit /
  metering / treasury threaded through. Treasury reserve-fund facade stays
  int64-cents (revenue-share is cents-granular).
- ai debit path (v1.806.6) emits exact decimal-USD; wireFinance parses it to
  atto. Balance READ stays coarse cents (gates a >0 threshold only). Grant
  response returns balanceAtto so a sub-cent debit is visible.

Pin ai v1.806.3 → v1.806.6 (exact nano-USD billing; datastore-go/v2 registers
driver 'datastore', no clash with cloud's hanzo-ds/go 'clickhouse').
2026-07-12 21:59:09 -07:00
hanzo-dev 7c7cb8f06c content: Storefront edge — published catalog Asset → storefront product image
A published content.Asset (kind in ecom/product/lifestyle, design==product slug)
materializes its S3 URL into the org's Hanzo Commerce store Listing headerImage —
the runtime display layer karma.style already reads (GET /v1/store/:store/listing).
Replaces the build-time studio->S3->library.json->sync-*->site pipeline with ONE
publish-edge side effect, decomplected exactly like the social Distributor.

- storefront.go: Storefront seam + commerce S2S impl (Bearer COMMERCE_SERVICE_TOKEN
  + X-Org-Id over clients/commerceinproc; store via GET /v1/store/current; upsert
  PUT /v1/store/:id/listing/:design). Fail-closed (not_configured) with no token.
- content.go: wire sf edge at Mount; fire StorefrontPublish on the published edge;
  TransitionResult.Storefront.
- Tenant-scoped by IAM org; assets referenced by S3 URL; no sync scripts.

Tests (CGO_ENABLED=0): gate, url resolution, transition side-effect, fail-closed,
and the real commerce S2S wire incl. X-Org-Id tenant pinning.
2026-07-12 21:53:29 -07:00
hanzo-dev fc87e6c0d0 deps: iam v1.31.24 (tenancy: Org.Parent + recursive authz; signup/signin IP capture); datastore-go v2.47.0
datastore-go was pinned at v2.47.1 — a version the module proxy cannot resolve (the /v2 module path does not exist at that tag), so cloud did not build from a clean cache. v2.47.0 resolves.

Claude-Session: https://claude.ai/code/session_01RFrWpXc1BsqfrFYMbyDusJ
2026-07-12 21:44:10 -07:00
z 47b0a36b8b chore(deps): bump hanzoai/ai v1.806.8 -> v1.806.9 (>256k glm-5.2 auto-rolls to DS4-Pro) 2026-07-12 20:21:22 -07:00
hanzo-dev 7991397320 cloud: clickhouse->datastore debrand (zero clickhouse .go, datastore:// DSN, drop legacy CLICKHOUSE env) + pin o11y v1.5.21 (restore /v1/sentry, one datastore driver) 2026-07-12 20:08:39 -07:00
z e977047a2f chore(deps): bump hanzoai/ai v1.806.7 -> v1.806.8 (ONE-rule billing subject) 2026-07-12 20:03:12 -07:00
zandhanzo-dev a932834b64 refactor(billing): mirror ai ONE rule — billing subject is always the org
billingSubject(org,name) = org (lowercased), always. Deletes the personalBillingOrgs
and orgBillingOrgs allowlist parsers (PERSONAL_BILLING_ORGS / ORG_BILLING_ORGS). Keeps
the console billing view in lockstep with ai/object.BillingSubject so the view and the
gateway gate scope to the SAME subject. Tests prove the killed envs are ignored.

Needs go.mod bump github.com/hanzoai/ai -> v1.806.8 (run in a module-resolving env).
2026-07-12 20:01:25 -07:00
zeekay a6ae479c32 revert: otel-collector v0.144.10 — v0.144.13 forced mock v0.14.3 whose renamed API breaks o11y v1.5.17 (cascade pending) 2026-07-12 19:46:48 -07:00
zeekay c73cc1ce4f deps: otel-collector v0.144.13 + hanzo-ds/mock v0.14.3 — chproto-free datastore stack 2026-07-12 19:44:41 -07:00
zeekay a6f1fa59d4 debrand: datastore-go v2.47.2 (0 clickhouse/CH identifiers) + chproto->dsproto 2026-07-12 19:43:38 -07:00
zeekay 5ab750387a deps: datastore-go v2.47.1 — cloud go.mod/go.sum now 0 clickhouse + 0 signoz
datastore-go's transport moved to hanzo-ds/native, so the ClickHouse/ch-go
indirect is pruned from cloud entirely. No cloud package imports a ClickHouse
or signoz module.
2026-07-12 19:31:48 -07:00
hanzo-dev 300eda4bd9 deps: adopt otel-collector v0.144.10 (hanzo-ds datastore drivers) — drop signoz + -hanzo.0 replaces
- otel-collector v0.144.8 (+ replace => v0.144.8-hanzo.0) -> clean require v0.144.10
- dropped: replace SigNoz/signoz-otel-collector => hanzoai/signoz-otel-collector
  and the // indirect SigNoz/signoz-otel-collector require
- cloud now pulls hanzo-ds/{go,native,mock} transitively; 0 signoz in go.mod/go.sum;
  no cloud package imports a ClickHouse driver directly (build green)
Residual: one ClickHouse/ch-go // indirect graph line from a transitive dep's
go.mod (not compiled in) — clears when that dep drops it.
2026-07-12 19:19:54 -07:00
hanzo-dev 39889ae44d deps: bump hanzoai/ai v1.806.6 -> v1.806.7
Measured DO context windows + config-only resolver (the old table refused
deepseek-v4-pro at 131072) + oversized-prompt reroute to the 1M model.
This is what lifts hanzo code claude to the full 1M context.
2026-07-12 18:44:29 -07:00
hanzo-dev fcc506b038 debrand(o11y): drop signoz — query plane reads o11y_traces.distributed_o11y_index_v3
The o11y read plane was renamed signoz_* -> o11y_* (databases, tables, query
identifiers) at the source; the ClickHouse cutover migration
(o11y/deploy/clickhouse/migrations/0001_rename_signoz_to_o11y.sql) renames the
physical objects data-preservingly. Cloud's eval telemetry queried the OLD
physical name directly, so it would break post-cutover AND leaked the brand:

  eval/metrics.go: spanTable signoz_traces.distributed_signoz_index_v3
                        ->   o11y_traces.distributed_o11y_index_v3

Plus every prose/table-name reference across the in-repo o11y read plane and
commerce OTel bootstrap: signoz_traces/signoz_logs -> o11y_traces/o11y_logs,
SigNoz-fork provenance comments -> o11y/upstream. No source brand leaks remain.

DEPLOY: apply 0001_rename_signoz_to_o11y.sql during the collector cutover window
so prod ClickHouse objects match the new identifiers before this image serves.

Residual: go.mod keeps a REDIRECTED github.com/SigNoz/signoz-otel-collector key
(replace -> our fork; no SigNoz code fetched) — pulled transitively by
hanzoai/otel-collector's own go.mod; purge belongs to that fork's rename.
2026-07-12 17:43:34 -07:00
hanzo-dev 2e488527f2 feat(billing): adopt ai v1.806.6 — thread exact USD debit through the usage recorder
ai v1.806.6's UsageEvent replaced Cents(int64) with USD (exact decimal string,
atto-precise) so a sub-cent AI call bills precisely upstream. Adapt cloud's recorder:
- types.UsageInput gains USD (supersedes Cents when set).
- build.go SetUsageRecorder forwards u.USD.
- finance.RecordUsage rounds USD -> cents at the ledger boundary (usdToCents,
  round-half-up via math/big, no float). The local finance ledger is cents-denominated,
  so sub-cent floors to 0 exactly as the prior int64-Cents contract did — the atto path
  is commerce, not this store. Money-safety locked by TestUsdToCents.

Also carries ai v1.806.6's glm-5.2 1M context window (already in v1.806.5). Build ./...
green, finance tests pass.
2026-07-12 17:17:02 -07:00
hanzo-dev 78373130da fix(code): default hanzo code to glm-5.2, not the reserved word best
Claude Code treats `best` (like opus/sonnet/haiku) as a reserved model
alias and rewrites it to a claude-* id. api.hanzo.ai does not serve those
claude-* ids (a request 403s — see anthropicWire), so `hanzo code claude`
on the default `best` died at session start. Default to glm-5.2: the
stable GLM-5.2-class 1M-ctx frontier, a concrete catalog id CC passes
through unchanged; the backend still cascades on rate-limit / down.
2026-07-12 17:05:02 -07:00
hanzo-dev 7f4b166b49 fix(billing): bill the SUBJECT's wallet — a personal account gets a personal balance
The ledger already scoped correctly (org = which books, subject = which wallet in them), but both hooks passed the org for BOTH, collapsing every member onto the tenant's pool wallet. Since every signup lives in 'hanzo', a brand-new $0 account read HANZO's balance and sailed through the gate: we were enforcing our own wallet, not theirs. Now the gate reads, and usage debits, the subject ai already resolves — a person => their own wallet (personal plan), an org-owned application/service key => the org's account. That is the product: sign up as yourself with personal billing, then stand up an org whose users are your customers (Organization.Parent + AdministersOrg in hanzoai/iam). The invariant that must never break: the gate READ and the usage DEBIT key on the SAME wallet, or spend outruns the balance that admitted it — both use subject, keep them together. Also unpins o11y v1.5.16, whose tag was re-pointed upstream so its hash no longer matches go.sum (build fails verification); v1.5.17 is the unpoisoned tag.

Claude-Session: https://claude.ai/code/session_01RFrWpXc1BsqfrFYMbyDusJ
2026-07-12 16:52:20 -07:00
hanzo-dev a24d6324b8 refactor(team): rip the last Huly refs — zero Huly anywhere
- tracker.go: prose 'Huly/Svelte' -> 'prior Svelte'
- model.json: Slack-mapping wire attrs hulyChannel/hulyChannelClass ->
  teamChannel/teamChannelClass (seed-model data, NOT Go-referenced; valid JSON).
The clients/team/*.go debrand already landed on main. This closes it out.

NOTE: teamChannel wire IDs are new-workspace seed data; the deployed front
(front:v0.7.391) still speaks hulyChannel for Slack channel mapping, so a lockstep
front rebuild is needed for Slack mapping on NEW workspaces — flagged, not silent.
2026-07-12 16:50:11 -07:00
hanzo-dev 1ec565c4a5 fix(billing): bill the SUBJECT's wallet — a personal account gets a personal balance
The ledger already scoped correctly (org = which books, subject = which wallet in them), but both hooks passed the org for BOTH, collapsing every member onto the tenant's pool wallet. Since every signup lives in 'hanzo', a brand-new $0 account read HANZO's balance and sailed through the gate: we were enforcing our own wallet, not theirs. Now the gate reads, and usage debits, the subject ai already resolves — a person => their own wallet (personal plan), an org-owned application/service key => the org's account. That is the product: sign up as yourself with personal billing, then stand up an org whose users are your customers (Organization.Parent + AdministersOrg in hanzoai/iam). The invariant that must never break: the gate READ and the usage DEBIT key on the SAME wallet, or spend outruns the balance that admitted it — both use subject, keep them together. Also unpins o11y v1.5.16, whose tag was re-pointed upstream so its hash no longer matches go.sum (build fails verification); v1.5.17 is the unpoisoned tag.

Claude-Session: https://claude.ai/code/session_01RFrWpXc1BsqfrFYMbyDusJ
2026-07-12 16:48:12 -07:00
hanzo-dev 2e775ed572 chore(deps): bump ai v1.806.4 -> v1.806.5 (GLM-5.x 1M context window)
Deployed glm-5.2 was capped at 16384 tokens (the context_length_util.go
fallback) — long Claude Code sessions 402'd. ai v1.806.5 sets glm-5.x to a
1M window with 131072 modern fallback (commit d248ff98).
2026-07-12 16:30:39 -07:00
hanzo-dev 2cd359fdb2 cli: pin CC tier slots to fixed zen5 aliases
The four Claude Code tier slots (Haiku/Sonnet/Opus/Fable) are a fixed
zen5-* capability contract, decoupled from the resolved main model id.
Previously OPUS tracked ANTHROPIC_MODEL, coupling the tier to the main
choice; now OPUS=zen5-pro and FABLE=zen5-ultra are stable.

Decomplects which-tier from which-model: the tier->alias map is fixed
in the client; the alias->upstream map lives in models.yaml. Swap an
upstream (GLM -> Qwen 3.6 -> a future frontier) and every SDK/CLI/CC
integration keeps working unchanged. zen5-ultra carries its own backend
fallback chain (zen5-ultra -> zen5-pro -> zen5 -> zen5-flash) so the
Fable tier degrades gracefully if the premium upstream is unavailable.
2026-07-12 16:18:08 -07:00
hanzo-dev cde95fae20 fix(code): pin all Claude Code model slots to zen5 aliases
claude code's subagents, permission classifier, and /compact default to
built-in claude-* model ids (claude-haiku-*, claude-opus-*, claude-sonnet-*).
api.hanzo.ai does not serve those ids — a request 403s, which:
  - kills the classifier ('auto mode cannot determine safety of Bash')
  - kills every subagent (the 403 that dead-ended session cff690fc)
  - leaves /compact to run on a non-1M model -> 262145 > 262144 -> unresumable

anthropicWire now pins every CC tier slot to a served zen5 alias (the
Hanzo-standard mapping of CC tiers onto top OSS models resold via DO GenAI):
  ANTHROPIC_MODEL             = <model> (default best -> zen5/glm-5.2)
  ANTHROPIC_SMALL_FAST_MODEL  = zen5-flash  (DeepSeek-4 Flash, classifier)
  ANTHROPIC_DEFAULT_HAIKU     = zen5-flash
  ANTHROPIC_DEFAULT_SONNET    = zen5       (GLM-5.2)
  ANTHROPIC_DEFAULT_OPUS      = <model>
  ANTHROPIC_DEFAULT_FABLE     = zen5-pro  (DeepSeek-V4 Pro)

Live-proven: zen5/zen5-flash/zen5-pro/zen5-ultra all return 200 on the account;
only the raw claude-* ids 403. tests: TestAnthropicWirePinsZen5Tiers +
TestAnthropicWireExplicitModel lock the mapping and forbid raw claude-*.
2026-07-12 16:18:08 -07:00
hanzo-dev 720f58d599 refactor(team): drop Huly branding — no brand prefix, no vendor name
Debrand the team subsystem (our fork is Hanzo Team, not Huly):
- prose/comments: Huly -> Team / the platform
- hulyName() -> personName() (internal Person.name formatter)
- HULY_MODEL_VERSION -> MODEL_VERSION (no brand prefix at all, per the naming rule)
- TestHulyName -> TestPersonName

model.json WIRE class IDs (slack:class:SlackChannelMapping_hulyChannel, attrs
hulyChannel/hulyChannelClass) are deliberately UNTOUCHED: the deployed front
(ghcr.io/hanzoai/front:v0.7.391) speaks them, so renaming needs a lockstep front
rebuild — tracked separately, not a silent prod break.

Build + team tests green.
2026-07-12 16:18:08 -07:00
hanzo-dev 4a3ef817e6 feat(billing): honor ORG_BILLING_ORGS in console billing subject + bump ai
Bump hanzoai/ai to the ORG_BILLING_ORGS build (v1.806.3 + the allowlist), so the
gateway's BillingSubject promotes an allowlisted org (e.g. hanzo) to ONE shared
pool. Mirror the same scoped override in the console billing BFF (billingSubject)
so the console view scopes to the SAME subject the gate reads. Default empty =
zero behavior change.

Also refresh the stale hanzoai/o11y v1.5.16 go.mod checksum in go.sum (metadata
only; the zip/code hash was already correct — the readonly build passes), which
a moved tag had left inconsistent and which blocked every cloud build.
2026-07-12 16:18:08 -07:00
hanzo-dev 04a8bc55ab feat(cli): hanzo code defaults to the virtual best model
Change defaultCodeModel glm-5.2 -> best so `hanzo code claude` (no model arg)
auto-routes to the best-available coding model by quality and cascades on
rate-limit / out-of-credit / down (server-side, controllers/failover.go).
Explicit overrides still work (`hanzo code claude glm5.2`); the fuzzy resolver
validates `best` against /v1/models, where it is a real listed catalog entry.
2026-07-12 16:17:39 -07:00
zeekayandClaude Opus 4.8 57c96c251f datastore: cloud source → hanzoai/datastore-go/v2 (registers "datastore", not "clickhouse")
Completes the datastore standardization for cloud's own source: audit_mirror,
commerce/db, o11y/event_ingest now import github.com/hanzoai/datastore-go/v2
(the rebranded fork registering the UNIQUE sql driver name "datastore") instead
of the interim github.com/hanzo-ds/go (which registers "clickhouse" and collides
with upstream). Bumps ai v1.806.3 → v1.806.4 (its object/datastore.go likewise on
datastore-go/v2). cmd/cloud now links ZERO upstream ClickHouse/clickhouse-go/v2.
Remaining hanzo-ds/go is transitive via o11y/pkg/datastoremetrics — needs an o11y
release built off datastore-go/v2 (v1.5.16 tag currently resolves to the interim
hanzo-ds/go variant).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 11:21:51 -07:00
antjeandGitHub 1594706f5a fix(commerce): service-token S2S auth beats the IAM scope gate (completions 500 → clean 402/allow) (#273)
An in-process metering/billing dispatch (cloud → commerce via buildMeteringClient)
carries the verified COMMERCE_SERVICE_TOKEN *and* an X-Org-Id header (to select the
tenant namespace). The X-Org-Id makes IAMTokenRequired stamp iam_authenticated=true
with ZERO permissions (an S2S call carries no X-User-Permissions), so on an
Admin-masked billing route (/v1/billing/{balance,tier,usage}) TokenRequired's IAM
branch ran first, hasScope(0, Admin)=false → 403 "IAM principal lacks required
permission scope". The service token was never consulted; the balance read / usage
debit failed and the completions edge rendered that internal failure as a client 500.

Fix: in TokenRequired, check the service-token branch BEFORE the IAM branch. A request
bearing the KMS-sourced service token is the trusted platform S2S caller and must
authenticate as the service, never be subjected to the per-user IAM scope gate — even
when it also carries X-Org-Id. The two branches' logic is byte-identical; only the
order changed.

- Does NOT loosen the gate for external callers: a real IAM user never holds the
  service token, so they still hit the IAM branch and are masked-gated exactly as
  before (TestTokenRequired_UserIAMScopeGateUnchanged, IAMBranchEnforcesMasks).
- Prepaid gate stays fail-closed: funded → allowed, unfunded → clean 402
  insufficient_balance (TestInProcMeteringDispatch_ServiceTokenAuthPath drives the
  real chain over commerceinproc with finance NOT co-resident).
- The service token is KMS/env-sourced and never logged.

The 500-render itself lives in the hanzoai/ai dep (it serves /v1/chat/completions and
turns the internal balance/debit failure into a 500); once the cloud-side dispatch no
longer 403s, that failure no longer occurs.
2026-07-12 11:19:48 -07:00
antje 480e7eb51c chore(deps): ai v1.806.3 (fast-500 nil-CruSession guard) + o11y v1.5.16 (datastore debrand)
ai v1.806.3: nil-CruSession guard on both session funnels + auth-before-autoroute
(routers/base.go; fixes fast 500 on unauthenticated session read).
o11y v1.5.16: datastore debrand (DatastoreDB()). luxfi pins unchanged.
2026-07-12 10:40:56 -07:00
antje f1ed51ea06 Merge remote-tracking branch 'origin/chore/audit-datastore-env' into chore/datastore-roll 2026-07-12 10:37:08 -07:00
antje c4350b2b0f fix(finance): bill the org billing ACCOUNT (pool) for both read + debit, not the per-user subject
The ai gate read the account pool but debited the per-user wallet (read-subject != debit-subject),
so a funded account gated but never depleted. Key BOTH the balance read and the usage debit on the org
(its default-account pool wallet) in the wireFinance hook, so a funded account gates AND meters
consistently. Fund accounts, not users.
2026-07-12 10:18:38 -07:00
66761a3600 feat(cron): ONE durable platform cron on the tasks engine — retire every ticker and k8s CronJob (#268)
* feat(cron): ONE durable platform cron on the tasks engine — retire every ticker and k8s CronJob

clients/cron replaces the k8s CronJob fleet AND the commerce sweep ticker
with durable schedules on the shared embedded hanzoai/tasks engine
(v1.50.0 — the release whose sweeper actually fires on the sharded store).
The engine owns time; runs are durable workflows visible in the Tasks
console (/_/tasks, tasks.hanzo.ai) under the CRON_ORG shard (default
hanzo), namespace default, queue cloud-cron.

Entries are DATA in universe git: a ConfigMap labeled
cron.hanzo.ai/enabled="true" carries schedule + EITHER job.yaml (a
batchv1 Job manifest run to completion with Forbid concurrency, entry
label, TTL self-reap) OR poke.json ({url,method,bearerEnv,timeout} —
bearer resolved from THIS process's KMS-synced env, never stored).
A reconcile workflow — itself a durable schedule (*/5) plus one boot
pass — diffs ConfigMaps against cron-prefixed schedules: upserts are
drift-gated (rewriting resets the fire anchor), deletes never touch
foreign ids. Fire-time activities re-read their ConfigMap, so payload
edits apply next tick.

The commerce auto-recharge sweeper (clients/commerce/sweep.go) is
deleted; its 15m POST /v1/billing/auto-recharge/run-all becomes the
cron-billing-autorecharge poke entry — same request, same token, one
cron system.

Tests (-race): TestPokeEndToEnd + TestJobEndToEnd drive the FULL durable
path against a real embedded engine (org-shard schedule → trigger →
loopback worker → activity → completed run in the org shard — the exact
console-visibility + dispatch-routing the design stands on);
TestReconcileConverges pins upsert/delete/foreign-id/anchor semantics;
TestParseEntry pins the ConfigMap contract. commerce + subsystems suites
green.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

* feat(tasks): UI at /tasks (no /_/) + org/project/user-native gate (tasks v1.51.0)

The Tasks console moves to console.hanzo.ai/tasks + tasks.hanzo.ai/tasks —
the /_/ prefix is gone. Subsystem routes mount before the console SPA
catch-all, so /tasks wins the path and every other console route keeps the
SPA fallback. The gate now threads the FULL validated identity — org,
project (X-Project-Id, minted by identity middleware from the validated
project claim), user, email — into the engine via tasks v1.51.0's
WithIdentity; convention: project ↔ tasks namespace inside the org shard.
ZAP plane unchanged (loopback ungated + IAM-gated cluster listener).

The embedded SPA bundle is rebuilt with base /tasks/ in a follow-up sync
commit (hanzoai/admin builds it; clients/tasks/ui/dist is the embed).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

* ci: retrigger (Actions dropped the push event)

* chore(tasks/ui): sync SPA rebuilt with base /tasks/ (hanzoai/admin@448b189)

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-12 09:53:06 -07:00
antje 85af41bb35 chore(audit): dual-read CLOUD_AUDIT_DATASTORE_* with legacy CLOUD_AUDIT_CLICKHOUSE_* fallback
Prefer the datastore-named env keys, fall back to the clickhouse-named legacy
keys so a rollout mid-flight (new binary / old manifest, or vice versa) never
drops the audit OLAP mirror connection. Code-only; no roll.
2026-07-12 09:48:18 -07:00
antje 557bebe577 fix(deps): ai v1.805.11 (datastore fork) — kill clickhouse double-registration; native commerce read + per-subject finance deposit
ai v1.805.10 pulled upstream ClickHouse/clickhouse-go via ai/object, which double-registered
the clickhouse driver against cloud's hanzo-ds/go fork → boot panic (CI smoke caught it). ai v1.805.11
merges the clickhouse→hanzo-ds purge, so the upstream driver is no longer imported (verified: 0 in the
build, binary boots clean). Also: commerce.BalanceCents (native in-proc balance read — backfill + cockpit
read real balances, no commerce.inproc) and POST /v1/admin/finance/deposit (fund a SPECIFIC wallet:
hanzo/z, not just the pool).
2026-07-12 09:47:50 -07:00
hanzo-dev c824ae56b1 chore(deps): bump hanzoai/ai v1.805.10 → v1.805.13 (Anthropic /v1/messages tools translation) 2026-07-12 09:28:30 -07:00
hanzo-dev 4b6c0bbaf6 merge: hanzo code CLI launcher (claude/codex/dev on any Hanzo cloud model) 2026-07-12 09:25:20 -07:00
hanzo-dev 8546343592 merge: LOW-1 — ml/provisioning balance Gate keys on home org (principal.Payer), matching the debit (Red fast-follow) 2026-07-12 09:08:47 -07:00
hanzo-dev 9e6832ca33 fix(billing): ml + provisioning pre-create GATE keys on home org (principal.Payer), matching the paired debit
LOW-1 fast-follow (Red). In these two create-handlers the DEBIT correctly keyed on the
HOME org (principal.Payer(c)) but the pre-create balance GATE still keyed on the
EFFECTIVE org — the two swapped only the meter, not the gate (their Gate signature had
gained a projectValidated arg, so the class swap missed them). Effect: a SuperAdmin
masquerading into a victim org was balance-gated on the VICTIM's funds while the debit
landed on admin's ledger (money already correct; an availability/consistency nit).

Fix: swap the Gate org arg -> principal.Payer(c) in both handlers, restoring the
invariant the other ~8 resource meters hold — gate + debit BOTH key on home; data scope
(namespace/project) stays effective.

Test: TestResourceMeter_GateKeysOnPayerForMasqueradingAdmin resolves principal.Payer(c)
from a masquerade ctx (X-User-Owner=admin, X-Org-Id=victim -> admin) and asserts the
recCommerce balance check keyed on admin (home), never victim. go build ./...=0 (links),
gofmt clean, root ResourceMeter suite + clients/ml green (provisioning store tests are the
pre-existing CLOUD_KMS_MASTER_KEY_REF env gate, orthogonal).
2026-07-12 09:07:58 -07:00
zeekayandClaude Opus 4.8 d5c4f491f2 git: re-integrate SSH + ZAP + client-less REST push onto the generics framework
Ports the prior Git-over-SSH + ZAP transport + client-less REST push work
(commit 95ba376, written against the old *svc-receiver service) onto the
current cloud.Service[state] generics framework on main. A port, not a
rewrite: the DRY architecture is preserved — ONE control-plane core, ONE
git pack path, three thin transports (REST, ZAP, SSH) over them.

Handler pattern adapted: every `*svc` method became a free function taking
`s *cloud.Service[state]` (matching git.go's existing create/list/get/del),
`cloud.TenantStore` → `cloud.NewOrgStore`, methods → `cloud.Handle(s, fn)`
route registration, `s.log`→`s.Log`, `s.stores/storage/keys/ssh`→`s.State.*`,
`tenant(c)`→`org(c)` (principal.Org). Package-scoped helpers (storeFor,
provision, recordUsage, refState, cloneURL, sshURL, firePushBuilds, session)
are the current framework's free-function forms.

New files:
- core.go   coreCreate/List/Get/Delete/Usage — the ONE transport-agnostic
            control-plane impl; REST + ZAP both call it.
- pack.go   serve{Upload,Receive}Pack + ssh{Upload,Receive}Pack — the ONE git
            pack code path both smart-HTTP and SSH drive (io.Reader/Writer,
            transport-agnostic); readerOnly guards the SSH channel write side.
- ssh.go    golang.org/x/crypto/ssh server. Host key from CLOUD_GIT_SSH_HOST_KEY
            (KMS env) or on-disk ed25519 generated+persisted 0600.
            PublicKeyCallback resolves key→(org,user) by SHA256 fingerprint,
            fail CLOSED. Session accepts only git-upload-pack/git-receive-pack,
            enforces path-org == key-org. Listen CLOUD_GIT_SSH_ADDR (:2222).
- keystore.go  fingerprint-indexed global SSH public-key registry (public keys
               only — nothing to hash).
- keys.go   POST/GET/DELETE /v1/git/keys.
- push.go   POST /v1/git/repos/:name/push — build tree+commit from posted
            utf-8/base64 files, advance ref, create-on-first-push (composes the
            ONE provision), fire the SAME firePushBuilds hook receive-pack fires,
            return commit + cloneUrl + sshUrl.
- zap.go    git/zap/{createRepo,listRepos,getRepo,deleteRepo,usage} envelope
            adapters over the SAME core funcs, on the shared /zap plane. No
            second ZAP server, no gRPC.

Modified:
- git.go       repoView/toView gain sshUrl; state holds sshHost/ssh/keys; Mount
               opens the keystore + starts the SSH listener; routes() wires
               push+keys+ZAP; Shutdown stops SSH + closes the keystore. REST
               control-plane handlers are now thin adapters over core.go.
- smart_http.go  uploadPack/receivePack drive the shared pack.go path via
                 resolvePackRepo; firePushBuilds + session helpers retained.

Tests (go test ./clients/git/... — 16 pass): SSH key register accept/reject +
cross-org reject + end-to-end SSH clone+push over an in-process listener; a
zapface WS round-trip proving the ZAP path hits the SAME core as REST; REST
push create/update/build-hook, first-push provisioning, validation, and
cross-org isolation. tenant_isolation_test + git_test bind the SSH listener to
an ephemeral loopback port so tests never collide on :2222.

CGO_ENABLED=0 GOWORK=off go test ./clients/git/... passes; go build clean;
gofmt clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 09:05:56 -07:00
antje f7555233ad feat(finance): route edge meter + admin grant onto the finance ledger, + commerce→finance backfill
metering.Client fetchAvailable/Record now resolve finance.Current() first (micros→cents
ceil so metered_ai's AmountMicros debit is never dropped), commerce HTTP only when finance is
not co-resident. admin ApplyGrant credits the finance wallet (fixes the broken commerce.inproc
grant path). New DepositInput.Ref makes deposits idempotent; finance.MigrateOrg + SuperAdmin
POST /v1/admin/finance/backfill?org= carry each org's commerce balance into its finance wallet
exactly once at cutover. All money — balance, usage, deposit — now flows through the ONE per-org
double-entry ledger.

Verified: build + go vet clean; finance/metering/admin/core tests pass (micros fold, ref
idempotency, backfill exactly-once, zero-HTTP-when-co-resident all locked by tests).
2026-07-12 09:02:36 -07:00
antje ce177d2042 feat(finance): per-org double-entry prepaid wallet ledger (finance.Client) + ai native hooks
New clients/finance: ONE lightweight SQLite file per customer (orgs/<org>/finance.db),
double-entry wallet on the treasury/ledger core — deposit=funding→wallet, usage=wallet→revenue,
balanced within the org file, idempotent. Orthogonal money interface types.FinanceClient
(finance.Client, mirrors commerce.Client); NOT bolted onto the Deps bag and NO pick/RPC/disabled
cruft — a narrow published seam (finance.Publish/Current) every money consumer resolves.

BuildDeps.wireFinance constructs+publishes it and installs the ai router's typed
BalanceReader/UsageRecorder hooks (ai v1.805.10) so the prepaid gate reads balance + debits usage
by a DIRECT in-proc call, no HTTP. Rob-Pike small interfaces between systems, not a god-struct.

Remaining before cutover: edge meter + admin grant onto finance.Current(), backfill commerce
balances into <org>:wallet, then build/deploy/prefund/drop BALANCE_EXEMPT_USERS.
2026-07-12 09:01:38 -07:00
antjeandGitHub 33a9027b34 chore(deps): pin all hanzoai/luxfi deps to clean v1 OSS tags (#269)
Drop pseudo-versions and +incompatible for our own modules; everything now
resolves to a published v1 semver tag (v1 only, per policy):

  goa            v0.0.0-pseudo        -> v1.0.0   (first tag)
  sign           v0.0.0-pseudo        -> v1.0.0   (v1 path; 36 bogus v2 tags dropped)
  captable       v0.0.0-pseudo        -> v1.0.0   (first tag)
  pubsub-go      v1.0.1-0.pseudo      -> v1.53.0  (existing clean tag; HEAD==v1.53.0)
  gochimp3       v0.0.0-pseudo        -> v1.0.0   (module path fixed: Elandiro -> hanzoai)
  goauthorizenet v0.0.0-pseudo        -> v1.0.0   (go.mod added)
  sendgrid-go    v3.4.2-...+incompat  -> v1.3.0   (go.mod added; v1 path)
  luxfi/keys     v1.2.2 (force-moved) -> v1.4.0   (clean current tag)

CGO_ENABLED=0 go build ./... green.
2026-07-12 00:58:01 -07:00
cd800e8d66 fix(release): race-safe version assignment — unjam the cloud release lane (#271)
Root cause of the jammed lane (failed releases + phantom tags like v1.786.221):
the push step published the racy v<X.Y.Z> tag BEFORE it was confirmed free, and
the tag step hard-failed when a concurrent release had claimed that number
(computed 220, already tagged → 'rejected, already exists'). Result: a pushed
image with no matching git tag, mutable :vX clobbering, and dead releases.

Fix — decouple the immutable artifact from the versioned release:
- Push step publishes ONLY the unique sha-<sha7> (+ floating latest); never the
  racy version tag.
- Tag step assigns the next FREE v<X.Y.Z> ATOMICALLY: recompute fresh, retag the
  proven sha-image → :vX/:X.Y.Z/:X.Y via imagetools (metadata-only, byte-identical),
  git-tag it, and RETRY on collision (the git-tag push is the serialization point —
  a loser recomputes). Concurrent releases each grab a distinct free number.
- Compute-step collision is now a non-fatal hint (Tag step owns assignment).
- notify-universe rolls the Tag step's FINAL version, not the compute guess.

Preserves the invariant: git tag vX ⇔ image :vX pushed + smoke-passed. Logic
unit-tested locally (free-find + collision-skip). YAML valid.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 23:58:40 -07:00
hanzo-dev 77a30d1f99 merge: admin-org predicate (owner==admin) + home-org billing (debit/gate on X-User-Owner, data scope on X-Org-Id) — admin masquerade bills the admin ledger 2026-07-11 23:41:30 -07:00
hanzo-dev 82375164c0 billing: debit+gate on HOME org (X-User-Owner); embedded-commerce sudo = owner==admin
THE billing fix (B): split 'who pays' (HOME org, X-User-Owner) from 'whose data'
(EFFECTIVE org, X-Org-Id), which the old code conflated onto one org. A platform
SuperAdmin masquerading into another org now spends from the admin ledger; data
scope stays on the acted-on org.

- clients/principal: Owner(c) (X-User-Owner, bounded+cloned), BillingOrg(c) (home w/
  effective fallback, Validated-gated), Payer(c) (bare-string for the in-handler meters).
- middleware_identity: mint X-User-Owner=home for every validated principal (before the
  admin org-switch) + strip it on ingress (authorityHeaders) so a client can't forge who pays.
- middleware_billing: identityFromCtx keys User+Org (balance check AND debit) on BillingOrg.
- 11 resource-meter live sites (visor/s3/security/platform-run/functions/ml/provisioning/
  bots/tracker/automations): Gate+Meter+MeterUsage bill principal.Payer(c) (home); Org stays
  effective for the namespace. Background/reconcile paths (a.Org/r.Org/b.Org, meterRun) and
  the studio_render 'org' param bill the RESOURCE's own org — FLAGGED (see Red handoff).
- metered_ai + types: ChatRequest/EmbedRequest gain BillingOrg; meteredAI gate+record key on
  billedOrg(BillingOrg,Org); threaded principal.Payer(c) through the code engine (Synthesize/
  Embed) so internal RAG bills home too. Inner AI call keeps req.Org (data scope).

Part A (embedded commerce, clients/commerce mirror of the commerce repo): drop the spoofable
IsSuperAdmin boolean; auth.IAMClaims.IsSuperAdmin() gates homeOrg()=="admin" (HomeOrg from
X-User-Owner ?: Owner); iammiddleware reads X-User-Owner->HomeOrg (Owner stays effective);
EdgeAuth strips+mints X-User-Owner before the ?org override, stops minting X-User-IsSuperAdmin;
all .SuperAdmin() call sites -> .IsSuperAdmin(). Org-scoped IsAdmin untouched.

Tests (green): TestIdentityFromCtx_AdminMasqueradeBillsHomeOrg (owner=admin+effective=victim ->
debit on admin, data on victim), TestBilledOrg, TestMeteredAI_AdminMasqueradeBillsHomeOrg
(end-to-end debit user=admin), vendored TestIAMClaims_IsSuperAdmin masquerade+anti-escalation,
EdgeAuth strips forged X-User-Owner. go build ./...=0, go vet=0.

Rollout: pre-gateway (no X-User-Owner) billing falls back to effective (home==effective for a
normal caller; masquerade fails CLOSED). Deploy gateway (mints X-User-Owner) first.
2026-07-11 23:36:25 -07:00
hanzo-dev 06cad7ce9d cli(code): fail loudly on unresolved models; declare the Hanzo provider for codex
Three defects found by testing a real completion instead of --version:
  - an unreachable catalog silently passed the typed id straight through, so an
    agent booted on a model that does not exist and failed opaquely mid-session;
    resolution is now strict.
  - a stale ANTHROPIC_API_KEY in the shell outranks ANTHROPIC_AUTH_TOKEN and
    silently wins; it is cleared for the claude wire.
  - codex ignores OPENAI_BASE_URL and talks to chatgpt.com unless a provider is
    declared; declare Hanzo and select it (wire_api=responses, per upstream).
2026-07-11 23:34:33 -07:00
hanzo-dev 68978ed174 docs(identity): last 'global admin' prose -> SuperAdmin (zero repo-wide) 2026-07-11 23:22:37 -07:00
hanzo-dev 88610b6b8b refactor(identity): ONE fact per predicate — SuperAdmin = admin-org membership, OrgAdmin = own-org admin
Cloud was the odd one out: it minted SuperAdmin from TWO signals
(claims.IsAdmin && owner == adminOrg) while IAM's canonical User.IsSuperAdmin() is
just user.Owner == conf.AdminOrg, and IsOrgAdmin folded SuperAdmin into itself. Two
predicates that each meant one-and-a-half things.

Decomplected — two orthogonal facts, one predicate each:
  IsSuperAdmin = owner == adminOrg          (platform sudo; the SAME equality IAM uses)
  IsOrgAdmin   = the IAM isAdmin bit         (admin of one's OWN org; implies nothing about super)
A gate admitting either now writes IsSuperAdmin(c) || IsOrgAdmin(c) explicitly, so the
superset is visible AT the gate, not hidden inside a predicate. GuardScoped already did.

The admin org holds ONLY SuperAdmins (provisioned in, never promoted), so membership IS
the fact — the isAdmin bit is the orthogonal org scope, never a super gate. The KMS
machine-principal exclusion STAYS (a real guard: an admin-org machine token must never
be super). Test renamed + strengthened to lock the one predicate. Build ./... clean,
identity/admin/principal suites all green, KMS-machine exclusion tests pass.
2026-07-11 23:21:17 -07:00
87a950b377 security: golang-jwt/jwt v3 → v4 (no-patch high; v3 line abandoned) (#270)
The 4 commerce auth/token files imported the vulnerable golang-jwt/jwt v3.2.2
(dependabot high, no v3 patch — fix is off-v3). v4.5.2 (already present) keeps
StandardClaims/Valid()/int64 dates → API-compatible, zero code ripple vs the
v5 RegisteredClaims rewrite. Dropped the orphan v3 require. Full build + commerce
auth tests green. (dgrijalva/jwt-go remains transitive-only = unreachable.)

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 23:19:39 -07:00
antjeandGitHub e11dfe19d1 chore(deps): bump embedded iam to v1.31.22 (#266)
Advances the in-process IAM embed (clients/iam, HIP-0106) from the
v1.31.20 pre-release pin (31a798fb, #117) to the published v1.31.22 tag
(387c4a60). Brings the project claim mint + default-project seed (#120)
into cloud's embedded IAM so console admin surfaces match standalone
hanzo.id, already on v1.31.22.

API-compatible: iamserver.InitEmbed and object.Project CRUD unchanged
(iam go.mod hash identical across versions), no clients/iam adaptation.
CGO_ENABLED=0 go build ./... green; clients/iam + clients/platform tests pass.
2026-07-11 22:51:42 -07:00
33de017fd2 cloud: bump zip v1.6.0 + licensing v0.1.4 — off the deleted App.Mount, one-way surface (#267)
zip v1.6.0 deleted the deprecated/redundant surface (App.Mount/Route/ModuleFn/
UseFiber). cloud is off App.Mount (#257); licensing v0.1.4 migrated its one
App.Mount call. Build 0, framework tests green.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 22:51:03 -07:00
hanzo-dev 6ddf02a7a4 cli: hanzo code — launch claude/codex/dev on any Hanzo cloud model
One way to start any coding agent on any Hanzo model: endpoint, credential and
model are injected, so nothing is exported by hand. Two wires cover all three
agents (claude speaks Anthropic; codex and @hanzo/dev, a codex fork, speak
OpenAI), model ids resolve fuzzily (glm5.2 -> glm-5.2), and agents run full-auto
unless --safe. Config gains apiKey; the key the rest of the toolchain already
keeps in ~/.hanzo/config.json is read (never written) so one key serves every tool.
2026-07-11 22:36:34 -07:00
zandantje e3b1fa604d chore(datastore): purge clickhouse-go/datastore-go → hanzo-ds + debrand (Group A, v3)
Rebased on current origin/main (e3c544de, +4: #262/#258/#261/prepaid-wiring).
- ai v1.805.9 (= v1.805.7 hardened prepaid gate + purge) — NOT the money-regressing v1.805.8
- o11y v1.5.15, otel-collector v0.144.8-hanzo.0
- datastore clients → hanzo-ds/go; ClickhouseDB()→DatastoreDB(); clickhouse→datastore rip
- go.mod clickhouse-free; go list -deps ./cmd/cloud clickhouse=0; 0 BALANCE_EXEMPT in linked ai
- boots clean fail-closed (single sql.Register); luxfi pins as live; wire/DSN/env contracts preserved
2026-07-11 22:25:32 -07:00
7f0666a260 docs(projects,tracker): mark the two Project structs as deliberately distinct (#264)
WS4 audit flagged projects.Project and tracker.Project as duplicate types.
They are not: projects.Project is the Slug-keyed deployable site (one global
projects.db, org column); tracker.Project is a KEY-prefixed Linear-style issue
team living in a per-(org,project) tracker.db WITHIN one of those sites. Only
the universal storage-row skeleton (id/org/name/description/timestamps) is
shared; the natural keys carry different semantics (DNS label vs issue-ID
prefix) and the field sets are not subsets. Record the distinction on each type
so the finding is not re-litigated. Comment-only; no API or behavior change.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 22:13:06 -07:00
e3c544de2b feat(billing): thread validated-project bool through ResourceMeter.Gate (#262)
principal.ValidatedProject(c) now flows through ResourceMeter.Gate into
metering.AuthInput.ProjectValidated, so resource-creation caps harden
consistently with the edge BillingGate. Removes the hardcoded
ProjectValidated:false at resource_billing.go.

- Gate signature gains projectValidated bool (adjacent to project, mirroring
  principal.ValidatedProject's return + AuthInput's field order).
- Every *zip.Ctx caller passes principal.ValidatedProject(c); the three
  no-principal/client-body paths (metered_ai LLM decorator, background agent
  run, content studio in.Project) pass false — unvalidated stays soft, never
  fabricated true.
- Meter/Record path unchanged: Usage carries no ProjectValidated; cap
  enforcement is Gate-only, so threading it there would be dead code.

Stays SOFT in prod today: ValidatedProject is true only for a validated NAMED
project, and IAM seeds none yet, so no org has a project claim. No behavior
change now; named-project caps auto-harden per-org as IAM seeds them.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 21:44:51 -07:00
1c3206dcbf feat(platform): collapse buildType surface to pack|dockerfile (one way) (#261)
The build path (buildFrontendCmd) already chose its BuildKit frontend on
dockerfile presence alone: an explicit Dockerfile → dockerfile.v0, otherwise
hanzoai/pack via gateway.v0. buildType never gated the build — it was stored
metadata whose closed set still advertised the retired nixpacks/buildpacks/
static strategies and defaulted git apps to nixpacks.

Collapse it to the one true surface:
- closed set is {pack, dockerfile}; git source defaults to pack, not nixpacks
- image source always yields buildType image (no build), forced by source, so a
  client can no longer stamp a git strategy on a prebuilt-image app
- Goa contract (design.go + generated openapi3.json/yaml) enum, description and
  examples track the same {pack, dockerfile, image} set

Adds TestBuildTypeSurface pinning the default (pack), the dockerfile escape
hatch, rejection of every retired strategy, and image-source forcing.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 21:44:48 -07:00
a75cfa2f2c refactor(identity): collapse hand-rolled org/project reads onto principal (#258)
Six identity reads re-derived org/project inline instead of going through
principal — the ONE accessor. Route them all through it so the trust
decision lives in exactly one place and cannot drift.

- analytics tenant(): delegate to principal.Org — fixes a retained-buffer
  bug (org keyed the cloud_usage ledger past request end as a zero-copy
  fasthttp view; principal.Org clones). Gate unchanged.
- git/security projectScope(): read via principal.Project; absent header
  and literal "default" both map to the un-suffixed default scope via
  principal.IsDefaultProject, keeping today's (org,project) key shape.
- admin core.ResolveScope / core.GuardScoped / me / core.EmitAudit: read
  org via principal.Org (validated principal + org), composed with the new
  principal.IsOrgAdmin predicate. Admin-org bucket kept local.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 21:44:08 -07:00
hanzo-dev 1d1b2fd396 feat(billing): prepaid AI gate — wire ai v1.805.7 to in-process commerce, no exempt
Pin hanzoai/ai v1.805.7 (exempt concept removed: no BALANCE_EXEMPT_USERS/KEYS, no
fail-open; balance-unverifiable now DENIES). BuildDeps sets aiobject.CommerceTransport
= commerceinproc.Transport() and self-configures the ai module's commerceEndpoint to the
in-process placeholder when commerce is co-resident, so the embedded ai router's balance
read + usage debit hit the raw commerce gin (service-token, no socket) — the SAME one
ledger the metering client bills — not the customer proxy that 401s a service token.
Every external inference is now prepaid-gated with zero exempt principals.

hanzo/z was a normal customer, never admin; exempting it leaked money. Closed.
2026-07-11 21:37:00 -07:00
ece1560d2b feat(platform): delegate project lifecycle to IAM (one source of truth) (#260)
Projects are now owned by Hanzo IAM (hanzo.id) as the org-scoped
(owner,name) resource. Platform REFERENCES that store instead of owning
one: apps still live under a project, but create/list/get/delete/exists
of the bare project delegate to IAM in-process.

- New ProjectStore port (projects.go) with an in-process iamProjects
  adapter over github.com/hanzoai/iam/object — no HTTP hop, and IAM's
  canonical *object.Project is used verbatim (no platform-local clone).
- Delete platform's project ownership: the Project struct, the
  platform_projects table, and Create/Get/GetByID/List/Update/Delete
  project store methods. DeleteProject is replaced by DeleteProjectApps
  (cascade of the app tree only; the project row is IAM's).
- Apps key on the IAM project NAME (platform_apps.project_id holds it);
  the internal proj_ id indirection is gone, so reconcile/preview/domains
  use app.ProjectID directly and drop their project lookups.
- run.go get-or-creates the default project via the ProjectStore, using
  principal.DefaultProject as the single source of truth for "default".
- tenant() gates on principal.Validated(c) (canonical), not a raw
  c.User()=="" whitespace-blind check.
- Tests: fake ProjectStore + TestProjectLifecycleDelegatesToIAM proving
  create/delete route through IAM and delete cascades platform's apps.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 21:01:24 -07:00
5267caa5a6 feat(identity): bind X-Project-Id from the validated project claim; harden per-project caps (#259)
SanitizeIdentity now mints X-Project-Id from the validated JWT `project` claim
(idClaims.mintedProject), exactly like X-Org-Id from `owner` — the raw client
X-Project-Id is never a source. Still checked non-foreign to the effective org, so
a global admin viewing another org drops their own-org project. Mirrors the edge
(iamauth.Claims.MintedProject), so the in-binary path binds the same header.

principal.ValidatedProject flips CONDITIONALLY: (project, true) only for a
validated, NON-default project claim — the signal a project-scoped spend cap uses
to HARD-enforce. The default project stays soft (IAM does not seed default
projects yet; a blanket true would wrongly hard-402 every org). Named project caps
auto-harden one org at a time as projects are seeded.

Tests: claim-sourced project binding + forged/override client X-Project-Id ignored
+ cross-org claim refused on admin org-switch + X-Org-Id forgery still blocked;
ValidatedProject claim-backed→(project,true), absent/default→soft, unvalidated→soft.

Follow-up (WS3, out of scope): resource_billing.go Gate hardcodes
ProjectValidated:false — resource-creation caps stay soft until it threads
principal.ValidatedProject.

Co-authored-by: Hanzo <dev@hanzo.ai>
2026-07-11 21:00:51 -07:00
hanzo-dev c0a0ec73e8 refactor(auth): rename GlobalAdmin -> SuperAdmin (SOC2/FedRAMP term)
Eliminate "global admin" terminology across the cloud repo in favor of the
standard SuperAdmin term. Pure naming refactor; behavior preserved.

Identifiers (commerce auth + middleware + root):
- (*auth.IAMClaims).GlobalAdmin() -> SuperAdmin() + all call sites
- IAMClaims.IsGlobalAdmin field -> IsSuperAdmin (JSON tag isGlobalAdmin
  -> isSuperAdmin; SuperAdmin() still honors owner=="admin", the canonical
  predicate, so behavior is preserved)
- edgeauth isGlobalAdmin() helper -> isSuperAdmin(); requireGlobalAdmin ->
  requireSuperAdmin; test-local globalAdmin vars -> superAdmin
- const HeaderUserIsGlobalAdmin -> HeaderUserIsSuperAdmin, value
  "X-User-IsGlobalAdmin" -> "X-User-IsSuperAdmin" (commerce-internal header:
  minted+stripped in edgeauth, read in iammiddleware; no external sender)
- auth/globaladmin_test.go -> auth/superadmin_test.go

clients/admin: the deprecated isGlobalAdmin JSON alias (sibling of the
canonical isSuperAdmin, same value) is REMOVED rather than renamed — a rename
would collide with the existing IsSuperAdmin field, and the alias was a
transitional back-compat scaffold for this very migration. Tautological
alias-equality assertions dropped; isSuperAdmin checks retained.

Prose: "global admin" / "global-admin" / "GLOBAL-ADMIN" / "GlobalAdmin" in
comments and docs (LLM.md, k8s manifests) rewritten to SuperAdmin, case-aware.

Left untouched: cloud gateway header X-User-IsAdmin; principal.IsSuperAdmin /
IsOrgAdmin; svcorg's DefaultNamespace (global) kind.

build ./... clean; vet clean; SuperAdmin behavior-locking tests pass
(commerce auth/edgeauth/iammiddleware/catalog/costs/checkout, admin
scope/money, principal, root identity). gofmt clean. Zero GlobalAdmin /
global-admin remaining in .go/.md/.yaml.
2026-07-11 18:20:58 -07:00
hanzo-dev cca930891e feat(admin): per-provider credit ledger + usage funding endpoints
Two SuperAdmin endpoints for multi-provider credit-management (the console renders
them; contract is authoritative):
  GET /v1/admin/providers/credit  -> [{provider, grant_cents, burn_cents,
      remaining_cents, runway_days, has_credit, is_paid_only}]
  GET /v1/admin/usage/funding?from&to -> [{provider, model, funding, tokens,
      cost_cents, requests}], funding in {credit,paid,paid_only,byo}

DRY: reuses the admin auth guard (core.Guard), finance.go's DO billing read (real
k grant, live remaining/burn/runway), and the ONE cloud_usage warehouse (no new
store). DO is the seeded real row; others land as keys arrive. Funding is
provider-level-derived in v1; the per-call split lands when the ai metering write
stamps a funding column (next commit). Envelope = core.OK {status,msg,data:[...]}.
Two-ledger model kept distinct: UPSTREAM provider credits here vs DOWNSTREAM Hanzo
customer billing (commerce). Pure logic TDD'd.
2026-07-11 17:24:20 -07:00
hanzo-dev 33ce0f29f0 refactor(principal): IsSuperAdmin + IsOrgAdmin — two named predicates, not bare c.IsAdmin()
Per the SuperAdmin convention (SOC2/FedRAMP; standard term SuperAdmin, NEVER
'global admin'): name the two admin scopes explicitly.
- principal.IsSuperAdmin(c) = c.IsAdmin() — platform sudo; SuperAdmin ⟺ owner==admin org
  (X-User-IsAdmin minted only for that identity).
- principal.IsOrgAdmin(c) = IsSuperAdmin(c) || X-User-IsOrgAdmin — admin of one's own org.
GuardScoped now reads IsSuperAdmin (fast-path) + IsOrgAdmin (scoped) instead of bare
c.IsAdmin()/OrgAdmin. Pure rename — no behavior change, identity suite green.
2026-07-11 17:22:13 -07:00
hanzo-dev cd888836a6 fix(deps): bump hanzoai/ai v1.805.5 -> v1.805.6 (failover credit-cascade)
v1.805.6 makes credit/quota exhaustion + agreement gates (402/403/insufficient_quota)
cascade to the next provider in the fallback chain — Phase 2 of multi-provider
credit-management + fixes the do-ai->anthropic opus fallback.
2026-07-11 17:15:52 -07:00
hanzo-dev e23416cdb1 admin: close same-tenant over-visibility gap in GuardScoped
GuardScoped admitted ANY validated org member to their own org's admin
panels (/v1/admin/{overview,orgs,users,usage,analytics,me,bases}), not
just org-admins: SanitizeIdentity discarded the JWT org-level isAdmin bit
for non-admin-org principals (it only minted the GLOBAL X-User-IsAdmin
when owner==adminOrg), so GuardScoped's fallback (validated User+Org) let
a plain member through.

Mint a new, unforgeable X-User-IsOrgAdmin signal and require it:

- middleware_identity.go: add X-User-IsOrgAdmin to authorityHeaders
  (stripped on every ingress request, so a client can never forge it),
  and mint it for any validated principal with claims.IsAdmin &&
  !isKMSMachinePrincipal — covering both a global admin and an org-admin,
  owner-scoped and machine-excluded.
- clients/principal: add OrgAdmin(c) = IsAdmin() OR X-User-IsOrgAdmin.
- clients/admin/core.GuardScoped: require principal.OrgAdmin(c) in
  addition to validated User+Org; a validated non-admin member now gets
  the same 403 as an unvalidated caller. Guard (global-only) untouched.

Tests: orgAdminHdr now carries the bit; add TestScope_MemberWithoutOrg
AdminDenied (member without the bit is 403 on every scoped panel) and
TestSanitizeIdentity_OrgAdminHeader (org-admin gets the bit not global,
member/machine get neither, forged bit stripped on bearer + anon paths).
2026-07-11 17:11:53 -07:00
hanzo-dev 7b8134b882 Merge branch 'moneysafe' 2026-07-11 16:58:15 -07:00
hanzo-dev 9aeb3312e7 admin: fail-closed grant durability + deposit idempotency (no unaudited/double money)
Finding 3 (grant durability — ARCHITECT: FAIL-CLOSED). EmitAudit is a silent
no-op when State.AuditStore == nil, so on a no-audit-store deployment a
SuperAdmin grant moved REAL money with NO durable cloud-side before/after record.

Decision: FAIL-CLOSED. Grants are a real-money op and the audit store is always
present in any real deployment — audit_serve.go REQUIRES a persistent data dir
for the trail (hard boot error otherwise), and a nil store arises ONLY from the
explicit CLOUD_AUDIT_DISABLED dev opt-out. So ApplyGrant now refuses the grant
with 503 BEFORE any money moves when AuditStore == nil: no unaudited money move.
The check sits after org validation and before the deposit, so the existing
validation errors (amount/cap/unknown-org) are unaffected.

Residual (documented, not regressed): a post-deposit Append failure (store
present but the write errors) keeps the money-moved success response — the money
DID land, and failing it would both misreport the grant and, absent idempotency,
invite a double-credit retry. It stays a loud log, backstopped by the
request-level AuditTrail middleware which independently records the request and
fails the request CLOSED on its own write error (serve.go / audit_middleware.go).

Finding 4 (deposit double-credit on retry — WIRED). commerce.Deposit posted
/v1/billing/deposit with no idempotency key, so a commit-then-timeout (cloud's
15s client) could drive an operator double-credit on retry. The commerce backend
DOES enforce idempotency: POST /v1/billing/deposit reads X-Idempotency-Key,
scoped billing-deposit:<subject> — a completed key REPLAYS the receipt, an
in-flight key 409s, an absent key is legitimately additive (never dedup by
amount). Verified in ~/work/hanzo/commerce/api/billing/deposit.go.

Fix: thread a DETERMINISTIC key from the grant. Deposit/post gained an
idempotencyKey arg sent as X-Idempotency-Key. ApplyGrant derives it as
sha256(org|amountCents|currency|source|nonce) where nonce is the operator-supplied
Idempotency-Key — so a retried grant carrying the SAME nonce dedupes at commerce
while two DISTINCT grants (even same org+amount) never collide, and a nonce reused
for a DIFFERENT amount still lands (dedup can never silently DROP a real grant).
No nonce => no key => additive default preserved; we do NOT fabricate a
content-only key (it would wrongly dedupe two legitimate identical comps).
Residual (cross-service, frontend): effective end-to-end once the operator
console sends an Idempotency-Key per grant attempt, reused verbatim on retry.

Finding 2 (GuardScoped over-visibility — NEEDS CROSS-SERVICE, not fixed here).
GuardScoped admits any validated principal with non-empty c.User()+c.Org().
SanitizeIdentity (middleware_identity.go) mints X-User-Id for EVERY validated org
member and mints the admin signal X-User-IsAdmin ONLY for a GLOBAL admin
(owner==adminOrg) — it DISCARDS the JWT org-level isAdmin bit for non-admin-org
principals. So a regular member's sanitized identity is byte-identical to an
org-admin's, and GuardScoped admits regular members to their own org's admin
panels (same-tenant over-visibility of financials + user directory; NOT
cross-tenant — ResolveScope pins to c.Org()). The finding is REAL, but the
prescribed fix (require org-admin) CANNOT be done in clients/admin/*: the
org-admin signal is not minted, and middleware_identity.go is read-only in this
scope. Requiring the only admin signal we have (c.IsAdmin(), GLOBAL) would break
the deliberate, test-locked org-scoped tier (scope_test.go admits org-admins).
Correct cross-service fix: in SanitizeIdentity's `case owner != ""` branch, mint
X-User-IsOrgAdmin=true when claims.IsAdmin (owner safe, non-KMS), add it to
authorityHeaders (stripped on ingress so unforgeable), then GuardScoped requires
c.IsAdmin() || X-User-IsOrgAdmin=="true". Left for the middleware owner.

Tests: TestGrantCredit_NilAuditStoreFailsClosed (503, no deposit, balance
unchanged); TestGrantCredit_IdempotencyKeyForwarded (same nonce=>same key,
distinct nonce=>distinct key, no nonce=>no key). Existing money must-pass tests
(TestGrantCredit_DepositLandsAndAudited, TestSuspendReactivate_*, TestAdminAudit_*)
still pass unchanged.
2026-07-11 16:54:33 -07:00
hanzo-dev 13a77b7f91 admin: decomplect partial-commerce reporting on /overview (one partial pattern)
Finding 1 (undercount masked as healthy). core.OrgMoney swallowed the
Commerce.Spend/Credits errors to a silent zero, and /overview derived the
"commerce" source freshness from a SINGLE probe org — so if commerce was down
for 40 of 41 orgs the fleet spend/credits totals were an undercount while the
source still read "healthy". revenue.go / finance.go already report this
correctly via a `partial` flag + the core.ErrPartialRevenue sentinel.

Fix (decomplect to ONE partial pattern, not a second one):
- OrgMoney now returns (spend, credits int64, ok bool); ok is false when the
  spend OR credits read failed — the SAME (row, ok) contract revenue.revenueOf
  uses. An unwired commerce is NOT a failure (Spend/Credits return (0,nil) when
  unconfigured), so ok stays true and Ready() still distinguishes not-configured.
- overview folds ANY per-org OrgMoney failure into the commerce source as
  degraded, reusing core.ErrPartialRevenue, and derives freshness from the SAME
  per-org reads the totals fold instead of a single probe org.

orgs is a per-ROW panel (OrgRow[] via OKList; NO sources[] channel): a failed
read degrades THAT org's row to an honest zero — there is no aggregate total to
mislabel, so no change beyond the signature. The customer per-row/detail call
sites are best-effort and unchanged in behavior.

Test: TestOverview_CommercePartialOnPerOrgError — commerce 500s for one org of
two; the commerce source reports not-ok with an error while the healthy org's
spend still contributes (honest partial total, not a hard panel fail).
2026-07-11 16:54:05 -07:00
hanzo-dev 0f1b2a5fe5 test(graph): align unreachable-upstream tests + doc to the code's honest-empty-200 (not 502) 2026-07-11 16:36:30 -07:00
hanzo-dev 9bd1c0ec3b chore(kms): delete dead clients/kms/replication — a lone test with no production source
The subpackage contained only replication_test.go referencing an undefined Producer
(no NewProducer/BackupOnce/etc. anywhere), so it never compiled and failed go vet.
Zero importers. Pike: the best code is no code.
2026-07-11 16:33:39 -07:00
hanzo-dev ed95fef1c7 style(admin): gofmt clients/admin/revenue/revenue.go (new split file) 2026-07-11 16:19:17 -07:00
hanzo-dev 47dd91c6d2 Merge branch 'splitA' into splitmerge 2026-07-11 15:37:47 -07:00
hanzo-dev bd0709b723 admin: rewire Mount onto core + domains, retire in-package handlers
Rewrite the top-level admin package as the Mount + aggregator only. state ->
core.State (exported fields), and every top-level handler + helper is retyped to
*cloud.Service[core.State] and calls core.* for the shared kernel:
  - routes() registers the org-scoped panels (me/overview/orgs/users/usage/
    analytics/bases) behind core.GuardScoped and the platform reads
    (roles/applications/products/compute/o11y/sync + flags/waitlist) behind
    core.Guard, then delegates to audit/customer/revenue/finance Routes().
  - analytics.go keeps only the analytics-specific derivation (growth/retention/
    churn/active/LTV) folding over the core activity model + spend series.
  - o11y/compute/bases/waitlist/flags/types retyped to core.State + core.*.

Delete the now-moved audit.go/customers.go/grants.go/revenue.go/finance.go/
scope.go (their handlers live in the domain packages; their shared helpers in
core). doTokenFromEnv moves to admin config; iamAuditQuery moves to the audit
package.

Move tests with their code: audit store tests -> audit package; grantTag test ->
core; finance pure-math tests -> finance package. The full-mount integration
tests (admin/scope/cockpit/finance-aggregation) stay in the admin package and
now drive the real routes() so the harness mirrors Mount exactly. Behavior,
routes, tenant scoping and every assertion unchanged.
2026-07-11 15:35:31 -07:00
hanzo-dev 5efe43770a admin: extract shared core kernel + carve audit/customer/revenue/finance domains
Introduce clients/admin/core as the subsystem's shared kernel — the State
struct (upstream clients + adminOrg + audit store) and the one-copy business
primitives every admin surface composes: the two-tier gate (Guard/GuardScoped),
the /v1 envelope writers (OK/OKList/OKRaw/Fail), CallerCreds, the tenant-scope
predicate (TenantScope/ResolveScope/ScopedOrgs/Descendants), the IAM fan-in
(ListOrgs/OrgMoney/FindOrg/Display/SrcOf/SourceStatus), the ONE credit-write path
(ApplyGrant + EmitAudit + grantTag/grantNote/CreditRequest) and the fleet
activity/time-series model shared by analytics and revenue
(CustActivity/TxnPoint/SeriesPoint/FleetActivity/SpendSeries + bucket helpers).

Carve one package per handler domain over that kernel:
  - audit    -> /v1/admin/audit{,/verify} (store-backed + IAM fallback)
  - customer -> /v1/admin/customers* + /v1/admin/grants (list/detail/credit/
                suspend/reactivate/grants ledger)
  - revenue  -> /v1/admin/revenue
  - finance  -> /v1/admin/finance (+ the pure ComputeFinance derivation)

Each domain imports core for the kernel and shared logic; no business logic is
duplicated. Routes are registered per-domain via <domain>.Routes(app, s).
2026-07-11 15:35:03 -07:00
hanzo-dev 55feb39624 feat(bots): GET /v1/bots + POST /v1/bots/:runId/stop — org-scoped list+stop over the bot-gateway
Completes the bots surface (launch -> launch+list+stop). Both are thin,
org-scoped proxies onto the in-cluster bot-gateway (BOT_GATEWAY_URL, the same
server-side knob clients/bot uses), carrying the caller's validated tenant
context (X-Org-Id pinned to principal.Org, never a request param).

- GET /v1/bots normalizes the gateway's session rows into
  {runId,task,surface,status,sessionUrl,startedAt}, deriving sessionUrl here
  (the one place a session URL is built). Honest-empty {"bots":[]} on an
  unconfigured/unreachable gateway, a non-2xx, or an undecodable body -- never 5xx.
- POST /v1/bots/:runId/stop returns {runId,status:stopped}; a run the caller's
  org does not own is 404; an unreachable gateway is a clean 502.

Both require a validated principal so org-scoping can't ride a forged X-Org-Id.
Hermetic list+stop tests against a fake gateway assert normalization, sessionUrl
derivation, caller-org scoping, honest-empty, and 404/502 paths.
2026-07-11 15:15:56 -07:00
hanzo-dev 526455b098 refactor(admin): extract iam upstream client into clients/admin/iam (finishes the upstream-client layer) 2026-07-11 14:53:10 -07:00
hanzo-dev 4fbbbccd18 fix(deps): bump hanzoai/ai v1.805.4 -> v1.805.5 (enforceBalanceGate fail-open)
v1.805.5 adds the controller-side balance-gate fail-open (BALANCE_GATE_FAIL_OPEN_ON_ERROR)
on top of v1.805.4's nil-guard, so a broken/misconfigured Commerce billing backend
degrades to allowed-but-ungated instead of 500-ing every authenticated chat for
non-exempt users. Together they let the CR drop the commerce.hanzo.svc:8001 bridge
and keep commerceEndpoint unset per the in-process design.
2026-07-11 13:21:45 -07:00
hanzo-dev 04bda86558 build(cloud): bump hanzoai/o11y v1.5.12 -> v1.5.13 — Hanzo Sentry /v1/sentry backend routes live 2026-07-11 12:39:20 -07:00
hanzo-dev 1abb1676a5 merge: Hanzo Sentry /v1/sentry cloud edge — mount + DSN-ingest gate exemption (Red-GO) 2026-07-11 12:37:25 -07:00
hanzo-dev 456a60be22 fix(deps): bump hanzoai/ai v1.805.3 -> v1.805.4 (nil balanceGate 500)
ai v1.805.4 guards the nil balanceGate deref in resolveBillingKey that returned a
bare HTTP 500 on EVERY authenticated /v1 request (models, chat/completions,
messages) whenever commerceEndpoint is unconfigured (balance enforcement disabled).
RateLimitFilter calls resolveBillingKey before BalanceGateFilter's own nil guard,
so the embedded AI subsystem crashed every authed request while anonymous requests
(no token) 401'd correctly. Fail-open: a disabled billing subsystem resolves no
billing subject and never crashes a request.
2026-07-11 12:27:38 -07:00
hanzo-dev 14c89a2565 feat(o11y): expose /v1/sentry edge mount + DSN-ingest gate exemption
Cloud edge for Hanzo Sentry (the /v1/sentry product face served by the embedded
o11y runtime):

- mountSentry registers the /v1/sentry/* wildcard, forwarding to the SAME gated
  runtime handler the /v1/o11y wildcard uses (one runtime, two path families; no
  path rewrite — the Sentry routes are literal /v1/sentry/... in the runtime).
- gate() now exempts the DSN-authenticated Sentry ingest writes (isSentryIngestPath:
  POST /v1/sentry/{project}/envelope|store/, tight method+prefix+suffix match) from
  the principal gate — the runtime authenticates the DSN key, not a Hanzo session —
  while EVERY Sentry read/write API stays principal-gated (no cross-tenant leak).

Uses only the existing o11y runtime-handler API, so it builds against the current
pinned o11y (v1.5.12) and is inert (404) until the o11y dep is bumped to a build
that carries the /v1/sentry routes.

FOLLOW-ONS (coordinated separately):
- Bump the hanzoai/o11y dep to the tag containing the /v1/sentry routes to activate.
- Gateway needs a byte-identical isErrorIngestPath sibling for POST
  /v1/sentry/{project}/envelope|store/ so the tokenless DSN ingest is not 403'd at
  the edge (do NOT touch ~/work/hanzo/gateway here).

Test: TestGateExemptsSentryIngestButGatesReads (ingest exempt, reads/writes gated).
2026-07-11 11:58:40 -07:00
hanzo-dev e2c21e6d9a fix(social): honest at-rest comment — token NOT yet encrypted (RED HIGH)
The Account.Token comment claimed the store is SQLCipher-encrypted and 'keeps
it encrypted at rest'. False: openStore uses cek.Open, which today runs the
no-key plaintext fallback (real WithRawKey-from-KMS lands with the connect
flow). Token column is empty today, so no plaintext secret ships.
2026-07-11 11:36:16 -07:00
hanzo-dev 40c8b59d85 merge(social): publish edge + scheduler parity (fail-closed provider seam) 2026-07-11 11:35:11 -07:00
hanzo-dev 2370bd3acf refactor(admin): complete first-principles upstream clients — money.Cents + digitalocean
Finishes the batch-F rework (the extraction landed in 850d4c0; this is the second,
first-principles half that the earlier cherry-pick stopped short of):

- clients/admin/money — type Cents int64; the unit lives in the type, so
  ConsumedCents/MRRCents/CreditsCents collapse to Consumed/MRR/Credits. int64 casts
  only at the operator-contract boundary (wire unchanged, JSON tags kept).
- clients/admin/digitalocean — do.go extracted from the inline client; Client.{Ready,
  Balance,History}. Named digitalocean (not do) so it never collides with the local do var.
- clients/admin/commerce — reworked to the money.Cents unit + collapsed the always-equal
  (org,user) into one subject; dropped the MRRCents + duplicate-rollup shims.

Applied cleanly (0 conflicts) atop the extraction + tenant->org main. Build ./... green,
vet clean, admin+commerce+digitalocean tests pass (pure-Go cek gate).
2026-07-11 11:17:10 -07:00
hanzo-dev 850d4c0dad refactor(admin): first-principles upstream clients — money.Cents + commerce/health/digitalocean/health packages
Extracts admin's inline upstream reader clients into self-contained, package-namespaced
units and gives billing a single value type. Decomplect + package-as-namespace, per the
Hickey/DRY bar:

- clients/admin/money — type Cents int64; the unit lives in the type (ConsumedCents/
  MRRCents/… collapse to Consumed/MRR). int64 casts only at the operator-contract edge.
- clients/admin/commerce — Client.{Ready,Spend,Credits,Plan,Ledger,Costs,Deposit}
  (Deposit = the one write). Collapses the always-equal (org,user) into one subject;
  the bare-slug X-Org-Id+user invariant is baked into the client. Drops MRRCents +
  duplicate rollup-balance shims.
- clients/admin/digitalocean — Client.{Ready,Balance,History}
- clients/admin/health — Client.{Ready,Up}

Wire unchanged (JSON tags kept, DTOs stay int64 cents). Integrated onto current main:
preserves the commerceinproc.BaseURL(...) in-process routing and the tenant->org
vocabulary. Build ./... green, vet clean, admin+commerce+integrations tests pass
(pure-Go, cek gate). Completes the batch-F rework the user authorized.
2026-07-11 11:12:08 -07:00
hanzo-dev c39d2a13bc feat(social): publish edge + in-process scheduler (fail-closed provider seam)
Fold the live social stack's publish + schedule onto the native /v1/social domain:

- Publish edge (publish.go): the ONE publishPost path — claim (at-most-once across
  the HTTP handler and a scheduler tick), fan out to the channel's connected accounts
  through the injectable Publisher seam, record the honest outcome (published + external
  id, or failed + reason) on the post. POST /v1/social/posts/:id/publish + on-create
  fanout (scheduled-for-now-or-earlier) both call it.
- Scheduler (scheduler.go): an in-process periodic sweep (the native equivalent of the
  live stack's Temporal timer + hourly missing-post poller) that advances every org's
  scheduled -> published when the time arrives; idempotent, per-org, clean shutdown.
  Mirrors clients/commerce/sweep.go.
- Provider seam: fail-closed default (notConfiguredPublisher) that reports EXACTLY which
  OAuth-app credentials are missing (the live orchestrator's env var names) and NEVER
  fakes success. No Hanzo deployment carries provider creds today, so this is prod's
  honest state. GET /v1/social/providers reports per-network publish-readiness.
- Store: token on accounts (SQLCipher-encrypted at rest; live stack stores it plaintext),
  external_id/account_id/error on posts, ClaimForPublish/MarkPublished/MarkFailed,
  DueScheduled (the ONE deliberate cross-org system read), RecoverStuckPublishing.

Tenant isolation preserved: every publish is org-scoped; the scheduler's cross-org sweep
only reads (org,id) to dispatch into the org-scoped path. 12 tests (9 new) prove publish
success/not-configured/no-account, idempotency, per-org isolation, the scheduler sweep,
crash recovery, and live capabilities. go build -tags 'cloud cloud_mount' ./... green;
frozen wire-order guard green.
2026-07-11 11:08:49 -07:00
hanzo-dev 4e20e0234c cek: complete plaintext-store coverage on live-prod + flatten to top-level package
Rebased blue's RED-reviewed encrypt-at-rest onto the CURRENT live-prod commit
(v1.786.185). The release train added stores blue's base never saw, all opening
PLAINTEXT — closed every one through the same cek.Open seam:
  - tenantdb.go   (the SOLE per-tenant opener → code/git/functions/tracker)
  - gojabase, gatewaypolicy (gateway.db), dataroom (link_index.db)
Result: ZERO plaintext sql.Open("sqlite") left in the cloud data plane
(commerce self-encrypts under its own KMS key; cek internals excepted).

Flattened internal/cek → top-level one-word package cek. Trimmed the AI-slop
import comments to one line.

Verified CGO=1+SQLCipher: go build ./... green, cek tests green, and blue's
cek.Open shipping path pre-proven on ALL 47 real prod DBs (ciphertext + plaintext
shredded + exact row-count parity, 0 fail).
2026-07-11 10:56:53 -07:00
blueandhanzo-dev 14d5fab57f ci(cek): run frozen-format guard inside the Docker image build
The frozen-fixture test ran in Go CI but not inside the image under the pinned
Alpine libsqlcipher, so a sqlcipher-dev pin/base bump that changes the on-disk
format could go green in CI while bricking prod. Add the frozen-format gate to
the Docker RED gate (beside TestEncryptionProof), and make requireCipher honor
SQLITE_REQUIRE_CODEC=1 (a would-be skip becomes a FAILURE) so the in-image gate
is airtight: any format change now fails the IMAGE build, not just Go CI.

Verified: SQLITE_REQUIRE_CODEC=1 go test -run TestFrozenFixtureOpens ./internal/cek = ok.
2026-07-11 10:52:44 -07:00
blueandhanzo-dev 6f3c6ffb3d fix(cek): frozen-format CI fixture + exact sqlcipher pin + confidentiality-only scope doc
RED re-review closers:
1. Cross-version brick guard (vector b): the version-freeze was soft (unpinned
   apk sqlcipher-dev resolves from the live Alpine repo). Now:
   - Dockerfile pins sqlcipher-dev=4.6.1-r0 → a repo bump fails the build LOUDLY
     (never a silent prod brick).
   - Commit a FROZEN encrypted fixture (internal/cek/testdata/frozen/store.db
     + .dek, written under cipher_compatibility 4) + TestFrozenFixtureOpens that
     copies it to temp, opens via cek, and reads a known canary row. A future
     libsqlcipher format change makes the FROZEN store fail to open → red CI,
     which build-time SQLITE_REQUIRE_CODEC (fresh-db only) cannot catch.
     TestGenerateFrozenFixture (CEK_GEN_FIXTURE=1) regenerates it on an
     intentional format rev.
2. Scope doc (vector c): cek package doc now states it provides CONFIDENTIALITY
   at rest, NOT integrity/authenticity/anti-rollback vs a PV-write
   (node-compromise) adversary — out of the stated read-only model. The
   logical-id+epoch binding is deliberately NOT added (out-of-model complexity).

9/9 cek tests green on real SQLCipher (cgo) + nocgo; gofmt/vet clean. Migration
still deferred; live cutover gated on the user's supervised go.
2026-07-11 10:52:44 -07:00
blueandhanzo-dev 8636760c2f fix(cek): address RED review — shred plaintext, fileID KEK, fatal-missing-key, content-parity
RED review fixes on the encrypt-at-rest codec:
1. [HIGH] Shred the pre-migration <db>.plain.bak after the verified keyed reopen
   (overwrite+remove, single call site in openEncrypted). Nothing reaped it
   before, so every migrated store left a COMPLETE plaintext replica on the
   volume forever — the exact threat the codec exists to kill. Test asserts the
   backup is gone post-migration.
2. [MED] KEK no longer binds to the CLOUD_DATA_DIR-relative path (brittle: a
   dir change bricked the plane). A random per-file id is stored in the sidecar
   head (fileID(16) || wrapped-DEK) and the KEK derives from it — intrinsic to
   the file, config-independent. Test moves a store to a new dir + wrong
   CLOUD_DATA_DIR and it still opens.
3. [MED] Missing key on an encryption-capable build is now FATAL (fail-closed,
   same posture as KMS), not a silent plaintext downgrade. Encrypting() is wired
   into the boot log (serve.go). No new gate/env — keyed off the existing
   CLOUD_KMS_MASTER_KEY_REF + build capability.
4. [MED] Parity gate gains a rowid-independent per-table content hash (commutative
   multiset sum of per-row hashes over user columns), catching value mutations
   that count+schema+integrity_check miss while ignoring benign rowid renumbering.
   Dropped the inaccurate 'byte-faithful' wording. Cross-version cipher stability
   is enforced by FREEZING libsqlcipher in the build (an at-open cipher_compat pin
   is infeasible with mattn's URI-key requirement — the URI param is ignored and a
   post-open pragma runs after mattn reads the header; proven); any mismatch fails
   closed (test: corrupt/missing sidecar refuses).
5. [LOW] recoverInterrupted scrubs stale -wal/-shm; migration removes them before
   the swap so a plaintext WAL never sits beside an encrypted db. No statement
   logging on keyed conns; the key never rides a logged DSN/error.

8/8 tests green on real SQLCipher 3.53.1 (cgo) + nocgo fatal-key path.
2026-07-11 10:52:44 -07:00
blueandhanzo-dev 7c125ba373 feat(cek): encrypt-at-rest for all cloud SQLite stores (plaintext→SQLCipher, zero-loss migrate-on-open)
The CGO+libsqlcipher cloud binary shipped encryption DORMANT: all 29 stores
opened via bare sql.Open("sqlite", path), so /var/lib/cloud/*.db (crm PII,
treasury ledger, wallets, audit, team/entitlements) were plaintext despite
CLOUD_KMS_MASTER_KEY_REF being present. The SQLCipher primitives were linked
(hanzoai/sqlite cek.go) but never USED.

internal/cek.Open is the ONE encryption-at-rest seam every store now routes
through. When the master key is configured it transparently, under a per-file
flock: mints a per-DB random DEK (SQLCipher page key), wraps it AES-256-GCM
under KEK=HKDF-SHA256(master, principal) in a <db>.dek sidecar, and — for an
existing PLAINTEXT file — migrates it to SQLCipher via sqlcipher_export, then
verifies schema + per-table row-count parity + integrity_check by re-opening
the encrypted copy EXACTLY as the app will, BEFORE an atomic swap. Fail-secure:
key set on a non-encrypting build is a hard error; unverifiable migration leaves
plaintext intact; wrong master fails closed; crash mid-swap is recovered.

Proven with real SQLCipher (TDD): plaintext→ciphertext header, row parity,
.dek unwrap, .plain.bak preserved, idempotent reopen, wrong-key rejected,
dev-mode gated, nocgo fail-closed.

Migration is deferred to a maintenance-window cutover (this image built via
arcd) — NEVER encrypt against the current binary, which cannot open SQLCipher.

Rewires 29 open-sites; base/o11y external-module DBs are a follow-on.
2026-07-11 10:51:13 -07:00
d741a0848f cloud: migrate off deprecated app.Mount → All+AdaptNetHTTP (one mount path); tidy go.sum (#257)
zip #5 deprecated (*App).Mount(prefix, h): it is exactly
  app.All(prefix+"/*", zip.AdaptNetHTTP(h))
kept only as a behaviour-identical alias. Move every foreign-http.Handler
mount onto the explicit primitive so there is ONE way to put a route on the
app, and so the cloud money binary keeps building once zip deletes App.Mount.

Migrated all THREE route-mount call sites (the task scoped two; commerce is a
third — its exclusion note referred to the commerce.Mount *function*, not the
app.Mount(p, handler) inside it):
  - clients/plugin/plugin.go:125   app.Mount(p.Prefix, h) → app.All(p.Prefix+"/*", zip.AdaptNetHTTP(h))
  - clients/iam/iam.go:159         app.Mount(p, handler)  → app.All(p+"/*", zip.AdaptNetHTTP(handler))
  - clients/commerce/mount.go:147  app.Mount(p, handler)  → app.All(p+"/*", zip.AdaptNetHTTP(handler))
Behaviour-identical (Mount IS this composition). Also updated the four doc
comments that named the deprecated zip.App.Mount so no dangling reference to a
soon-deleted method remains. grep-confirmed ZERO app.Mount( route-mounts left.

go.sum: removed the two inert zap-proto/zip v1.3.0 hash lines (nothing in the
module graph requires v1.3.0 — orphan cruft a working `go mod tidy` would drop).
Full `go mod tidy` is blocked by a PRE-EXISTING, unrelated force-moved tag on
luxfi/keys@v1.2.2 (server serves h1:nuD+y5…; committed go.sum records
h1:XH5mRm…), so the two dead lines were removed surgically instead — luxfi/keys
and every other entry left byte-identical to origin/main. No GONOSUMCHECK hack.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 10:50:09 -07:00
hanzo-dev 35bb240e5c fix(commerce): derive org from IAM on the token path — no commerce-owned org
Per the one-authority directive: commerce must not require its OWN Organization
record; IAM is the sole org/user/auth authority. The service-token path already
auto-projects the org from X-Org-Id via the cached GetOrCreate resolver, but the
IAM-principal path c.Next()'d without resolving the org — it depended on
iammiddleware running upstream, and when it hadn't, GetOrganization MustGet-
panicked (500) / the org was absent, so an IAM org with no pre-existing commerce
row could not view or create billing. ensureIAMOrg now resolves the validated
X-Org-Id through the SAME cached GetOrCreate resolver on the IAM path too
(idempotent), so any IAM org "just works" and a thin billing record is
auto-projected on first use — commerce derives the org from IAM, never its own
table. This is also the root cause behind the "hanzo has no commerce org record"
wall on the live 2-org proof.
2026-07-11 10:45:33 -07:00
hanzo-dev 1ac5ee53d4 fix(billing): account handlers never panic on an unresolvable org
The billing-account CRUD (List/Create/Get/Update/Delete + project bindings +
members + loadOwnedAccount) called middleware.GetOrganization, which MustGet-
panics (→ recovered 500) when the request's org has no commerce Organization
record — the same class as the already-deployed spend-alert fix. Switch all to
GetOrganizationOK with a safe default (reads → empty, mutations → 400/404), so
an IAM principal whose org lacks a commerce record gets a clean response, not a
500. Completes the metering-path panic hardening.
2026-07-11 10:33:24 -07:00
02966ed201 cloud: zip v1.5.0 + OnShutdown teardown — fix teardown-before-drain race (#256)
Bump github.com/zap-proto/zip v1.3.0 → v1.5.0 (verified drop-in) and move
subsystem teardown onto zip's OnShutdown hook, deleting the hand-rolled
ShutdownAll reverse-loop.

Before: serve.go called ShutdownAll(specs) — a reverse-mount teardown loop —
BEFORE app.ShutdownWithContext. Subsystems were torn down while the listener
was still accepting and in-flight requests were still draining: a latent race
(a request could use a store that teardown had just closed).

After: MountAll registers each enabled spec's ShutdownFunc via app.OnShutdown
right after the subsystem mounts. zip drains those hooks LIFO — AFTER the
listeners stop accepting and in-flight requests drain — so registration-at-mount
reproduces the exact reverse-mount teardown order ShutdownAll gave, minus the
race. app.ShutdownWithContext now owns the whole teardown.

Scope is deliberately narrow: MountSpec, MountAll, Wire(), Typed, and the
OwnsHealth health loop all STAY (the imperative composition-root flatten was
proven unsound — a generic /v1/:name/health route is shadowed by 3-segment
subsystem routes). Only ShutdownAll and its serve.go call site are deleted;
audit/gateway-policy/telemetry teardown keep their positions.

Test: build_onshutdown_test.go drives a real in-flight request over a loopback
listener, shuts down mid-request, and proves (1) Shutdown blocks until the
request drains and (2) the MountAll-registered hooks then run LIFO = reverse
mount order. A second test locks the enablement axis + nil-Shutdown guard.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 05:35:45 -07:00
hanzo-dev f1ceb4e889 fix(o11y): exempt DSN-authed error-ingest from the principal gate
The Sentry error-ingest wire endpoints (POST /v1/o11y/api/<project>/envelope|store/)
authenticate with a DSN public key downstream in the o11y handler, not a Hanzo
principal. cloud's o11y gate() 403'd them for lacking X-User-Id, so the tokenless
ingest that the gateway allowlists (isErrorIngestPath) was blocked one layer deeper
— error-tracking could never ingest end-to-end.

Add the cloud-side counterpart: gate() now also exempts isErrorIngestPath
(byte-for-byte the gateway's matcher — method + /v1/o11y/api/ prefix + envelope|store
suffix, never a bare prefix). Reads under /v1/o11y/api/vN/... and the Issues
list/detail/update stay principal-gated; the exempted ingest still fails closed on a
bad/absent DSN key (401/503). Tested: TestGateExemptsErrorIngestButGatesReads.
2026-07-10 23:58:25 -07:00
0e8d033625 fix(commerce): sessionless webhook org resolve must not MustGet-panic (#254)
The live signed-webhook e2e (#118) got past HMAC verification and then
500'd: resolveWebhookOrg called middleware.GetOrganization — gin MustGet
— but webhook ingress runs OUTSIDE the auth-token group, so no
middleware ever set "organization" and every signature-VALID provider
delivery panicked ("key organization does not exist"). Switch to the
GetOrganizationOK variant that exists precisely for signature-verified
sessionless ingress; the header/env/default fallback chain below it now
actually runs.

Regression test drives resolveWebhookOrg on a bare sessionless gin
context and asserts no panic.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 23:39:24 -07:00
a525033a33 fix(commerce): seed the Square registry provider from env — unbreak inbound webhook validation (#253)
Every inbound Square webhook 401'd 'square processor not configured':
payment/providers/square registers an EMPTY Provider whose Configure()
only runs from BD's per-tenant charge resolver — but tryValidateWebhook
(the sessionless inbound path) reaches the registry slot directly. The
env-registering thirdparty/square init could never win the slot either
(import-order clobber / defer-to-existing), so webhook validation had no
configured processor in ANY deployment — 100% of live Square deliveries
were rejected.

init() now seeds Configure() from the deployment env (same vars +
SQUARE_ENVIRONMENT sandbox switch thirdparty reads; charge creds required,
webhook fields optional with ValidateWebhook's own fail-closed contract).
BD's per-tenant Configure still overrides per request for outbound money.

Regression guard drives env -> configFromEnv -> Configure ->
ValidateWebhook over a real Square-spec HMAC (url+body), plus tamper and
sandbox-switch cases.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 22:56:08 -07:00
8add272e26 feat(commerce): in-process auto-recharge sweep — retire the external CronJob (#252)
Standalone commerce was swept by a k8s CronJob (curl image + cluster hop +
token secret) POSTing /v1/billing/auto-recharge/run-all every 15m at
commerce.hanzo.svc:8001. With commerce folded into the cloud binary that
loop is redundant moving parts: the binary now dispatches the SAME request
loopback through its own embedded gin handler — full middleware chain
(TokenRequired service-token branch -> PlatformOnly mint gate -> datastore/
KMS context), byte-identical to the wire path (guarded by
TestSweepOnceWireContract).

- interval: COMMERCE_AUTORECHARGE_INTERVAL (default 15m; 0/off disables;
  garbage disables fail-safe — a card-charging loop must never guess)
- token: COMMERCE_SERVICE_TOKEN (absent -> disabled with a loud warn,
  not a 403-every-tick loop)
- first fire after one FULL interval (never front-run the outgoing CronJob
  during rollout)
- runs only where commerce mounts (single-writer pod; reader role never
  mounts commerce) -> exactly one sweeper, same guarantee the single
  CronJob schedule gave
- stops with Embedded.Stop

Unblocks deleting the commerce-auto-recharge CronJob + the standalone
commerce/commerce-sandbox pods (#118).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 22:33:02 -07:00
hanzo-dev 64dbb60f9f merge(social): fold native /v1/social domain (ship-dormant; no ingress cutover)
# Conflicts:
#	subsystems/subsystems.go
#	subsystems/wire_test.go
2026-07-10 21:46:12 -07:00
hanzo-dev ef478f735b merge(ads): fold native /v1/ads domain
# Conflicts:
#	subsystems/subsystems.go
#	subsystems/wire_test.go
2026-07-10 21:45:26 -07:00
hanzo-dev 1a41cfd775 merge(marketing): fold native /v1/marketing domain 2026-07-10 21:44:39 -07:00
hanzo-dev 8ed8014d78 feat(content): real Generator + Distributor over the framework CMS, hardened
Turns the agentic-marketing content loop from scaffolding into a working
edge pair, then closes every finding from the adversarial review.

Edges (wired at Mount, fail-closed until configured):
- Generator: zen5 copy via deps.AI.ChatCompletion (metered Bill.Gate/MeterUsage)
  + studio assets via the ComfyUI Qwen-Image-Edit-2511 graph.
- Distributor: hanzoai/social Public API fan-out, per-brand key custodied in KMS.
  errNotConfigured until a brand connects a key — no key, no fan-out.

Hardening:
- Publish TOCTOU interlock: a per-item, store-backed lease (framework fw_locks,
  the ONE cross-process coordination primitive) serializes concurrent publishes
  of the same item across drivers and pods; non-idempotent fan-out runs once.
- source_media SSRF gate: the URL validator fails closed on unparseable/backslash
  input.
- external_ids is server-managed: the before_save guard rejects a client write;
  Publish records it under the lease as a trusted server write.

Adversarial regression suite pins each guarantee from the outside (raw framework
PUT, direct ops, concurrency): red_adversarial / red_rereview / red_final /
red_lease_final, plus blue_hardening and per-file unit tests.

One open item recorded as a HARD GATE in clients/content/LLM.md: lease
TTL-preemption re-opens the double-post window for a brand with ~15+ slow
channels (fan-out (N+1)x20s > 5m TTL, external_ids recorded only at fan-out end).
ZERO exposure until a brand connects a social key; the fix (lease heartbeat/renew
preferred) MUST land in the same change that connects the first real key.

Claude-Session: https://claude.ai/code/session_013jh8aka8q8RvhhVQ1psMeW
2026-07-10 20:54:56 -07:00
hanzo-dev 0598394b83 fix(social): add social to frozen wire-order guard (RED ship-blocker) 2026-07-10 19:13:09 -07:00
59aa40c20c hardening(consolidation): split-proof the framework-content guard + DataDir doc (RED INFO) (#251)
Two INFO items from RED's #250 re-review:
- TestFrameworkContentModulesLinked asserted only the module registry. erp's
  ledger-posting HOOKS register in a SEPARATE init() step, so a future split of
  registerHooks() out of erp's module init() could drop the hooks while the guard
  stayed green. Add framework.RegisteredHookCount() and assert it > 0 so the guard
  fails if erp's hooks (computeJournalTotals, journalEntry/paymentEntry
  submit+cancel, …) are ever unlinked from the binary.
- gojabase Config.DataDir comment said "{tenantSlug}.db" (the pre-C1 name); the
  on-disk segment is TenantSegment (injective, traversal-safe base32 of raw org
  bytes). Comment now matches the code.

go build + go test ./subsystems/... ./clients/framework/... green.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 19:11:18 -07:00
hanzo-dev 0762959bd7 feat(ads): native /v1/ads domain in the cloud binary
Net-new per-org ad-campaign domain on the ONE cloud framework (zip/Fiber +
cloud.Deps + per-org SQLite), the same shape clients/crm uses — twin of crm.
Registered in subsystems.Wire() right after crm; frozen wire sequence updated.

/v1/ads surface (all org-scoped, tenant-isolated on the bearer owner claim):
  GET    /v1/ads/health             (auto, serve.go liveness)
  GET    /v1/ads/summary            per-org roll-up (total/active/budget/spend)
  GET    /v1/ads/campaigns          list (?status=)
  POST   /v1/ads/campaigns          create
  GET    /v1/ads/campaigns/:id      detail
  PUT    /v1/ads/campaigns/:id      update
  DELETE /v1/ads/campaigns/:id      delete

Campaign = root of the ad hierarchy (campaign -> ad sets -> ads; ad-set/ad legs
hang off this seam): Platform (meta/google/tiktok/x), Status (draft/active/
paused/completed), Objective, Budget/Spend (cents).

Tests: per-org isolation + full CRUD + summary round-trip, both green.
2026-07-10 18:50:50 -07:00
hanzo-dev 1ddd08ff0c feat(social): fold the live social stack as native /v1/social domain
In-process fold of github.com/hanzoai/social (social-backend/frontend/
orchestrator, a Postiz-style scheduler) onto the ONE cloud framework
(zip/Fiber + per-org SQLite), twin of clients/crm + sibling of the
marketing fold. NOT a proxy to the standalone social pods.

Two entities faithful to the live Public API (clients/content publish.go
already talks to it): Account = a connected channel (the stack's
integration), Post = content published/scheduled to a channel. Scheduling
is a Post with status=scheduled + a future scheduleAt, not a third entity.

Every query filters WHERE org=? on principal.Org (validated bearer owner,
HIP-0026); one tenant can never read/mutate another's rows. Registered in
subsystems Wire() after crm with a ctxShutdown that closes the DB.

Surface (org-scoped, /v1 only): summary + accounts CRUD + posts CRUD.
Generic liveness serves GET /v1/social/health.

Build: go build -tags 'cloud cloud_mount' ./... GREEN; 3 store tests pass
(per-org isolation across accounts+posts, post CRUD+summary, account CRUD).
2026-07-10 18:44:03 -07:00
hanzo-dev 855f4b617a feat(marketing): fold hanzoai/marketing as native /v1/marketing domain
Mount github.com/hanzoai/marketing in-process on the ONE cloud framework
(zip/Fiber + cloud.Deps + per-org SQLite), the same shape clients/crm uses —
NOT a proxy to a standalone marketing pod. Registered in subsystems.Wire()
right after its twin crm; frozen wire sequence updated to match.

/v1/marketing surface (all org-scoped, tenant-isolated on the bearer owner claim):
  GET    /v1/marketing/health             (auto, serve.go liveness)
  GET    /v1/marketing/summary            per-org roll-up (total/active/budget/spend)
  GET    /v1/marketing/campaigns          list (?status=)
  POST   /v1/marketing/campaigns          create
  GET    /v1/marketing/campaigns/:id      detail
  PUT    /v1/marketing/campaigns/:id      update
  DELETE /v1/marketing/campaigns/:id      delete

Campaign faithful to the repo domain: Channel (email/sms/social/meta/google/
tiktok), Status (draft/active/paused/completed), Objective, Budget/Spend (cents).
Genetic-optimizer / ML-forecasting / ad-platform integrations not folded yet.

Tests: per-org isolation + full CRUD + summary round-trip, both green.
2026-07-10 18:01:08 -07:00
hanzo-dev a969684635 Merge fix/genai-tracer-clobber-repin: pin ai to v1.805.3
Bumps github.com/hanzoai/ai v1.805.2 -> v1.805.3 (GenAI tracer pinned at adopt
time; gen_ai spans survive the embedded o11y/SigNoz global tracer-provider
reassignment and reach o11y_traces). go.mod/go.sum only, no cloud source change.
2026-07-10 17:58:22 -07:00
hanzo-dev d0f5a2635f deps: pin ai to v1.805.3 (GenAI tracer immune to o11y global-provider clobber)
Bumps github.com/hanzoai/ai v1.805.2 -> v1.805.3. v1.805.3 pins the GenAI
tracer at adopt time so the embedded o11y/SigNoz runtime reassigning the
process-global OTel tracer provider can no longer redirect gen_ai spans off
the o11y sink — they reach o11y_traces. No cloud source change; go.mod/go.sum only.
2026-07-10 17:57:43 -07:00
hanzo-dev d2bc54034b feat(content): native agentic-marketing content loop on the framework CMS
Add clients/content — the ONE Go-native replacement for the bespoke karma
Python pipeline. A framework app-lane (module "marketing": Campaign, SocialPost,
Asset) + a thin /v1/content/* control-plane. Store-less: content IS framework
documents; the subsystem is a stateless orchestrator over the framework store +
the zen5/studio/social edges.

- lifecycle.go: ONE state machine (draft→in_review→approved→queued→published,
  +archived), a pure value read by the before_save hook (enforces edge legality
  at the storage boundary) and the transition endpoint (same check + fan-out).
- hooks.go: before_save gate on every publishable DocType.
- content.go: board (cross-DocType aggregate), lifecycle, transition (+best-effort
  distribution), generate/publish/channels. Org-scoped via principal.Org; never a
  5xx from a foreseeable condition (fail-closed 503 / honest 4xx).
- generate.go/publish.go: Generator + Distributor seams with fail-closed defaults;
  real zen5 (deps.AI) + studio (ComfyUI) + hanzoai/social wiring documented for the
  follow-up. Exported Generate/Publish/Transition are the ONE impl the HTTP surface
  AND the automations connector call.
- framework: add Get (read-one), exported ErrNotFound/ErrConflict/ErrBadRef +
  IsValidationError so in-process callers classify errors without string-matching.
- automations: connector_content.go exposes content_generate/transition/publish as
  flow steps + MCP tools (in-process, org-scoped) so the loop runs autonomously
  (cron flow: generate → wait_for_approval → transition → publish).
- subsystems: Wire content after knowledge; frozen wire-order test updated.

Tests: lifecycle table, before_save hook, end-to-end loop over the real framework
store (install→create→board→transition→publish), forge-403, cross-org isolation.
go build ./... + go test (content/framework/automations/subsystems) all pass.

Claude-Session: https://claude.ai/code/session_013jh8aka8q8RvhhVQ1psMeW
2026-07-10 16:48:54 -07:00
6e183ec034 fix(subsystems): restore cms/erp/help framework content modules (#248 regression) (#250)
#248 (Wire() composition root) rewrote subsystems.go and dropped the blank
imports for cms/erp/help. Those three are NOT mount subsystems — no HTTP surface,
never in Wire(). Each registers DocType fixtures and, for erp, ledger-posting
lifecycle hooks (computeJournalTotals, journalEntry submit/cancel, paymentEntry
submit/cancel, …) into the always-on clients/framework engine from a package
init() (framework.RegisterModule). Dropping the imports left them out of the
binary: /v1/framework/* carried no erp/cms/help and the erp ledger hooks were
silently gone. No mount test caught it (frozen[]/Wire() cover only mount specs).

Fix (RED-verified): re-add the three blank imports under an explicit "framework
content modules" comment; add framework.RegisteredModules() + a guard test
(TestFrameworkContentModulesLinked) asserting the engine carries each lane so the
drop cannot silently recur. Also relax TestDepGatedSubsystemsFailClosed to accept
any non-2xx — a dep-disabled subsystem denying 403 is fail-closed; >=500 was
wrongly strict (o11y denies 403, ai returns 5xx).

go list -deps ./cmd/cloud shows cms/erp/help; go build ./... green;
go test ./subsystems/... ./cmd/cloud/... -race green.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 16:24:14 -07:00
hanzo-dev 295ce084e8 fix(billing): metering gate no longer panics on an unresolvable org
The S2S metering path (ScopeRules → ListSpendAlerts; AuthorizeVerdict →
AuthorizeSpendCap) can reach these handlers with no "organization" context key
when X-Org-Id does not resolve to a commerce org (e.g. the agents scheduler
probing an unprovisioned org). middleware.GetOrganization MustGet-panicked
there → a recovered 500 storm on the money path (observed live: "key
organization does not exist", ~every 5-15s). Switch the metering-verdict
handlers + billingSubject to GetOrganizationOK with a safe default — no org
means no org-scoped caps, so ListSpendAlerts returns empty and
AuthorizeSpendCap allows — instead of panicking. Regression test proves neither
handler panics with no org.
2026-07-10 16:16:19 -07:00
hanzo-dev 1f4a02f938 feat(principal): carry Project + BillingAccount from the verified identity
types.Claims gains Project + BillingAccount; principal.BillingAccount(c) reads
the gateway-minted X-Billing-Account-Id, added to subScopeHeaders so the raw
client copy is stripped on ingress and re-injected only for a validated
principal (mirrors X-Project-Id). It is an ATTRIBUTION hint only — the debited
account is always resolved server-side by commerce from the org's
ProjectBinding, never trusted from the header — so a mislabelled account can
only ever misattribute the caller's OWN spend within its own org, never
redirect spend to another tenant. Inert until IAM emits the billing_account
claim + the gateway mints the header (slices 63/64).

Also fixes a stale test left by de2a97a3 (/metrics is now a console page, not an
API 404 — dropped from the must-404 list).
2026-07-10 16:00:57 -07:00
a08883cf78 cloud: explicit composition root — Wire() replaces the init-registry; order-ints deleted (#248)
Replace the init()-registry (blank imports + cloud.Register(name, order, …) +
magic order-ints) with ONE explicit subsystems.Wire() []cloud.MountSpec. Slice
position IS the mount order — MountAll iterates it as-given, ShutdownAll in reverse.

Core (build.go/serve.go/cmd): delete MountSpec.Order, Register,
RegisterWithShutdown, the HealthOwner option func, and var Registry. MountAll and
ShutdownAll take the []MountSpec slice; Serve threads it in (cloud never imports
subsystems → no cycle). cmd/cloud + cmd/hanzo call subsystems.Wire(). Typed and the
factory hooks (RegisterKMSClientFactory, RegisterCommerceClientFactory,
RegisterOrgScopeResolver, RegisterPushBuilder, RegisterTelemetryInstaller) are
untouched — a different mechanism.

In-repo (~64 clients/*): delete each init() registration; export the mount fn where
unexported (commerce.MountFromDeps, o11y.MountO11y) and the shutdowns. ctxShutdown
bridges the func() error shutdowns in one place.

Externals wired explicitly; the wave-2 tags no longer self-register:
  ai v1.805.2 (@150 catch-all), o11y v1.5.12 (@70 wildcard) — origin/main already
  pins these (genai-span) but did NOT wire them, so main currently DROPS ai + the
  o11y wildcard from its live registry (main's own TestRegistryAssemblesSubsystems
  fails on that). This composition root RESTORES both. authz v1.10.7 (@70),
  licensing v0.1.3 (@110, Mount is already a MountFunc — wired direct), metrics
  v1.110.2 (@40, takes its own metrics.Deps via mountMetrics). vfs unchanged: it
  never registered a subsystem, so it is not wired.

Order is proven by subsystems.TestWireOrderMatchesFrozen against the sequence
captured empirically from origin/main @c504d2b (68 self-registering specs) with ai
+ the o11y wildcard restored at their order-int slots. The Service[state] refactor
reshuffled same-order tie positions on main; the frozen sequence adopts main's new
order (functionally inert — tied subsystems own disjoint route prefixes).

Also fixes a pre-existing clean-main build break (#247): clients/sign/sign.go
referenced an undefined `log` — main does not compile without it, so the whole tree
(subsystems → cmd/cloud) failed to build. One-line fix (log → deps.Logger); flag
for the owner to factor out if preferred.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:42:09 -07:00
b69a926fb1 fix(sign): use deps.Logger for the VFS-nil guard (semantic merge fix, #117) (#249)
#247's VFS-nil health-only guard was authored against the pre-refactor sign.go
(which had a local `log` var); it auto-merged cleanly onto the concurrently-landed
cloud.Service refactor (principal.Org / s.Log) but referenced an undefined `log`,
red-ing the build (clients/sign/sign.go: undefined: log). Point it at deps.Logger
(guaranteed non-nil by the guard above it). No behavior change.

go build ./... + go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud +
go test -race ./clients/{gojabase,captable,sign,dataroom}/... all GREEN.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 15:24:58 -07:00
c504d2bf1e fix(consolidation): gojabase blob seam + sign SEQUENTIAL/off-DB PDFs + cap-table dilution (#117 M5/M7/M8) (#247)
Second wave of RED's consolidation review — the mediums that needed new
hanzoai/captable + hanzoai/sign bundle versions (now merged) plus their cloud-side
wiring and tests.

M5 (captable bundle @119bf9c0) — capTable summed ALL option rows regardless of
  status, so EXERCISED/EXPIRED/CANCELLED grants inflated fullyDilutedShares and
  every ownership %. Fixed to count OUTSTANDING options only. New
  TestDilutiveOptionsExcludeTerminal proves terminal-state grants don't dilute.

M8 — ONE blob seam in gojabase (Config.Blob + a tenant-scoped globalThis.__blob =
  { put(key,b64), get(key) }), keys namespaced {Name}/{TenantSegment} so a bundle
  can only reach its own tenant's objects. sign (bundle @315a3fe6) now routes PDF
  bytes THROUGH it instead of inlining 32 MiB base64 in document_data.data: create
  stores the original blob key, seal writes a sealed key, view/download read via
  __blob.get. The sign leaf passes deps.VFS as the seam (health-only without it).
  document_data holds only the key now (type BLOB_KEY). Same VFS/S3 plane dataroom
  uses — one blob strategy, not two.

M7 (sign bundle @315a3fe6) — SEQUENTIAL signing order was declared but never
  enforced. assertTurn gates signField+signComplete so a later signer can't act
  until every earlier signer has SIGNED. New TestSequentialSigningOrder proves an
  out-of-turn signer is refused (403) and the turn opens once the earlier one signs.

sign tests now inject an in-memory VFS and assert PDF bytes land on the seam
(tenant-scoped key), NOT in the tenant SQLite. All four gate packages pass under
go test -race against the published module versions.

Gate: go build ./... + go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud +
go test -race ./clients/{gojabase,captable,sign,dataroom}/... all GREEN.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 15:19:42 -07:00
hanzo-dev 6a3f6e5a9a Merge feat/genai-span-host-provider: hoist gen_ai host tracer install into cloud.Serve; pin ai v1.805.2 + o11y v1.5.12 2026-07-10 15:10:08 -07:00
hanzo-dev 63ba3d5231 telemetry: bootstrap the host tracer provider inside cloud.Serve — one site, every entrypoint
cloud installs the ONE global tracer provider wired to the o11y in-process trace
sink, but in in-process-sink mode it sets no OTLP/ZAP exporter endpoint. The embedded
hanzoai/ai module then found no endpoint and DISABLED its gen_ai span emit, so the
gen_ai plane in o11y_traces was dark (cloud's own request spans flowed; every LLM
call's gen_ai span was gated off). The provider install + adopt also lived ONLY in
cmd/cloud/main.go, leaving every 'hanzo <svc>' entrypoint (which shares cloud.Serve)
telemetry-dark.

Hoist the bootstrap into cloud.Serve — the ONE serve body cmd/cloud AND every
'hanzo <svc>' share — so both install the provider and adopt it into ai identically,
BEFORE MountAll mounts ai (ai's InitTelemetry reads the adopted-ready flag at mount).
cloud.Serve cannot import clients/o11y (clients/o11y imports cloud -> cycle), so the
concrete bootstrap (SetTracerProvider + aiobject.AdoptHostTracerProvider) lives in
clients/o11y and registers via cloud.RegisterTelemetryInstaller — the same cycle-free
inversion as RegisterKMSClientFactory / RegisterPushBuilder. Serve flushes the
provider on shutdown BEFORE ShutdownAll tears the sink down, so buffered spans drain.

Removes cmd/cloud/telemetry.go (moved to clients/o11y/traceprovider.go). Repins ai to
the branch carrying AdoptHostTracerProvider.

Red review (SHIP): MED-1 — this hoist (both entrypoints adopt identically). Tests:
cloud.installTelemetry dispatch/no-op (telemetry_test.go); clients/o11y
installTraceProvider adopt-latching + OTLP-env-retire + disabled-noop
(traceprovider_test.go).

ai: -> v1.805.1-0.20260710213829-b5eb789d3878 (feat/genai-span-host-provider @ b5eb789d)
2026-07-10 15:09:19 -07:00
hanzo-dev cf04ad92df Merge remote-tracking branch 'origin/main' into wt3/integrate
# Conflicts:
#	clients/affiliates/affiliates.go
#	clients/auditlog/auditlog.go
#	clients/authors/authors.go
#	clients/automations/automations.go
#	clients/automations/mcp.go
#	clients/billing/billing.go
#	clients/billing/finance.go
#	clients/bots/bots.go
#	clients/captable/captable.go
#	clients/dataroom/dataroom.go
#	clients/framework/permission.go
#	clients/functions/billing_test.go
#	clients/functions/functions.go
#	clients/functions/invoke.go
#	clients/functions/metrics.go
#	clients/gateway/gateway.go
#	clients/git/git.go
#	clients/git/mirror.go
#	clients/git/smart_http.go
#	clients/graph/graph.go
#	clients/integrations/integrations.go
#	clients/knowledge/connectors.go
#	clients/knowledge/subsystem.go
#	clients/projects/deploy.go
#	clients/projects/domains.go
#	clients/projects/fork.go
#	clients/projects/projects.go
#	clients/referrals/referrals.go
#	clients/security/security.go
#	clients/tracker/tracker.go
#	clients/treasury/treasury.go
#	clients/visor/fleet.go
#	clients/wallets/wallets.go
2026-07-10 15:03:50 -07:00
hanzo-dev c9ab269d0a Merge remote-tracking branch 'origin/main' into wt3/integrate
# Conflicts:
#	clients/agents/agents_test.go
#	clients/agents/model_validation_test.go
#	clients/agents/scheduler_test.go
#	clients/captable/captable.go
#	clients/crm/applications.go
#	clients/crm/applications_test.go
#	clients/dataroom/dataroom.go
2026-07-10 14:48:11 -07:00
4b389f7a65 cloud: IAM-native vocabulary — org/user/project everywhere, tenant concept removed (TenantDB→OrgDB) (#246)
* cloud: IAM-native vocabulary — org/user/project everywhere, tenant concept removed (TenantDB→OrgDB)

"tenant" was a non-IAM synonym for org. Replace it with the IAM-native nouns
org / user / project / billing account so there is ONE name for the concept.

Root framework primitives (package cloud) — now 100% tenant-free:
  TenantDB                     -> OrgDB            (tenantdb.go -> orgdb.go)
  TenantStore[T]               -> OrgStore[T]
  NewTenantStore               -> NewOrgStore
  tenantDBPath / openTenantDB  -> orgDBPath / openOrgDB
  TenantScopeResolver          -> OrgScopeResolver (tenant_scope.go -> org_scope.go)
  RegisterTenantScopeResolver  -> RegisterOrgScopeResolver
Dropped the legacy X-Tenant-Id / X-Tenant-ID entries from the identity
strip-list (nothing reads them; X-Org-Id is the live header).

Cross-subsystem seams:
  principal.Tenant(c) -> principal.Org(c)  (clients/principal; no collision —
    Project/User kept, already IAM-native). ~50 call sites + ~70 stale doc refs.
  types.TenantConfig -> types.OrgConfig; CommerceClient.GetTenantConfig ->
    GetOrgConfig  (+ commerce client impl, disabled/rpc/entitlements consumers,
    the cloud.OrgConfig alias in deps.go).

Adopters deep-cleaned (identifiers, comments, test names): clients/code, git,
functions, tracker, provisioning, projects. Docs: subsystems.go composition
comments, README.md, and a new LLM.md "Framework doctrine" section.

GATED EXCEPTION (flagged, intentionally unchanged): clients/platform derives
LIVE k8s namespaces, registry image refs, and quota/limit objects from a
"tenant-<org>" string prefix. Renaming it orphans deployed namespaces + built
images, so the literal string is retained behind a // NAMING(gated) note in
clients/platform/k8s.go. The rbac test file + its funcs were renamed
(tenant_rbac_test.go -> org_rbac_test.go).

Out of scope (separate waves; independent domains, touched only for the
principal.Org call-site + stale-ref fix): commerce internal tenant tables
(active commerce-dissolve branch), runner tenantsource, treasury ledger, and
other subsystems' own tenant vocab.

Build: GOWORK=off CGO_ENABLED=0 go build ./... -> exit 0.
Tests: every touched package green. The 38 pre-existing failures (fakeAI
missing Embed; undefined Producer; commerce integration tests; o11y/graph/zt/
kms route-precedence & service tests) fail identically on the base commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* rebase: apply org vocabulary to post-branch main commits (metering/HA/tracing comments); drop unused TenantConfig alias

---------

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 14:45:00 -07:00
hanzo-dev 457aba0ba5 merge: integrate cloud.Service[state] refactor onto origin/main (zip v1.3.0, o11y, renames) 2026-07-10 14:39:39 -07:00
zeekayandClaude Opus 4.8 75b4aa77a0 style(config): gofmt align HA reader/writer fields in LoadConfig
Follow-up to the reader-tier commit — align the CLOUD_WRITER_URL/
CLOUD_READER_RETRY_BUDGET/CLOUD_WRITER_LEASE struct-literal keys with gofmt so
the CI fmt gate is clean. No behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 14:37:32 -07:00
c6ea9ae411 fix(consolidation): tenant-injective per-tenant SQLite + un-stage folds + harden gojabase (#117) (#245)
RED adversarial review of the one-binary consolidation (gojabase + captable/sign/
dataroom folds). Fixes the two ship-blockers plus the in-repo mediums/slop.

C1 (HIGH) — cross-tenant collapse via non-injective filename encoding.
  gojabase.slugify ToLower+folded [^a-z0-9._-]→'_', collapsing DISTINCT owners
  (Acme/acme, "a b"/"a_b") onto ONE per-tenant SQLite file — a cross-tenant break,
  the exact fold principal.Tenant keeps the org verbatim to avoid. Replaced with
  gojabase.TenantSegment: lowercased unpadded base32 of the RAW org bytes —
  INJECTIVE (distinct orgs never share a file) and traversal-safe ([a-z2-7], never
  "."/".."/"/"). Table test proves injectivity (Acme≠acme≠a b≠a_b) + traversal
  containment. IAM owner charset permits case/separator variants, so this was a
  real (not theoretical) collapse. Fresh-tenant-only: the folds pre-date any
  release, so no on-disk data uses the old names — nothing to migrate.

H2 (HIGH) — code==docs on staging. captable/sign/dataroom were un-staged in
  config.go (stagedSubsystems={iam,ingress}) yet every leaf/README claimed
  "STAGED / standalone keeps authority". Evidence (do-sfo3-hanzo-k8s): NO
  standalone captable or dataroom deployment exists; the esign pod runs but its
  SQLite holds ZERO tenant data (User=0, DocumentData=0, Recipient=0, Field=0 —
  only BackgroundJob/RateLimit churn). Decision (a): keep un-staged, delete the
  false comments (captable.go, sign.go, dataroom.go, subsystems.go, README ×2).
  No migration needed (dead/empty apps).

M3  drop dead commercesvc api.Route(/v1/{billing,checkout,store,subscription,
    account}) — unreachable in embed mode (only /v1/commerce/* mounted, no
    rewrite); money path is clients/billing, unaffected. Removed unused import.
M4  gojabase per-tenant *sql.DB cache is now an LRU (cap CLOUD_GOJABASE_MAX_DBS=256)
    with idle eviction (CLOUD_GOJABASE_IDLE_TTL_SEC=300) and dispatch PINNING —
    only idle handles evict, never a DB mid-transaction. Bounds fd/memory for N
    tenants.
M6  dataroom deny_list is now ENFORCED in view.authenticate and WINS over allow
    (checked first); surfaced on linkOut. One shared email matcher (DRY).
M9  sign refuses to boot with a self-signed cert in a production env — requires the
    KMS-custodied CLOUD_SIGN_CERT_PEM/KEY_PEM; dev still self-signs.
M10 added a -race concurrent multi-tenant dispatch test (heavy eviction churn +
    case-variant tenants) proving pool + cache + eviction are race-free and
    isolation holds under concurrency.

Slop/decomplect:
  - goja: a response with no explicit valid status now FAILS CLOSED (default 500,
    rolls the transaction back) instead of committing at a defaulted 200.
  - newID (gojabase) + randKey (dataroom): a crypto/rand failure now returns an
    error / fails the dispatch instead of a predictable time/zero fallback.
  - subsystems.go: removed 6 duplicate blank imports (pubsub, eval, exec, plan,
    plugin, pricing).
  - dataroom: unified on ONE tenant encoding — the object-store key prefix now uses
    gojabase.TenantSegment, matching the SQLite filename (was raw org).

Gate: go build ./... + go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud +
go test -race ./clients/{gojabase,captable,sign,dataroom}/... all GREEN.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 14:35:24 -07:00
hanzo-dev e228849e44 feat(ai): meter EVERY inference at the one chokepoint — no exempt path
The metering decorator (metered_ai.go) wraps deps.AI so every chat + embed
call is authorized against the caller's org balance/budget/freeze BEFORE the
call and debited its billing account AFTER — the single DRY chokepoint through
which no inference runs unattributed. The billing scope (org, project) rides
the request value (ChatRequest/EmbedRequest), so it is compile-time impossible
to call AI without declaring who pays; no bypass, no side-channel key.

Closes the exempt holes — clients/code (index+search+ask), clients/knowledge
(search + index embeds), clients/crm (application screen) — all previously ran
the balance-exempt M2M path unmetered; each now threads org/project to the
chokepoint.

- types.AIClient.Embed takes *EmbedRequest (scope); ChatRequest carries
  Org/Project; ChatResponse surfaces token counts for exact metering.
- httpAI stays pure transport but surfaces resp.Usage tokens and stamps
  hanzo.org/hanzo.project on its gen_ai spans (feeds per-tenant o11y isolation).
- token-based micro-USD debit (CLOUD_AI_PRICE_UUSD_PER_1K, default $2/1M tok);
  metering.Usage gains AmountMicros so a sub-cent call meters exactly instead
  of rounding to zero and slipping through unbilled.
- reuses ResourceMeter over Deps.Metering — same per-org invariants; a
  transparent pass-through when commerce is unconfigured (dev never blocked).
- fixes a latent slice-1 test break (crm/agents AIClient fakes lacked Embed).
- tests: pricing, scope forwarding, system-call, ModelLister preservation.
2026-07-10 14:32:27 -07:00
zeekayandClaude Opus 4.8 de2a97a3bd fix(webui): /metrics is a console page, not an API 404 — drop it from apiPrefixes
The console catch-all 404'd /metrics because it was in apiPrefixes (the Prometheus
scrape-path convention). But the real Prometheus surface is on the SEPARATE ops
listener (:9090, healthMux); on the product API (:8000) /metrics is the console
MetricsModule page. Drop /metrics from apiPrefixes so it falls through to the SPA
shell. One surface per port: :8000 product+SPA, :9090 ops. (ServiceMonitor repointed
to the ops port in the same change.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 14:30:53 -07:00
zeekayandClaude Opus 4.8 54ea87bba4 feat(ha): reader-proxy edge + writer fcntl lease for zero-downtime cloud rolls
The cloud writer embeds an exclusive-lock ZapDB KMS store. A new probe
(clients/kms.TestConcurrentOpen_LiveWriterStoreIsNotROShareable) proves that
opening that store READ-ONLY while the writer is live FAILS ("Log truncate
required to run DB") — Badger's RO open replays the live memtable WAL and
refuses to truncate it. So the prior groundwork's assumption that a reader can
open the KMS store RO off the writer's PVC is false for a LIVE writer (only the
sequential close-then-reopen case worked). The audit SQLite store IS
concurrently shareable (audit/shareability_probe_test.go); the KMS store is the
one that is not, and every mutation is audited on the writer anyway.

Reader tier is therefore a transparent, always-ready reverse proxy (opens no
stores) to the single writer:
 - reader_proxy.go: CLOUD_ROLE=reader boots serveReaderProxy BEFORE BuildDeps —
   forwards every request to CLOUD_WRITER_URL, streams SSE, preserves inbound
   Host. Dial-only retry (retryTransport) absorbs the writer's roll gap: it
   retries ONLY when the connection was never established (no ready endpoint /
   refused), so a non-idempotent POST is never double-executed; bounded by
   CLOUD_READER_RETRY_BUDGET (default 25s) then 502.
 - The reader Deployment rolls RollingUpdate(maxUnavailable:0), so the edge
   Service always has a ready endpoint — this removes the ~30s console blip that
   the writer's Recreate/replicas:1 causes today.

Writer zero-gap roll (opt-in, default OFF = byte-identical Recreate):
 - writer_lease.go (+_unix/_other): CLOUD_WRITER_LEASE takes an exclusive fcntl
   flock on {DataDir}/.writer.lock BEFORE opening the RWO stores and releases it
   LAST at shutdown (after every store closes). A surge writer blocks until the
   old one releases, so the exclusive ZapDB/audit stores are handed off, never
   double-opened. Fail-closed on timeout.

Removes the dead ReaderGuard (the reader no longer runs the full pipeline; it is
the proxy). Unset CLOUD_ROLE + unset CLOUD_WRITER_LEASE ⇒ writer, byte-identical
to today.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 14:12:46 -07:00
hanzo-dev 9cb39adb49 Merge branch 'wt3/F' into wt3/integrate 2026-07-10 14:11:39 -07:00
hanzo-dev fa3b04d5c3 feat(billing): GCP-style billing accounts — funding separate from org
BillingAccount is a funding entity separate from the org: it holds a spend
limit + level + freeze and funds 1..N of the org's projects (dedicated or
shared). A project resolves to its account via ProjectBinding; usage debits
carry Transaction.AccountId so an account's balance and calendar-month spend
sum from the SAME append-only ledger the balance gate + per-scope caps read —
no parallel ledger, no stored total, never drifts.

The authorize verdict layers an account cap + freeze on top of the per-scope
caps (most-restrictive-wins, fail-closed). Resolution is ALWAYS server-side
from the org namespace — the account is never a forgeable client header.
Backward-compatible: (org,"default") folds to the org-wide pool, so an org
with no account behaves byte-for-byte as before.

- models/billingaccount, models/projectbinding (+ hashid kinds 284/285,
  query reserved-kind list)
- Transaction.AccountId indexed ledger axis
- resolveAccountId + accountSpentCents + account cap/freeze in AuthorizeSpendCap
- real account + project-binding CRUD replacing the org-wrapper stubs
- tests: account cap, freeze kill-switch, dedicated-binding isolation,
  backward-compat pool fold
2026-07-10 14:07:31 -07:00
fa01af852b cloud: zip v1.3.0 — zap-proto/fiber engine, route precedence is now a framework guarantee (#244)
zip v1.2.1 -> v1.3.0 rides zap-proto/fiber v3.2.1 (gofiber v3.2.0 + native
ServeMux-1.22 specificity precedence: most-specific wins regardless of
registration order, ambiguous overlaps panic at registration, use/mount stay
declaration-ordered barriers). TestIAMKeysBeatsWildcard now passes as a
FRAMEWORK property — subsystem order-ints are no longer load-bearing for
route precedence (their init-ordering role remains; removal rides the
composition-root refactor). Also swaps the 6 direct gofiber test-file imports
to the fork (production code was already 100% behind zip).

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:44:13 -07:00
hanzo-dev bb663203dc feat(ai): embeddings via the one AIClient — org/project-aligned, no static key
Both semantic subsystems (clients/code, clients/knowledge) embedded via their own
static CLOUD_AI_API_KEY HTTP client — a side-channel credential separate from the
chat path, and the root of vectors:0 (the key was dead + entitlement-gated). Add
Embed() to types.AIClient and route both embedders through deps.AI — the SAME
client chat runs through, which authenticates with the IAM client-credentials
(M2M) token when no static key is set: ONE org/project-aligned identity, one way,
no static key to rotate. Emits gen_ai OTel spans so embeddings are observable end
to end like chat.

This is the ai-module leg of the canonical path
ingress -> gateway -> commerce -> ai module; metering + no-exempt + billing-on land
next on this seam. Supersedes the CLOUD_EMBED_* dedicated-provider detour.

- types.AIClient: + Embed(ctx, model, inputs)
- clients/aihttp: httpAI.Embed (raw POST reusing the static/M2M authed transport)
- clients/disabled, clients/rpc: stub Embed (fail-closed / not-wired)
- clients/code, clients/knowledge: embed through deps.AI; drop the static key path
- knowledge test: exercise the deps.AI seam (inject a deterministic fake embedder)
2026-07-10 13:19:47 -07:00
zeekayandClaude Opus 4.8 bad91f5b75 docs(o11y): reword LLM.md so the one-concept grep stays exact
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:03:21 -07:00
zeekayandClaude Opus 4.8 da1c0f40be refactor(o11y): collapse 5 subsystems -> ONE o11y; flat version-less paths (#71)
Decomplect the observability estate to exactly ONE top-level concept.

## 5 -> 1 registration collapse
The plane was FIVE separately-registered subsystems (o11yscope 69,
o11y-runtime 71, o11y-event-ingest 68, o11y-otlp-ingest 72,
o11y-trace-inproc 73) whose names leaked five public concepts (five config
toggles + five /v1/<name>/health routes). The k8s-style ordering was an
internal impl detail. They collapse to ONE
`cloud.RegisterWithShutdown("o11y", 69, mountO11y, shutdownO11y, HealthOwner)`:
mountO11y performs the ordered sub-mounts in-process (mountEventIngest ->
mountScope -> mountRuntime -> mountIngest -> mountTraceSink), so the PUBLIC
concept is a single `o11y`. Behavior is preserved EXACTLY — every specific
/v1/o11y/* route still registers inside the one order-69 mount, hence BEFORE
the upstream hanzoai/o11y wildcard (order 70), so Fiber's in-order match still
gives the specific routes precedence. The upstream module co-owns the `o11y`
name at order 70 (the wildcard); HealthOwner on this entry keeps /v1/o11y/health
registered exactly once (never a duplicate).

## Flat, version-less public surface (one /v1/, no nested /api/vN)
The upstream SigNoz engine version is an internal impl detail resolved inside
the handlers, never leaked into a route:
- /v1/o11y/vm/{query,query_range} (was /v1/o11y/vm/api/v1/*) — VM proxy; the
  upstream VM api/v1/* path stays INSIDE the handler (queryRaw). SuperAdmin
  gate + {up,sum(up),count(up)} allowlist unchanged.
- /v1/o11y/{query,query_range} (new, query.go) — the flat builder query;
  resolves to the v3 engine route SERVER-SIDE (the version-less alias would
  float to v5, which 400s the console's v3 composite payload), delegating to
  the same gated runtime handler the wildcard uses.

o11y stays EMBEDDED in-process (the everything-binary); OTLP ingest + trace
sink stay opt-in. Registers exactly one `o11y` in clients (grep-verified),
alongside analytics/evals/usage/audit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:02:28 -07:00
a3ea6191c7 cloud: dissolve commercesvc → commerce.Client (fold-finisher + decomplect) (#242)
Absorb the thin clients/commercesvc mount wrapper AND the fail-closed
clients/commerce_local.go stub into the in-tree commerce library, and expose
a real in-process commerce.Client — one package now owns the commerce library,
its /v1/commerce subsystem, and its cloud.CommerceClient, self-registered via
cloud's inversion hooks (the clients/kms pattern; cf. #241 gatewaysvc→gateway).
cloud never imports commerce, so there is no cloud⇄commerce import cycle.

commerce.Client (client.go): a real in-process types.CommerceClient. The former
stub failed CLOSED on every CheckEntitlement (the Phase-2 gap). It now resolves
org→active-subscription→plan-tier→license-features from commerce's OWN models +
the @hanzo/plans vocabulary:

  - org → namespace via commerce's canonical org.Resolve (the same binding the
    money path uses), so a read can never cross tenants;
  - active, unexpired subscriptions via a plain Status filter (matches commerce's
    own read idiom, so grant- and payment-created subs are both found);
  - plan tier → flat license features via a new plan.LicenseEntitlement seam that
    runs @hanzo/plans' toLicenseFeatures (the vocabulary stays in one place, not
    re-implemented in Go);
  - Active iff the plan's features carry "licensing.product:<id>".

MONEY-SAFETY: Active:true only for a real active sub whose real plan really
licenses the product. Every unresolvable piece (commerce not co-resident, org
unresolvable, subscription query error, plans vocabulary unavailable) returns an
ERROR → the entitlements gate treats it as "cannot verify ⇒ 503"; a clean
"no plan licenses this product" is Active:false (→ 402), never an error and never
a fabricated grant.

Decomplect: commerce.Mount takes a MountConfig VALUE (Brand/Env/DataDir/Domain)
+ a logger — the values it uses, not the whole cloud.Deps bag; mountFromDeps is
the one place Deps is narrowed and carries the PCI Payments/Vault warnings.

Network path preserved: pickCommerceClient still selects the ZAP-RPC/disabled
client when commerce is NOT enabled in-process (CLOUD_COMMERCE_ZAP_ADDR). This
fold does NOT force the live in-process cutover — that stays operator-gated.

Deleted: clients/commercesvc, clients/commerce_local.go(+test), the legacy
//go:build cloud clients/commerce/mount.go(+ its two tests), and the redundant
cmd/commerce --cloud boot path (cloud_boot.go/cloud_stub.go) — one way to serve
commerce inside cloud: the folded subsystem.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 13:02:00 -07:00
zeekayandClaude Opus 4.8 57ef4a41ac test(audit): prove store shareable by RO reader under live writer (HA carve)
Concurrent RO opener reads all records while the serialized writer appends;
writer chain stays intact and a fresh RW re-open recovers the head with no
fork/gap. Audit-store analog of clients/kms TestReaderReadOnlyRoundTrip.
Locks in the reader/writer shareability invariant the cloud HA carve depends
on. Test-only; zero runtime change (writer path byte-identical).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 12:54:13 -07:00
hanzo-dev afaa80b7df fix(embed): dedicated CLOUD_EMBED_* provider — unbraid embeddings from chat
The code + knowledge embedders read CLOUD_AI_BASE_URL/CLOUD_AI_API_KEY,
which are ALSO the chat/synth AIClient's config (config.go:308). That
braided embeddings onto the IAM-gated api.hanzo.ai path, whose /embeddings
403s customer keys and 401s gateway keys — only a superadmin JWT passes —
so the vector tier indexed vectors:0 platform-wide.

Split embeddings onto dedicated CLOUD_EMBED_BASE_URL / CLOUD_EMBED_API_KEY /
CLOUD_EMBED_MODEL, each falling back to the shared CLOUD_AI_* for back-compat.
Both semantic subsystems (clients/code + clients/knowledge) read the same
three vars — one embed config, orthogonal to chat. Deployment points them at
DigitalOcean GenAI (bge-m3 @1024-dim, first-party, not IAM-gated) via the
DO_AI_API_KEY already in cloud-api-llm-keys; chat stays on CLOUD_AI_*.
2026-07-10 12:09:15 -07:00
hanzo-dev 52a1a12603 fix(platform): preserve a kept secret on empty setEnv (never wipe KMS)
Secrets are write-only: toAppView masks a secret value to "" on read, so a client
editing env re-submits kept secrets with an empty value. sealSecretEnv now treats an
empty secret value as "keep the already-sealed value" — it is preserved, not resealed
to empty (which wiped the KMS secret). Only a non-empty value seals (and requires KMS).
Makes the masked-read -> setEnv round-trip a no-op for untouched secrets instead of a
data-loss footgun; unblocks the console env editor's Keep path. Adds a focused test.
2026-07-10 11:55:55 -07:00
1e4911994a cloud: drop svc suffix — clients/gatewaysvc → clients/gateway (#241)
The gateway subsystem package carried an "svc" suffix as a naming habit
only: there is no clients/gateway to collide with, and the package imports
no "gateway" library, so it renames cleanly to the plain domain name.

- git mv clients/gatewaysvc → clients/gateway (history preserved)
- gatewaysvc.go / gatewaysvc_test.go → gateway.go / gateway_test.go
- package gatewaysvc → package gateway; Mount() error strings + doc comment
  updated to gateway.*
- update the blank import in subsystems/subsystems.go and the doc comments
  in deps.go, middleware_edge.go, clients/gatewaypolicy/policy.go

commercesvc is intentionally NOT renamed in this PR. clients/commerce
already exists in-tree — the embedded upstream Hanzo Commerce library
absorbed by #114 (package commerce, ~1583 files) — and commercesvc.go
imports it as github.com/hanzoai/cloud/clients/commerce. Moving
clients/commercesvc → clients/commerce is therefore a directory-level
collision, not an import-alias shadow; re-aliasing does not free the path.
Renaming commerce cleanly needs the operator to decide the target name (or
relocate the embedded library), so it is flagged for follow-up, not forced.

Build: GOWORK=off CGO_ENABLED=0 go build ./...  → exit 0
Test:  GOWORK=off CGO_ENABLED=0 go test ./clients/gateway/... \
         ./clients/gatewaypolicy/... .           → ok

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:52:55 -07:00
hanzo-dev b02d0bb57b fix(platform): wire kmsIdentity (secret env) + mount platform,git in deploy enable list 2026-07-10 11:48:42 -07:00
zeekayandClaude Opus 4.8 9a5f0b9413 feat(o11y): SuperAdmin VM read proxy for the console infra-health board (#71)
The console's /metrics and /status SuperAdmin infra-health board read
VictoriaMetrics `up{}` via the console's Next.js `/telemetry/[...path]` route.
That server route is STRIPPED by the static-export embed (cloud go:embeds
console as output:'export'), so the browser call 404s — the last console error.

Add a same-origin, SuperAdmin-gated VM read proxy on the cloud `/v1` API that
serves the exact three queries the board issues, registered at o11yscope order
69 (before the o11y wildcard at 70):

  GET /v1/o11y/vm/api/v1/query?query=up
  GET /v1/o11y/vm/api/v1/query_range?query=sum(up)|count(up)&start&end&step

Security follows scope.go's contract ("the client never supplies a raw query"):
  - admin(c) gate (X-User-IsAdmin, reserved admin org) — 403 for everyone else.
  - The ?query param is ALLOWLISTED to exactly {up, sum(up), count(up)}; anything
    else is 400. Range args (start/end/step) validated as positive integers. No
    generic PromQL passthrough — this can never become an exfiltration/DoS surface.
  - VM's native Prometheus envelope is returned VERBATIM (c.Bytes) so the console's
    parseInstant/parseRange work unchanged. Reuses the existing newVMClient()
    (O11Y_VM_URL); adds vmClient.queryRaw for the verbatim forward.

Pairs with console 1beb6fca9 (telemetry.ts repoint). Verified: go build + go vet
clean on clients/o11y.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:47:37 -07:00
zandGitHub ab32a6bd3c Merge pull request #240 from hanzoai/feat/114-absorb-commerce-source
feat(#114): absorb commerce source in-tree (clients/commerce) — one module, one binary
2026-07-10 11:32:50 -07:00
hanzo-dev 1a02b256d6 feat(#111): billing money-path in-process — retire the standalone commerce hop
Every co-resident subsystem that spoke the commerce billing S2S surface over HTTP
to the standalone pod (commerce.hanzo.svc:8001) now dispatches straight into the
in-tree commerce handler (#114) — no socket, no serialization change. This is what
lets the standalone be retired.

- New seam clients/commerceinproc: commercesvc.Mount publishes the embedded
  commerce http.Handler (now carrying /v1/billing via api.Route) once at boot; a
  self-routing http.RoundTripper dispatches each S2S request to it in-process when
  co-resident, else falls back to plain HTTP (the pre-#111 split-deploy behavior).
  Behaviour-preserving: same path, same Bearer+X-Org-Id headers, same body/status
  bytes either way — proven by commerceinproc_test (in-process dispatch, HTTP
  fallback, base resolution).
- Converted: clients/{billing,account,admin,referrals,authors,affiliates,usage} —
  each keeps its OWN request-building + tenant subject-pinning (the security
  boundary is untouched); only the transport swaps. account keeps its shared
  httpClient for HUSD EVM JSON-RPC and routes ONLY commerce calls in-process.
- The request-edge METERING gate (build.go buildMeteringClient) debits the
  in-process handler; base pinned non-empty when co-resident so the gate never
  silently no-ops (free-money hole) even after CLOUD_COMMERCE_HTTP_URL is dropped.

GATES: go build ./... + cmd/cloud (sqlite tags) green; commerceinproc + all 8
converted packages' tests pass. LIVE money-parity gate (in-process vs standalone
balance/deposit/usage on shared Postgres + metering debits) precedes retiring the
standalone — that live cutover is gated, not in this commit.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ
2026-07-10 11:29:07 -07:00
hanzo-dev 1b42cea706 feat(#114): absorb commerce source in-tree (clients/commerce) — one module, one binary
Move hanzoai/commerce out of the external-dep seam and INTO the cloud module,
so /v1/commerce (and, next, /v1/billing) is served by one repo, one binary, one
way. No external github.com/hanzoai/commerce* require remains.

Absorbed the EXACT versions cloud already compiled (behavior-preserving — not
main), copied from the module cache so the in-tree tree == what the live binary
built:
  - github.com/hanzoai/commerce            v1.46.40  -> clients/commerce
  - github.com/hanzoai/commerce/metering   v0.1.4    -> clients/commerce/metering
  - github.com/hanzoai/commerce/thirdparty/ethereum v1.40.0 -> clients/commerce/thirdparty/ethereum

- ONE Go module: removed the three nested go.mod/go.sum; commerce's deps merged
  into cloud/go.mod via `go mod tidy` (MVS keeps the highest existing patch — the
  single major conflict, luxfi/zap, already resolved to cloud's v1.2.1 in the old
  build, so nothing recompiles differently). New direct deps discovered by tidy:
  huandu/facebook, square-go-sdk/v3.
- Imports rewritten repo-wide: github.com/hanzoai/commerce* ->
  github.com/hanzoai/cloud/clients/commerce* (1103 files: the absorbed tree +
  cloud's own build.go/deps.go/middleware_billing.go/clients/{bots,functions}/…
  metering importers). commercesvc leaf now imports the in-tree package.
- Excluded the app/ frontend pnpm workspace (59M, NOT referenced by any .go —
  the built ui/dist + billing/ui/dist + checkout/ui/dist that Go //go:embed's are
  kept). //go:build cloud files kept (excluded from the plain build as before).

GATES (all green):
  go build ./...                                   -> ok
  go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud -> ok (633MB binary boots)
  go test ./clients/commercesvc/... ./clients/commerce/{,datastore,api/billing}  -> ok
  go test -run 'Billing|Metering|SpendCap|Commerce' .  -> ok

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ
2026-07-10 11:13:14 -07:00
hanzo-dev e80e02e6ce Merge branches 'wt3/B' and 'wt3/C' into wt3/integrate 2026-07-10 11:11:22 -07:00
hanzo-dev e7a6908277 refactor(admin): adopt cloud.Service[state], drop per-package svc 2026-07-10 11:09:43 -07:00
hanzo-dev 32897c3c87 refactor(ml): adopt cloud.Service[state], drop per-package svc 2026-07-10 11:08:54 -07:00
hanzo-dev cefda54f63 refactor(affiliates): adopt cloud.Service[state], drop per-package svc 2026-07-10 11:06:59 -07:00
hanzo-dev fa1d77ba88 refactor(do): adopt cloud.Service[state], drop per-package svc 2026-07-10 11:03:59 -07:00
hanzo-dev 1940aaff4c Merge branch 'main' into wt3/integrate 2026-07-10 11:03:17 -07:00
hanzo-dev 89f477fd30 refactor(tracker): adopt cloud.Service[state], drop per-package svc 2026-07-10 11:00:06 -07:00
hanzo-dev c9c2e1fec1 Merge branch 'wt3/G' 2026-07-10 10:59:09 -07:00
hanzo-dev d300b53f45 Merge branch 'wt3/D' 2026-07-10 10:59:01 -07:00
hanzo-dev 21dc2361e9 refactor(treasury): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:58:36 -07:00
hanzo-dev 071926a2b7 Merge branch 'wt3/E' 2026-07-10 10:58:23 -07:00
hanzo-dev 744b13e24a refactor(framework): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:58:04 -07:00
hanzo-dev 13194d82ec refactor(paas): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:57:45 -07:00
hanzo-dev ca96336306 refactor(automations): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:57:01 -07:00
hanzo-dev 12c1cc79b5 Merge branch 'wt3/H' 2026-07-10 10:56:11 -07:00
hanzo-dev 84902731cc refactor(wallets): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:56:03 -07:00
hanzo-dev c077987ac3 refactor(platform): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:55:07 -07:00
hanzo-dev 8b5b06e7a4 refactor(ingress): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:54:49 -07:00
hanzo-dev 031215db55 Merge branch 'wt3/A' 2026-07-10 10:54:04 -07:00
hanzo-dev 48c6844885 refactor(crm): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:53:35 -07:00
hanzo-dev 803674be73 refactor(storage): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:52:53 -07:00
hanzo-dev 2926c96089 refactor(agents): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:52:40 -07:00
hanzo-dev 40b8829150 refactor(sbom): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:51:55 -07:00
hanzo-dev 60c7a24fb6 refactor(dataroom): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:49:35 -07:00
hanzo-dev 0b942d229d refactor(git): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:49:27 -07:00
hanzo-dev b0ed00e295 refactor(sign): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:48:48 -07:00
hanzo-dev 4806aea5c2 refactor(projects): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:48:43 -07:00
hanzo-dev f7c84bd248 refactor(integrations): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:47:19 -07:00
hanzo-dev 3eff525605 refactor(authors): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:46:54 -07:00
hanzo-dev 664fe2b98d refactor(graph): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:46:37 -07:00
hanzo-dev c61474b41f refactor(kms): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:46:22 -07:00
hanzo-dev 38ac821553 refactor(functions): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:46:02 -07:00
hanzo-dev 3231a26323 refactor(provisioning): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:45:26 -07:00
hanzo-dev 4fb877a0c0 refactor(account): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:43:16 -07:00
hanzo-dev 4f2eb3ada0 refactor(analytics): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:42:02 -07:00
hanzo-dev 87e6134657 refactor(zt): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:40:59 -07:00
hanzo-dev 3090d0afb9 refactor(visor): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:39:47 -07:00
hanzo-dev ba41ae165b refactor(referrals): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:39:41 -07:00
hanzo-dev f84532f617 refactor(captable): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:39:40 -07:00
29103f8183 fix(deps): pin hanzoai/beego/v2 to tag v2.4.1 (kill controlplane-containment shallow-clone flake) (#239)
cloud pinned beego at a PSEUDO-VERSION
(v2.4.1-0.20260710093857-0ad99bdf8b90). A pseudo-version forces `go` to
resolve the dep via a live VCS fetch-by-commit-hash into the shared ARC
GOMODCACHE cache/vcs. Parallel containment jobs racing that shallow bare
repo hit `fatal: shallow file has changed since we read it` → intermittent
FAIL, which has forced admin/green-locally squash-merges (#235, #236) and
defeated the containment gate.

beego HEAD (0ad99bdf) is exactly one benign commit past tag v2.4.0 (silences
a missing-default-app.conf stderr warning, beego#29). Cut that commit as a
proper patch tag v2.4.1 and pin to it — byte-identical code, but `go` now
fetches the immutable refs/tags/v2.4.1 ref instead of shallow-fetching a
bare commit, so no cache/vcs race. beego is private (no module-proxy), but
the tag ref path is deterministic and does not trip the shallow-file check.

go.sum regenerated via `go mod tidy` (authentic v2.4.1 hash). `go build ./...`
green. iam stays on tag v2.3.10 (already a tag, not a pseudo-version).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 10:39:12 -07:00
hanzo-dev 83236e4e33 telemetry: declare the host tracer provider to embedded ai (gen_ai spans -> o11y)
cloud installs the ONE global tracer provider wired to the o11y in-process trace
sink, but in in-process-sink mode it sets no OTLP/ZAP exporter endpoint. The
embedded hanzoai/ai module then found no endpoint and DISABLED its gen_ai span
emit, so the gen_ai plane in o11y_traces was dark (cloud's own request spans
flowed; every LLM call's gen_ai span was gated off).

After otel.SetTracerProvider, call aiobject.AdoptHostTracerProvider() so ai emits
every gen_ai span through THIS provider -> the o11y in-process sink -> o11y_traces.
Repins ai to the branch carrying AdoptHostTracerProvider. The OTLP-env unset stays
as orthogonal defense against any other lib forking a competing provider.

ai: github.com/hanzoai/ai v1.804.1 -> v1.804.2-0.20260710172916-723e03f81bca
2026-07-10 10:38:51 -07:00
hanzo-dev 3348a40291 refactor(billing): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:37:09 -07:00
hanzo-dev d202d9eca6 refactor(bots): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:36:03 -07:00
hanzo-dev 0e9d128981 refactor(security): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:35:49 -07:00
hanzo-dev fc676221a2 refactor(team): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:35:49 -07:00
hanzo-dev 021c9c859c refactor(knowledge): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:35:00 -07:00
hanzo-dev 96bfba297e refactor(prompts): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:33:58 -07:00
hanzo-dev 9b6922bc9a refactor(templates): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:33:18 -07:00
hanzo-dev 0d68513933 refactor(gatewaysvc): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:32:10 -07:00
hanzo-dev 3669f1d78d refactor(auditlog): adopt cloud.Service[state], drop per-package svc 2026-07-10 10:31:20 -07:00
hanzo-dev ecd3930029 feat(cloud): export cloud.NewBase for complex-Mount subsystems
Simple subsystems use one-line cloud.Mount[S]. Subsystems whose Mount is more
than build+routes (background reconciler, package-global for cross-package hooks,
shutdown cancel — e.g. platform) construct the Service value directly with
cloud.NewBase + &cloud.Service[state]{...} and wire routes via Handle — still the
ONE generic type, one Base derivation.
2026-07-10 10:25:53 -07:00
hanzo-dev c859906d6b feat(cloud): one generic subsystem type — cloud.Service[S], kill per-package svc
The ONE server abstraction: a subsystem is cloud.Base (shared deps derived once:
Log/KMS/Bill/Brand/Env/Domain/DataDir) + its own typed State. Handlers are FREE
FUNCTIONS func(*Service[S], *zip.Ctx) error bound with cloud.Handle — so a package
declares NO service/receiver type, only its State (plain data) and its handlers.
cloud.Mount[S] is the one generic entrypoint (build state, wire routes).

Pike minimalism: generics carry the state type, functions carry behaviour. Kills
the 'type svc struct{ …re-plumbed deps… }' shape copied ~40×.

Proven on clients/usage: svc type gone, log via embedded Base (s.Log), commerce
reader in State (s.State.commerce), all handlers/helpers free functions. Build +
vet + test green, routes + tenant isolation unchanged.
2026-07-10 10:25:53 -07:00
3a4cdc5dd4 feat(#105): un-stage commerce (in-binary /v1/commerce) — DRAFT, gated on cutover prep (#237)
* feat(#105): un-stage commerce — serve /v1/commerce in-process from the one binary

Phase 2 final step (tasks #96#105). commerce was the last staged
in-process subsystem; drop it from stagedSubsystems so the mount-all default
serves /v1/commerce (+ /_/commerce) from the cloud binary instead of proxying
to the standalone commerce pod. iam + ingress STAY staged (the IAM embed
corrupts its own Beego bootstrap under mount-all).

commerce owns the money path, so the cutover is data-neutral BY CONSTRUCTION:
the authoritative stores stay put and shared — balances/deposits/credits live
in Hanzo SQL (SQL_URL), analytics in DATASTORE_URL, blobs in S3 — and the
in-process commerce.Embed reads the SAME stores via the SAME backend env the
standalone CR carried. Only the small per-org merchant SQLite + tenant `base`
tree migrate into the cloud data dir. No money is copied or split.

Tests: go test -run TestEnabled ./  → ok (staged contract: commerce now mounts
under the empty-Enable default; iam/ingress still gated to explicit CLOUD_ENABLE).

Also gofmt: fixes a pre-existing struct-literal misalignment in LoadConfig.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

* fix(commercesvc): isolate in-process commerce data under {DataDir}/commerce

In-process commerce writes orgs/ and base/ under its DataDir. cloud sets
deps.DataDir=/var/lib/cloud, where cloud ALSO owns /var/lib/cloud/orgs (its
own per-org subsystem SQLite, HIP-0302) and /var/lib/cloud/base (its Base/IAM
store) — verified live. Sharing the root would open two apps on the same
SQLite files (base/data.db) and corrupt them. Always nest commerce under
{deps.DataDir}/commerce (was only the empty-DataDir fallback), keeping the
commerce ledgers physically separate on the same cloud-api-data PVC. This is
the target path the #105 data migration copies the per-org merchant SQLite +
tenant base into.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 10:05:20 -07:00
hanzo-dev 716c54303b Merge branch 'wt2/preview' 2026-07-10 10:01:28 -07:00
hanzo-dev a812c47a2a Merge branches 'wt2/bots' and 'wt2/gateway' 2026-07-10 10:01:11 -07:00
hanzo-dev 915836e1cf cloud(platform): preview deployments + promote + rollback 2026-07-10 10:00:38 -07:00
hanzo-dev 992ce799ad cloud(gateway): per-org edge config — cache TTL + CORS + rate, org-scoped round-trip 2026-07-10 09:59:20 -07:00
hanzo-dev 1e2d66c6c4 cloud(bots): POST /v1/bots/run — launch a computer-using agent, return VNC session 2026-07-10 09:56:41 -07:00
hanzo-dev 2b4fac2199 feat(git): mirror external repos into the embedded git server + self-host cloud's own repo 2026-07-10 09:50:22 -07:00
hanzo-dev fba4ff77f8 feat(platform): native release semantics on /v1/runner (retires release.yml build/tag/notify) 2026-07-10 09:48:41 -07:00
hanzo-devandGitHub ff8dec31c5 fix(code): normalize embedder base to /v1 — deployed CLOUD_AI_BASE_URL lacks /v1, so /v1/code semantic tier posted to /embeddings (405) → vectors:0. Append /v1 when absent; ask/RAG now works. (#238) 2026-07-10 09:46:47 -07:00
hanzo-devandGitHub b5a534ca38 fix(code): normalize embedder base to /v1 — deployed CLOUD_AI_BASE_URL lacks /v1, so /v1/code semantic tier posted to /embeddings (405) → vectors:0. Append /v1 when absent; ask/RAG now works. (#238) 2026-07-10 09:46:21 -07:00
a3e7ceaf51 feat(sbom): registry pull-on-miss — materialize attached SBOMs into ClickHouse (#77) (#236)
The consumer half of the SBOM datastore lane. The registry is the source of
truth: CI produces the CycloneDX SBOM and `cosign attach`es it to the image
digest. Cloud now PULLS that attached artifact and materializes its components
into the global hanzo.sbom_component table — no CI push-ingest.

clients/sbom/pull.go (new): registry pull with go-containerregistry (pure-Go,
no binary deps). Resolves ref→digest, locates the CycloneDX SBOM by the cosign
SBOM tag (sha256-<hex>.sbom) first, OCI 1.1 referrers second, and parses it
through the SAME parseComponents the POST /v1/sbom path uses (one flattener).

Triggers:
- Pull-on-miss: GET /v1/sbom/{ref} with 0 rows and an image ref pulls the
  attached SBOM, upserts it, and rereads FINAL — the console goes live with no
  console change (the panel already GETs by repository:tag).
- Deploy-time: platform applyLive fires sbom.Prefetch(ref) async when a
  deployment goes live (best-effort, idempotent; platform→sbom, one direction).

go.mod: + github.com/google/go-containerregistry v0.21.7 (direct), authentic
go.sum via go mod tidy.

Tests: hermetic end-to-end over a real in-memory OCI registry (cosign tag +
OCI referrers + no-attachment + bare-digest), all green with -race. Plus an
env-gated live end-to-end (pull_live_test.go) proven against registry:2 + real
ClickHouse serving a real cyclonedx-gomod SBOM: GET → pull-on-miss → production
pullSBOM → parse → INSERT → reread → 200 with the real components + cache hit.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 09:34:28 -07:00
hanzo-dev 6ffe57f3ab feat(platform,git): git-push-to-deploy — a push triggers a native build
A push landed on the embedded git server (clients/git) now fires a build
for every app that tracks that repo+branch — no GitHub, no Actions.

- build.go: GitPushEvent + RegisterPushBuilder/OnGitPush — the same
  package-level inversion as kmsClientFactory, so git never imports
  platform and there is no git<->platform cycle.
- clients/git/smart_http.go: after a push lands (post-metering),
  firePushBuilds fires OnGitPush for each branch ref that advanced
  (tags + deletes skipped). Best-effort: a trigger failure is logged,
  never fails the push the client already committed.
- clients/platform/push.go: buildFromPush resolves every git-source app
  whose RepoURL+branch matches the pushed ref and launches a build via
  the ONE shared build-launch core.
- clients/platform/deploy.go: extract startGitBuild (ctx-only) as that
  single core; deployGit maps it onto the HTTP deploy, buildFromPush onto
  the push trigger — one build-launch path, no duplication.
- clients/platform/validate.go: the cloud's own embedded-git apex
  (deps.Domain) is always a trusted build source, so a self-hosted-git
  app builds with no env — host all repos on our own git, not GitHub.

Tests: TestPushFiresBuildTrigger (real go-git push -> OnGitPush fires with
org/repo/branch/commit/cloneURL), TestBuildFromPush_{LaunchesMatchingApp,
NoMatchIsNoop,IgnoresImageApp}. Full platform + git suites green.
2026-07-10 09:26:32 -07:00
zandGitHub ddcec83364 fix(team): remap migrated-workspace socialId to deterministic person on connect (#235)
Jul-5 team-go→cloud migrated workspaces threw "Confirmed social identity is attached to the wrong person" on transactor connect: the confirmed hanzo:<account> SocialIdentity was still attached to a team-go-era Person id, not the deterministic person-<account>. reconcile() now runs remapMigratedSocialIds(uid) to re-point it — migrated-only, idempotent, non-destructive. CI red check (controlplane-containment) is an unrelated shared-runner Go module-cache flake on hanzoai/beego; fix is clients/team-only and green locally (go build ./..., make build, go test/-race/vet/gofmt).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ
2026-07-10 09:25:49 -07:00
zeekayandClaude Opus 4.8 e7eaf2f57c fix(o11y): edge-trusted local authz in the embed (o11y v1.5.10)
Set O11Y_AUTHZ_PROVIDER=local so the in-process o11y authorizes org-scoped,
gateway-authenticated users locally instead of round-tripping to an external IAM
Casbin enforcer the one-binary has no credentials for. That round-trip was 401ing
every /v1/o11y read (provision Grant -> add-policy authz_unavailable), breaking the
console overview-metrics widgets on ~9 secondary product pages. Same enforced
policy; tuples in-process. Bumps o11y 1.5.9 -> 1.5.10.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:49:11 -07:00
zeekay 391a19bc58 deps: bump hanzoai/o11y v1.5.8 -> v1.5.9 (surface swallowed IdentN errors — diagnose o11y read 401) 2026-07-10 08:25:36 -07:00
zeekayandClaude Opus 4.8 e81e2ed8e2 deps: bump hanzoai/o11y v1.5.7 -> v1.5.8 (role-selector digits — fix o11y-admin grant panic)
v1.5.8 allows digits in TypeRole selectors, unbreaking the built-in o11y-admin role
grant that panicked (→500) on EVERY authenticated embedded o11y data read. Completes
the o11y-telemetry fix (v1.5.6 aliases + v1.5.7 /api passthrough + v1.5.8 grant):
/v1/o11y/{query_range,services,rules,dashboards} now resolve for the console
overview-metrics widgets.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 06:24:50 -07:00
zeekayandClaude Opus 4.8 997062d8f7 deps: bump hanzoai/o11y v1.5.6 -> v1.5.7 (embedded /api/* passthrough — fix o11y data 404s)
v1.5.7 routes /api/*-prefixed paths straight to the router in the ExternalPath wrapper,
fixing the double-strip that 404'd EVERY embedded o11y data call. With v1.5.6's
version-less aliases, /v1/o11y/{query_range,services,rules,dashboards}+/metrics now
resolve — fixes the console overview-metrics widgets on studio/gateway/cli/registry/
desktop/console/dashboards/alerts/metrics.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 05:26:55 -07:00
zeekayandClaude Opus 4.8 2e4161d7d1 deps: bump hanzoai/o11y v1.5.5 -> v1.5.6 (version-less /v1/o11y/<resource> aliases)
v1.5.6 registers the version-less /api/<resource> aliases on the app.Server router
the embedded runtime uses (o11y e01015954), so the console's /v1/o11y/{query_range,
services,rules,dashboards} + /metrics resolve instead of 404 — fixes the o11y-telemetry
overview widgets on studio/gateway/cli/registry/desktop/console/dashboards/alerts/metrics.
Also folds in the v1.5.5 C1 cross-tenant llmobs read fix.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 04:37:05 -07:00
827c3e970f config: keep commerce staged (money-path data migration required first) (#234)
captable/sign/dataroom stay un-staged — their standalone stacks held no live
data. commerce owns real transactional data + the money path (commerce-api /
pay / webhooks + credit-deposit flow); un-staging split-brains /v1/commerce onto
a fresh in-process dataset. Proxy the authoritative standalone until commerce's
in-binary cutover (data migration + money-path repoint + cron) is done properly.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 04:21:35 -07:00
zeekayandClaude Opus 4.8 b0ac625080 fix(zt): networks/edge READS return empty-200 when ZT unconfigured (not gate 503)
The prior fix degraded the orgRouters-error path, but zt's gate() fail-closes with
503 BEFORE that when ZT_CLIENT_ID/SECRET are unset — so /networks + /edge still 503'd
a console error on every load. Short-circuit the two READ handlers to an honest-EMPTY
list (200) when unconfigured, ahead of the gate. WRITES keep the fail-closed 503.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 03:57:05 -07:00
2e9c6badd8 fix(hanzo): control-plane verbs emit no server-init noise (#231)
Every `hanzo` control command (version, whoami, config, apps, login, …) printed
three lines of server-mode init chatter first:

  init global config instance failed ... open conf/app.conf: no such file...
  failed to load persistent registry signing key: KMS_SERVICE_TOKEN ... required
  generating ephemeral registry signing key for non-production runtime

These come from dependency package init() functions that run before main(), so
main.go's client-vs-server branch cannot gate them, and Go's alphabetical
package-init order (beego < cloud < iam) means no cloud-side os.Stderr swap can
pre-empt them — verified with an init-order probe. Masking the output would also
leave a wasteful KMS fetch + RSA keygen firing on every CLI call. Fixed at the
source instead:

  - hanzoai/iam#117: registry signing key resolved lazily (sync.Once) at its use
    sites, not in package init(); server token paths keep identical semantics,
    the CLI never touches KMS or generates a key.
  - hanzoai/beego#29: the benign conf/app.conf probe is silent when the default
    file is absent (the CLI case), loud only on a present-but-broken file.

Bump both deps to the fixed versions and document the quiet-output invariant at
the CLIENT MODE gate in cmd/hanzo/main.go.

Result: `hanzo version|whoami|config path|apps --help` emit ZERO stderr; server
subcommands (`hanzo ai --help`, serves) initialize unchanged.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 03:42:39 -07:00
7d05abd4b0 config: phase-2 flip — un-stage commerce/captable/sign/dataroom (serve from the one binary) (#232)
All four are folded in-process and validated on cloud-unified-canary
(v1.786.167): commerce embedded, captable/sign/dataroom "mounted in-process
(goja + per-tenant Base)", /v1/{commerce,captable,sign,dataroom}/health all 200.
Dropping them from stagedSubsystems makes the mount-all default serve them, so
the main cloud (empty CLOUD_ENABLE) runs them natively and their standalone
Postgres/Next pods retire. iam + ingress stay staged (IAM embed corrupts its own
bootstrap under mount-all; iam served by the standalone pod).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 03:38:19 -07:00
zeekayandClaude Opus 4.8 5a04f0d135 fix(graph,zt): degrade indexer/oracle/network/edge reads to honest-empty (no 502/503 page errors)
console.hanzo.ai /indexer, /oracles, /networks, /edge fired 502/503 console errors
because these list handlers returned the upstream error when the chain indexer /
price-feed oracle / ZT controller is unreachable or unconfigured (ZT_CLIENT_ID
optional). Same graceful fold already shipped for visor clusters/machines/gpus:
log + return an honest-EMPTY list (200). An empty list is honest (you have none),
never fabricated; ZT WRITES stay fail-closed. Clears the console errors on 4
secondary product pages for every org without those backends deployed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 03:25:15 -07:00
86d805c1f0 cloud: remove /v1/console/* namespace — routes to their real domains (keys/onboard→/v1/iam) (#227)
"console" is just our cloud FE name; there must be NO /v1/console/* API domain.
Rename clients/console → clients/account and re-home every route onto its REAL
domain, forwards-only (no /v1/console aliases, no compat shim):

  keys   GET/POST/DELETE  /v1/console/keys        → /v1/iam/keys
  onboard POST            /v1/console/onboard      → /v1/iam/onboard
  csrf   GET              /v1/console/csrf         → /v1/csrf
  embed-status GET        /v1/console/embed-status → /v1/embed-status
  topup  POST             /v1/console/topup/wallet → /v1/commerce/topup/wallet
  health                  /v1/console/health       → dropped (generic /v1/<name>/health)
  waitlist                /v1/console/waitlist     → dropped (SPA uses clients/base /v1/waitlist)
  billing/commerce bridges /v1/billing/*,/v1/commerce/*  paths unchanged, relocated

The same handlers, CSRF protection (requireCSRF), per-IP rate limiting, and the
VALIDATED-principal tenancy are preserved — only the PATHS change.

IAM wildcard ordering: keys/onboard live on /v1/iam/*, which clients/iam (order 50)
mounts as a WILDCARD. The package registers TWO subsystems so the specific routes win
Fiber's first-match scan: `account` (order 48) mounts /v1/iam/{keys,onboard} + /v1/csrf
+ /v1/embed-status + /v1/commerce/topup/wallet BEFORE the wildcard (and before the
commerce embed at 100); `account-bridge` (order 122) mounts the /v1/billing/* +
/v1/commerce/* catch-all bridges AFTER clients/billing (121) + the commerce embed (100).
Both share one svc + a process-wide CSRF key so a /v1/csrf token verifies on the bridge
writes. Proven by TestIAMKeysBeatsWildcard (native /v1/iam/keys beats the wildcard;
/v1/iam/oauth/token still falls through) and TestRegisteredOrders (account<50, bridge=122).

waitlist.go/waitlist_test.go deleted; httpClient relocated to topup.go. All 54 tests
pass; go build ./... green.

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 03:24:55 -07:00
decb0c3d8c feat(dataroom): fold dataroom into cloud in-process on gojabase (#101) (#230)
Fold hanzoai/dataroom (Papermark fork: Next.js + Prisma + Postgres) FULLY into
the unified cloud binary via the gojahost pattern (HIP-0106, task #101 / epic
Postgres, no Next.js.

REUSE the shared binding, don't build a second. clients/dataroom runs the
self-contained dataroom goja bundle (byte-identical to hanzoai/dataroom/goja/
bundle.js, go:embed) on the REUSABLE clients/gojabase host — the SAME RW-Base
binding captable (#97) pilots and esign (#100) reuses — which injects
__db/__newId/__now, opens one SQLite file per tenant, and runs each dispatch in
one transaction (commits iff status<400). The leaf adds only: the per-tenant
Schema (schema.go), the object-storage seam for document bytes, a bcrypt HostFn
for link passwords, and the public link->org index. Zero domain logic in Go.

gojabase gains ONE generic, domain-free seam — Config.HostFns — the extension
point esign/dataroom both reach for (dataroom injects __bcrypt; the reserved
__db/__newId/__now always win). captable is unaffected (nil HostFns).

Storage: document BYTES go through the cloud object-storage seam (deps.VFS — the
S3/SeaweedFS data plane, a Go storage host-fn in the leaf, NOT local FS); the
bundle persists only the opaque key. View-analytics events (page-by-page
tracking) are Base rows in the tenant DB.

Auth: admin routes require a validated cloud principal (principal.Tenant -> org);
public viewer routes resolve their org from the link index. Passwords hashed with
bcrypt in Go — never plaintext. Registered order 134, HealthOwner, STAGED behind
CLOUD_ENABLE. go.mod unchanged.

Proof (clients/dataroom/flow_test.go, in-process over real per-tenant Base + the
VFS seam): create dataroom -> upload document (bytes to storage) -> attach ->
create email+password-gated share link -> open as public viewer -> authenticate
(wrong password 401, disallowed email 403) -> record per-page views -> analytics:
  {"pages":[{"pageNumber":1,"views":2,"totalDuration":6000,"avgDuration":3000},
            {"pageNumber":2,"views":1,"totalDuration":900,"avgDuration":900}],
   "totalPageViews":3,"totalViews":1}
plus viewer byte download round-trip and cross-org isolation. Live binary boots
with CLOUD_ENABLE=dataroom, mounts in-process, health 200, admin 403 fail-closed.

Companion bundle PR: hanzoai/dataroom#6.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 03:09:22 -07:00
6a53ff9c43 feat(sign): fold hanzoai/sign into cloud via the reusable gojabase host (task #100) (#229)
Fold the esign product (Documenso fork — open-source DocuSign) FULLY into the
unified cloud binary, per HIP-0106 (epic #96, task #100). Cloud serves /v1/sign/*
itself — the TS domain on dop251/goja backed by per-tenant Hanzo Base/SQLite. No
Next.js, no Prisma, no Postgres. Reuses the SAME clients/gojabase RW-Base binding
the captable pilot (#96) established — ONE binding, not a second.

clients/gojabase: add an additive, backward-compatible Config.HostFns passthrough
— extra native host globals injected per dispatch alongside __db/__newId/__now.
esign uses it for __pdf; captable is unchanged (tests green).

clients/sign (leaf on gojabase):
  - schema.go — the per-tenant sign.db DDL (gojabase Config.Schema).
  - signer.go — THE HARD PART as Go host-functions injected via HostFns as
    __pdf = { stamp (pdfcpu renders field values onto the PDF), sign (real
    x509/PKCS#7 seal via digitorus/pdfsign) }; signer sourced from KMS PEM,
    persisted PEM, or a self-signed dev cert. Signing orchestration stays TS.
  - sign.go — Mount + route table; owner routes gated by principal.Tenant,
    recipient token routes org-in-path. Registered + STAGED behind CLOUD_ENABLE
    (config.stagedSubsystems); retires the standalone esign pod on cutover.
  - sign_test.go — end-to-end wire proof: create→recipient→fields→send→sign→
    complete seals a REAL signed PDF (/ByteRange,/Type /Sig,PKCS7) + full audit,
    per-tenant Base-backed, with cross-tenant isolation.

Bundle: github.com/hanzoai/sign (goja/bundle.js) — the ESM-free domain port on
the gojabase contract (__db/__newId/__now/__pdf, handle{route,params,query,orgId,
body}, one txn per dispatch). go.mod additive; pdfcpu pinned v0.11.0,
hhrutter/pkcs7 v0.2.0 (no bumps).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 03:06:27 -07:00
hanzo-dev f40a3f01fb release: cloud v1.786.166 — org-scoped o11y (C1) + BYO billed_cost (C3)
Ship the crown-jewel security fix: o11y v1.5.5 (org-scoped llmobs span views — closes
the cross-tenant read exposed by the Observe->/v1/o11y repoint) + ai v1.804.1 (BYO
billed_cost). The leaky observation read is already deleted upstream (#217); this repin
ships the org-scope via the cloud-embedded o11y runtime.

(Coordinator asked for v1.786.162 but that tag + through v1.786.165 were already cut on
origin; this is the next free tag.)
2026-07-10 02:52:34 -07:00
hanzo-dev f978e6d1ee fix(security): repin o11y v1.5.5 (org-scoped llmobs) + ai v1.804.1
Crown-jewel security repin off the pseudo-versions to the merged release tags:
- o11y v1.5.4 -> v1.5.5: the llmobs span-view SQL is now org-scoped
  (gen_ai.hanzo.org_id = <validated tenant>, fail-closed) — closes the cross-tenant
  read the Observe->/v1/o11y repoint exposed. Cloud EMBEDS the o11y runtime
  (clients/o11y), so this is the ship vehicle for the fix.
- ai <pseudo> -> v1.804.1: gen_ai span emits _o11y.gen_ai.billed_cost alongside
  total_cost (BYO invoice reconciliation) + the enriched gen_ai span.

The leaky cloud_usage-as-observations read stays DELETED (upstream via #217); the
metering warehouse (cloud_usage via /v1/usage + the #218 /v1/evals/metrics dashboard)
is untouched. No go mod tidy (luxfi/keys go.sum fragility) — only the two repins.
Build: go build ./... green. Test: clients/eval + clients/o11y green.
2026-07-10 02:52:22 -07:00
3c8bb354cb feat(captable): fold Captable,Inc into cloud via goja + reusable Base binding (#96 pilot) (#228)
Cloud now serves /v1/captable/* ITSELF, per tenant, on Base/SQLite — the PILOT of
epic #96 (fold the Captable,Inc app into the unified binary; drop Next.js/Prisma/
Postgres). Where clients/plan + clients/pricing host a read-ONLY @hanzo catalog in
goja, captable hosts the tRPC business LOGIC (ported to a self-contained goja
bundle in github.com/hanzoai/captable) and gives it PERSISTENCE over per-tenant
Base/SQLite. The bundle carries logic; the Go host carries storage.

REUSABLE Base-goja binding (clients/gojabase) — the deliverable esign (#100) +
dataroom (#101) rebase onto. It is the storage-bearing sibling of clients/goja
(the pure JS engine): given a Bundle + a per-tenant Schema (DDL) + DataDir, it
- opens ONE SQLite file per tenant (lazy, migrated once, cached; slug-contained),
- injects per dispatch a tenant-bound __db bridge (query/exec) + __newId + __now,
- runs globalThis.handle inside ONE transaction that commits iff status<400 and
  handle didn't throw (atomic multi-statement mutations for free), and
- carries ZERO domain logic. clients/goja gains DispatchWith (per-call native
  globals) as the read-WRITE extension of the read-only plan/pricing path.

clients/captable leaf: go:embed'd bundle (hanzoai/captable.Bundle) + the per-
tenant schema (Prisma model → SQLite DDL) + a company seed (OnOpen) + the
/v1/captable/* zip routes. Org resolves from the VALIDATED principal
(principal.Tenant), never a client header; that org selects the DB file AND
scopes every row. Registered order 133; STAGED behind CLOUD_ENABLE (joins iam/
ingress/commerce in config.stagedSubsystems) so main stays shippable and the
standalone captable service keeps authority until the phase-2 cutover.

Full fold over Base: stakeholders, share classes, equity plans, securities
issuance (shares + options), share transfers (full + partial, atomic), SAFEs +
convertible notes, rounds + investments (a priced round issues shares and
dilutes), and a computed cap table (fully-diluted ownership, per-class
authorized-vs-issued, convertibles + rounds summary).

Proven:
- clients/gojabase: RW round-trip, per-request rollback (caught-500 + raw-throw),
  per-tenant isolation, OnOpen seed, slug traversal-containment (real SQLite).
- clients/captable: the REAL embedded bundle vs REAL SQLite through the whole
  lifecycle (create stakeholder → issue share class → issue shares → priced round
  + investment dilution → transfer → cap table), and an HTTP wire test via the
  zip/Fiber test client (trusted headers) proving create→read-back, issuance→cap
  table, the bundle's OWN 404 (not a proxy 502), the 403 principal gate, and
  cross-tenant isolation.
- Live binary boots under CLOUD_ENABLE=captable and serves /v1/captable/health
  200 in-process (a proxy would 502).

go build ./... + go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud green.
go.mod pins github.com/hanzoai/captable at its merged main commit; go.sum authentic.

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-10 02:48:03 -07:00
hanzo-dev 087a950e7d feat(platform): native POST /v1/runner build endpoint (retires GitHub Actions builds)
The server side of the ex-/v1/arcd surface: one native build API on the
runner fabric that hanzo build, git-push-to-deploy, and cloud's own
self-release all call — no GitHub builders, no Actions.

- runner.go: POST /v1/runner. Privileged (caller supplies the output
  image), so gated by a constant-time build-callback token AND an
  image-ref allowlist (ghcr.io/{hanzoai,luxfi,zooai}/*). Fails closed
  when no token is configured.
- k8s.go: launchDirectBuild — validated at the same choke point as the
  tenant build; plus buildFrontendCmd + buildJobSpec extracted so tenant
  and direct builds share ONE Job spec and ONE frontend selector.
- hanzoai/pack is the default BuildKit frontend (zero-config, gateway.v0);
  a Dockerfile is the explicit escape hatch (dockerfile.v0).

Tests: token 503/403, missing-field 400, image-allowlist 403, happy-path
202. Full platform suite green; whole cloud module builds.
2026-07-10 02:28:35 -07:00
8f3947018a cloud: per-project SQLite via one cloud.TenantDB resolver (DRY tenant DB) (#226)
Before: subsystems opened SQLite inconsistently. clients/code used the good
per-ORG-file pattern ({DataDir}/orgs/{slug}/code.db, resolved per-request), while
git/functions/tracker each opened ONE shared DB at Mount ({DataDir}/git.db,
functions.db, tracker.db) scoped only by an org column per-row — a decomplected
tenancy gap where the physical boundary was a single file for every tenant.

After: ONE resolver — cloud.TenantDB(dataDir, org, project, subsystem) — is the
single way any subsystem opens a tenant SQLite DB. Path convention:
  project-scoped: {DataDir}/orgs/{orgSlug}/projects/{projectSlug}/{subsystem}.db
  org-scoped:     {DataDir}/orgs/{orgSlug}/{subsystem}.db
It MkdirAll 0700s, opens via the sole "sqlite" driver (github.com/hanzoai/sqlite),
applies the shared single-writer + WAL pragmas, and folds org/project through the
injective SanitizeOrg slugger so distinct tenants can never share a file and no
segment can traverse. A generic cloud.TenantStore[T] caches per-tenant stores
(opened once each) so the hand-rolled per-subsystem map is DRY'd into one value.

SanitizeOrg (the one injective org-slug normalizer) moves to the root cloud
package beside OrgHasUnsafeRune and TenantDB; provisioning.SanitizeOrg delegates
to it, byte-identical, so S3/KMS/knowledge slugs are unchanged.

Subsystems migrated onto the resolver:
- code:      adopts the helper; stays ORG-scoped (no project axis) — same path.
- git:       single-shared git.db -> per-ORG file. Kept org-scoped (NOT project)
             because /v1/git/usage is a deliberate org-wide rollup across every
             project; the project stays a row column.
- functions: single-shared functions.db -> per-ORG file (no project axis).
- tracker:   single-shared tracker.db -> per-(org, IAM-project) file — tracker is
             project-scoped (principal.Project); its KEY-based projects are rows
             WITHIN each per-project file.
- tasks:     left as-is — it opens NO SQLite (delegates to the shared durable
             engine owned by durable.go), so there is nothing to migrate.

Data safety: the single-shared -> per-tenant switch is fail-closed (an invalid
org/project errors rather than falling through to another tenant's file). These
are new subsystems with little/no production data; existing rows in a prior
shared *.db would live under {DataDir}/{subsystem}.db and are NOT auto-migrated —
a deployment carrying such data must relocate rows into the per-tenant files
before cutover. No silent data drop.

Tests prove isolation: two orgs -> two files, no cross-read; two projects under
one org -> two nested files; project-scoped path nests; the cache opens each
tenant once. Root tenantdb_test.go plus per-subsystem end-to-end file-isolation
tests (git/functions org, tracker project).

Co-authored-by: zeekay <ai@hanzo.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 02:19:36 -07:00
hanzo-dev 38236d2589 Merge branch 'wt/v1run'
# Conflicts:
#	clients/platform/platform.go
2026-07-10 01:55:41 -07:00
hanzo-dev ecbd72ed38 cloud(run): POST /v1/run container-serverless handler (reuses Service-CR deploy path) 2026-07-10 00:52:55 -07:00
zeekayandClaude Opus 4.8 8ccb935540 fix(embed): cachebust on console main HEAD (re-embed on console-only change)
CONSOLE_CACHEBUST was the cloud sha, so a console-only push could not trigger a
fresh embed without a cloud commit — the whole point (freshness) leaked between
cloud pushes. Resolve hanzoai/console main HEAD (git ls-remote, extraheader
cleared since actions/checkout's GITHUB_TOKEN 404s cross-repo; gh absent on the
runner) and use it as the cachebust; fall back to the cloud sha if empty. A
console change now moves the cache key on its own.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 00:47:37 -07:00
hanzo-devandGitHub 2296e89841 controlplane inc-2 seam (a): per-pod ML-DSA-65 identity keys (contained, flag stays false) (#221)
* controlplane inc-2 seam (a): per-pod ML-DSA-65 identity keys

Replace the symmetric-HMAC proof-of-possession with per-pod asymmetric ML-DSA-65 (github.com/luxfi/crypto/mldsa, MLDSA65, FIPS 204 Level 3) identity keys — the same key material that becomes the cert-signing key in seam (c). idKey is now a fresh random keypair (crypto/rand), NEVER seed-derived; the registry stores the public key; signPoP uses the FIPS 204 5.2 deterministic variant with a domain-separation context; VerifyPoP is asymmetric VerifySignatureCtx.

Acceptance: the two byzantine-safety tests TestRed_B_DerivablePoPForgesHonestLeg and TestRed_B_LoneNodeForgesFullQuorum are un-skipped and now GREEN (an attacker rebuilding a pod's custody from public inputs gets a different key whose PoP fails); TestSafety_RogueAndForgedLegs_Rejected is re-armed to forge a CORRECTLY-DERIVED leg under a real attacker key (not a bit-flip) and still rejects it.

Scope: seam (a) only. ProductionBCCSigningReady() stays false and all other stubs remain — the flag flips later in the same change that lands the real cert (seam c) and deletes the stub types. Full suite green (zero skips), -race clean, gofmt clean, containment intact (no-tag build still matches no packages).

* controlplane seam (a): R3 — doc.go PoP narrative now reflects discharged crypto

RED review R3: refresh the stale CLASS-B caveat + ShareCustody stub-catalog entry so prose matches the code. Per-pod identity keys are real random ML-DSA-65 (not seed-derived); the two TestRed_B_* are un-skipped + green; only the z-share / cert crypto remains stub (ProductionBCCSigningReady stays false until seam c). Doc-only; no code change.
2026-07-10 00:33:24 -07:00
hanzo-devandGitHub 25c0f544cc feat(o11y): native-Go LLM-obs event ingest (folds retired console-worker) (#222)
Adds the write path for LLM-observability events (traces/observations/scores)
that the retired console-worker (Node BullMQ->Valkey->Datastore) used to
provide, folded into the cloud binary as a normal o11y subsystem.

- POST /v1/o11y/ingestion (validated tenant via principal.Tenant) -> parse batch
  -> route by type -> per-table batch insert into the Hanzo Datastore via the
  branded github.com/hanzoai/datastore-go/v2 client (promoted to a direct dep;
  first direct user in cloud). ZERO clickhouse imports/identifiers -- datastore-go
  brings the same upstream ch-go line (MVS-unified v0.71.0) the SigNoz o11y query
  runtime uses, so it coexists in one binary (verified).
- Grounding: the embedded o11y runtime (github.com/hanzoai/o11y) is a SigNoz fork
  serving INFRA o11y and mounts app.All("/v1/o11y/*") at order 70; it has no
  LLM-obs ingestion. This is a cloud-native SPECIFIC route registered at order 68
  so Fiber's in-order match binds it AHEAD of the wildcard (same rule scope.go
  uses for /v1/o11y/{logs,metrics,status} at 69). A route at the OTLP-ingest
  order (72) would be swallowed by the proxy.
- Oversized event bodies overflow to object storage (blob ref stored inline),
  threshold via CLOUD_O11Y_INGEST_BLOB_BYTES (default 1 MiB).
- Always mounted (no feature flag); the Datastore (O11Y_DATASTORE_DSN) is a
  required dependency. Fail-soft: no DSN / unreachable datastore -> unmounted,
  never blocks boot. Inert in prod until the console producer repoints here.

Tests: go test -tags 'cloud cloud_mount' ./clients/o11y/... green (8 cases:
routing, batching, blob overflow/disabled, sink+blob error propagation, threshold).
Full build green: go build -tags 'cloud cloud_mount' ./...

FLAGGED for cutover review:
- ASSUMED table/column schema (worker source ships dist-only; reconcile
  traces/observations/scores columns with 002_llm_observability.sql before the
  console producer is repointed).
- Durable EmbeddedTasks hand-off: flush runs INLINE today (removes BullMQ+Valkey);
  the durable enqueue->activity path is the next reviewed step (a Datastore insert
  must be a durable Activity, not run in a workflow fn).
2026-07-10 00:33:13 -07:00
hanzo-devandGitHub 422fb59b85 fix(idem): test uses hanzoai/sqlite not modernc directly — ONE driver, airtight (#225)
Pre-existing stray direct modernc.org/sqlite import in a test file (from #201).
Swap to the canonical _ "github.com/hanzoai/sqlite" (its !cgo backend IS modernc,
identical behavior) so NO file anywhere imports modernc directly. Test-only —
not in the shipped binary — but keeps 'hanzoai/sqlite only' truly airtight.
2026-07-10 00:30:11 -07:00
hanzo-devandGitHub 21a6324545 feat(md): agent-ready markdown content-negotiation via zap-proto/md (#224)
ONE data model, MANY adapters: handlers keep returning structured JSON; this
middleware re-serializes successful application/json responses through
zap-proto/md when the caller asks (Accept: text/markdown or ?format=md), so
token-efficient markdown is a request-time choice, not a second code path.
/v1/code/ + /v1/agents/ may default to markdown; caller override always wins.
Fail-safe: md render error leaves JSON untouched (never a 500); streams/HTML/
bytes pass through.
2026-07-10 00:24:43 -07:00
hanzo-devandGitHub bd90e0339b feat(code): /v1/code — SOTA hybrid code-intelligence (FTS5+trigram+tree-sitter+sqlite-vec), per-org (#223)
Native, per-org code-intelligence subsystem for AI coding agents and hanzo.app.
Retrieval is HYBRID — three orthogonal tiers fused with reciprocal-rank fusion
(the SOTA lesson that embeddings alone under-serve code search):

  - lexical  — FTS5 trigram over code-tokenized text (camelCase/snake_case split,
    operators kept); substring + regex via trigram pre-filter + regexp verify (Zoekt).
  - symbolic — go/parser for Go (real def→ref call edges) + compact lexical
    extractors for TS/JS/Python/Rust/Solidity; go-to-symbol + edge table.
  - semantic — AST-boundary chunks embedded via the SAME gateway /embeddings
    clients/knowledge uses; cosine KNN over a float32 vector table.

Storage is ONE SQLite file per org at {DataDir}/orgs/{slug}/code.db (HIP-0302):
the tenant boundary is PHYSICAL. Every request is principal-gated (principal.Tenant)
— no validated principal ⇒ 403, a client X-Org-Id is never trusted.

Routes (order 134, before the AI /v1/* catch-all):
  GET  /v1/code/search   ?q=&type=text|regex|symbol|semantic|hybrid&repo=&limit=
  POST /v1/code/context  {query,budgetTokens,repo}  → budget-packed context bundle
  GET  /v1/code/ask      ?q=&repo=  (or POST)        → cited RAG answer (deps.AI)
  POST /v1/code/index    {repo,files,prune}          → (re)index, incremental by hash

Parsing is pure-Go and vectors are brute-force cosine because the repo's canonical
build is CGO_ENABLED=0 (Makefile); CGO tree-sitter and the sqlite-vec loadable
extension would break `go build ./...`. The vectors table is the schema-compatible
sqlite-vec `vec0` drop-in seam. Builds + tests green under both CGO=0 (modernc) and
CGO=1 (sqlite_purego).
2026-07-10 00:24:21 -07:00
zeekayandClaude Opus 4.8 209b39b3e0 fix(visor): degrade /v1/clusters gracefully when Visor is unreachable
listMachines/listGpus already log+fall-through to a BYO-only list when Visor is
down; listClusters alone returned the error, which surfaced as a 502 + a console
error on the Clusters/GPUs page for every org where Visor isn't deployed
(visor.hanzo.svc unresolvable). Mirror the graceful fold: log, drop managed
pools, still return the org's BYO clusters. 200, honest empty, no page error.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 23:43:53 -07:00
81b28bef19 fix(iam-embed): bump hanzoai/iam v1.31.18 -> v1.31.19 (NewEnforcer panic fix) (#219)
Unblocks the embedded IAM subsystem. v1.31.18 getPermissionEnforcer called
authz.NewEnforcer(&DefaultLogger{}, false) — the (logger,bool) form Casbin
type-switches params[1]->persist.Adapter, panicking "bool is not persist.Adapter:
missing method AddPolicy" the moment InitEmbed runs against a FRESH store (exactly
the unified cloud iam subsystem). v1.31.19 (fe50caf7) uses NewEnforcer()+SetLogger.

Proven on a fresh store: CLOUD_ENABLE=iam,ai boots green ("iam embedded in-process")
and serves /v1/iam/.well-known/openid-configuration 200 (was fail-closed 503/404);
iam + ai co-reside, process listens :8080/:9653/:9090.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 23:26:10 -07:00
hanzo-devandGitHub 1050a6f924 feat(websearch): native in-process keyless meta-search — retire the SearXNG proxy (#220)
Finishes the native web-search half of /v1/websearch (HIP-0106: no external
search SaaS, one fewer non-Go dependency). The route no longer reverse-proxies
to the retired SearXNG pod; it runs metaSearch in-process:

- search.go: keyless meta-search over public engines (Bing default, DDG opt-in),
  parses HTML with x/net/html, merges+dedupes by normalized URL, returns the
  exact SearXNG {query,number_of_results,results[]} envelope the LibreChat
  searxng client decodes verbatim. A failing/bot-challenged engine contributes
  zero and never fails the request (degrades to fewer results, never a 5xx).
- websearch.go: /v1/websearch/search now serves searchNative; removed
  newSearchProxy + searchUpstream + WEBSEARCH_UPSTREAM. Auth unchanged (F2):
  validated principal OR shared X-API-Key; neither ⇒ 401/503, never open.
- tests: converted the proxy route/guard tests to native (mocked engine via
  WEBSEARCH_BING_URL fixture); added metaSearch parse + graceful-degrade tests.

go test ./clients/websearch/... green; full binary builds.
2026-07-09 23:16:01 -07:00
072a681958 feat(evals): native AI-observability dashboard at GET /v1/evals/metrics (#218)
Wire the metrics board handler and route that the completed data layer was
missing. metrics.go already had the ClickHouse ledger + GenAI-span aggregation
(assembleTotals/Series/ByModel, usageWhere, latency percentiles) and the
in-memory honest-empty path; this adds:

- metricsBoard handler: principal gate (403 without a validated tenant),
  SuperAdmin all-orgs via c.IsAdmin(), range preset -> window/bucket
  (24h|7d|30d, ?interval override), ?project threaded. nil telemetry or a
  non-default project -> honest-empty board (never 503, never fabricated).
- Telemetry.Metrics added to the interface (dsTelemetry + memTelemetry already
  implement it).
- Route registered in Mount() and the test mountApp().

All clients/eval tests pass, including the three handler tests that previously
404d (TestMetricsHandlerHonestEmpty / RequiresPrincipal / NonDefaultProjectEmpty).

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 22:56:43 -07:00
hanzo-devandGitHub 78ca8eee3d feat(eval+cli): collapse llmobs to o11y span plane + compute-ladder CLI verbs (#217)
* feat(eval): drop cloud_usage-as-observations read; collapse to o11y span plane

Step 1 of the unified AI-observability plan: the observation of record is the
o11y gen_ai span plane (/v1/o11y/observations), not a second projection of the
metering warehouse. evalsvc no longer reads hanzo.cloud_usage as 'observations'.

- Remove Telemetry.ListObservations + Observation/ObservationFilter types + the
  dsTelemetry (cloud_usage) and memTelemetry impls + the now-dead asInt64 coercer.
- Remove GET /v1/evals/observations route, its handler, and observationView/
  toObservationView. The console Observe > Observations view now reads o11y.
- cloud_usage stays the metering warehouse (read by /v1/usage + billing) — only
  the duplicate obs projection is gone. eval keeps its unique datasets/evaluators/
  runs and its own eval_traces/eval_scores tables.
- Bump ai dep to the enriched-gen_ai-span build (forward-only from v1.804.0).

Build+vet+test ./clients/eval green.

* cloud(cli): compute ladder — hanzo run/agent/bot verbs (thin /v1 clients)

Preserve in-flight CLI work: hanzo run (artifact/function), hanzo agent
(headless managed agent -> /v1/agents/:ref/run), hanzo bot (computer-using
agent -> operative/visor). Thin clients over IAM token + cloud /v1.
Claude-Session: https://claude.ai/code/session_01EjRSpFBvbjxTqaYVbds9bA
2026-07-09 22:55:21 -07:00
873c589712 fix(config): accept aud=hanzo-world in defaultJWTAudiences (#216)
world.hanzo.ai is the OIDC client `hanzo-world`; IAM stamps its access
tokens with aud=hanzo-world (each app's aud is its client_id). That
audience was missing from cloud's baked identity-sanitizer allowlist, so
signed-in world tokens resolved anonymous and api.hanzo.ai returned 401.
Append the client_id (forwards-only) and add a membership + resolved-env
acceptance test.

Claude-Session: https://claude.ai/code/session_013jh8aka8q8RvhhVQ1psMeW

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 22:14:23 -07:00
492461ce3b feat(commerce): embed commerce in-process as a cloud subsystem (task #89 phase 1) (#215)
Cloud now serves /v1/commerce/* + /_/commerce/* ITSELF via a new
clients/commercesvc leaf that wraps commerce.Embed's gin handler — the same
wrap-don't-rewrite fold clients/iam and clients/kms use — instead of proxying to
a remote commerce pod. deps.Commerce resolves to the in-process CommerceClient
(CommerceInProcess) when commerce is co-resident.

Why a leaf (not the upstream commerce.Mount): commerce's own Mount/init sit
behind //go:build cloud, and cloud builds without that tag, so cloud's plain
build never compiled the registration — commerce was blank-imported yet absent
from cloud.Registry (proxied at runtime). The leaf lives in-repo and imports only
commerce's cloud-free surface (Embed, api.Route, Version), so the upstream
commerce.Mount that imports cloud stays tagged out — no cloud<->commerce import
cycle. Zero go.mod/go.sum churn (commerce v1.46.40 already required).

STAGED (prod-safe): commerce joins iam/ingress in stagedSubsystems, so the
mount-all default is unchanged — the in-process cutover happens only on explicit
CLOUD_ENABLE=...,commerce. Phase 2 flips the default once validated in prod. The
remote proxy seam (CLOUD_COMMERCE_HTTP_URL / CLOUD_COMMERCE_ZAP_ADDR) is
untouched; the disabled/RPC fallbacks still compile.

GetTenantConfig is answered in-process (org + brand); CheckEntitlement fails
closed until commerce exports its subscription->plan->features resolver (Phase 2)
— the specified "cannot verify => never open" default clients/entitlements relies
on.

Proven: CLOUD_ENABLE=commerce -> GET /v1/commerce/tenant, /v1/commerce/catalog,
/_/commerce/healthz all 200 from the embedded gin engine; an unknown
/v1/commerce path returns gin's own 404 (a proxy would 502).

Claude-Session: https://claude.ai/code/session_016yg7GPhYdWCh9vpp4HEwLZ

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 22:08:05 -07:00
hanzo-dev fa4459c930 Merge branch 'wt/meters' into feat/collapse-llmobs-to-o11y 2026-07-09 21:48:20 -07:00
hanzo-dev 9c42d9943f cloud(billing): usage-native meters — function GB-seconds + build minutes 2026-07-09 21:44:15 -07:00
hanzo-dev 625a161de9 cloud(sites): opt-in COOP/COEP cross-origin isolation for WebGL 2026-07-09 21:39:21 -07:00
hanzo-dev 9062497996 cloud(sites): correct MIME for WebGL/WASM game assets (Unity/Emscripten/Godot)
Served sites typed .wasm/.data/.mem/.unityweb/.pck via mime.TypeByExtension only,
which returns "" for the engine payloads (empty Content-Type) and can mis-type
.wasm — breaking WebAssembly.instantiateStreaming (requires application/wasm) and
the loader's streaming fetch of Unity/Emscripten .data/.mem and Godot .pck. Pin
those in one gameAssetType map; everything else defers to the stdlib table.
Unblocks hosting WebGL game builds. Tested (TestGameAssetContentType).
2026-07-09 21:12:27 -07:00
hanzo-dev 71ec5f3496 cloud(cli): rename the native build endpoint /v1/arcd/enqueue -> /v1/runner
'arcd' is the client-side GitHub-Actions BYO product (github.com/arc-runner);
the platform's own native CI/compute pool is 'runner'. Rename the enqueue path
and de-brand the build command help/comments accordingly. Pairs with the
platform route move pages/api/v1/arcd/enqueue.ts -> pages/api/v1/runner.ts.
2026-07-09 20:19:10 -07:00
hanzo-dev 887341ac8a cloud(ci): BuildKit cache mounts on go build/test/mod — warm Go cache across builds
The 4 go invocations (mod download, sqlite double-register gate, encryption-proof
test, final build) had no cache mount, so every release recompiled the full CGO
graph (k8s + otel-collector + sqlcipher, CGO=1) from scratch on the ephemeral ARC
runner — the Build step was ~1316s/22min, dwarfing every other step. Mount
/go/pkg/mod + /root/.cache/go-build (sharing=locked) so the persistent ARC dind
BuildKit cache keeps the Go build+module cache warm. First build cold; subsequent
builds reuse compiled artifacts — target single-digit-minute rebuilds.
2026-07-09 20:03:43 -07:00
hanzo-devandGitHub 0235278e32 Merge pull request #214 from hanzoai/feat/runner-ship
cloud(runner): embed the arc JIT runner as `hanzo runner`
2026-07-09 19:26:41 -07:00
hanzo-dev cbcc97117b cloud(runner): embed the arc JIT runner as hanzo runner
Migrate arc-runner/arc (arc-archive) cmd/arcd host-role JIT GitHub-Actions
runner into hanzoai/cloud as package runner/, exposed as `hanzo runner` —
third verb of the one-binary trifecta: engine serves models, gpu connect shares
compute, runner claims CI. One org login, outbound-only, GPU/vulkan-aware.

- runner/: host-role JIT daemon (config, GitHub App auth, poll, JIT launcher,
  /v1 control surface, WSL labels). In-cluster controller role deferred.
- cli: wire `hanzo runner`; also register `engine` in controlCommands (was
  constructed but missing from the router — silently undispatchable).
- Security (red+cto reviewed): /v1 defaults 127.0.0.1 + localGuard (Host
  allowlist vs DNS-rebind, Origin vs CSRF); child env stripped of secrets;
  fork repos skipped by default (private/internal-org scoping is the real
  containment; documented honestly).
- deps: +go-github/v52, +ghinstallation/v2; luxfi/keys v1.2.0->v1.2.2 (v1.2.0
  tag mutated at origin — bump past it, verified under -mod=readonly, no bypass).
2026-07-09 19:25:05 -07:00
hanzo-dev f2ddb388b7 o11y: release chtraces exporter on failed Start (no leak on fail-soft path)
CreateTraces opens the ClickHouse conn + spawns the writer's ticker goroutine, so
a failed Start must Shutdown to release them rather than leak on the fail-soft
mount path.
2026-07-09 17:39:47 -07:00
97a619bdd3 test(kms): make dual-mount two-scope assertion load-robust (#212)
The validated-org-principal check asserted ==200, coupling this cross-package
gate test to the orgs/users/me handler's downstream success (IAM/datastore),
which flaked under full-suite parallel load. Assert the gate/shadow decision
only — admitted (not 403) and mounted (not 404) — since tenant-scoped data
correctness is proven in clients/admin/scope_test.go. Anonymous->403 and the
SuperAdmin-only platform routes are unchanged.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 17:32:13 -07:00
zeekayandClaude Opus 4.8 4d54be04b0 fix(embed): bust console clone layer with cloud sha (gh/ls-remote-free)
The prior two attempts (c97af12 sha-pin via git ls-remote, 4a7e533 via gh api)
both FAILED at version-compute: the ARC runner has no gh CLI, and git ls-remote
404s because actions/checkout installs a global http.extraheader carrying THIS
repo's GITHUB_TOKEN (scoped to hanzoai/cloud), overriding URL creds on the
cross-repo hanzoai/console lookup.

Bulletproof instead: no console-HEAD resolution at all. release.yml passes the
cloud commit sha as --build-arg CONSOLE_CACHEBUST (unique per push); the
Dockerfile references it in the proven `git clone --depth 1 --branch main`
RUN, so the layer cache key changes every build and re-clones console main HEAD
fresh. No gh, no ls-remote, no extraheader. Correctness over cache reuse — the
console stage rebuilds each release, but the embed is never the frozen snapshot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 17:30:51 -07:00
4c217c7efb fix(base+admin): base serves /v1/base/health (HealthOwner) even embed-off; dual-mount red test tracks the admin two-scope model (#211)
- clients/base: register /v1/base/health in Mount BEFORE the CLOUD_BASE_EMBED
  gate and mark cloud.HealthOwner — same always-on liveness pattern as
  clients/plan + clients/pricing. Fixes cmd/cloud TestMountAllAndServeHealth
  (base was the only listed subsystem not self-serving health).
- clients/kmssvc red_dualmount_test: #192 made the admin cockpit two-scope —
  orgs/users/me are org-scoped (guardScoped: a validated org principal is
  admitted + hard-scoped to its own org; anonymous still 403), while
  audit/roles/finance/flags/revenue stay SuperAdmin-only (guard: 403 for a
  non-admin principal). Assert both, plus kms's public /v1/kms/config never
  shadows either. No production code semantics changed — the stale test tracked
  the pre-two-scope admin-only contract.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 17:26:29 -07:00
zeekayandClaude Opus 4.8 4a7e533d5d fix(embed): resolve console HEAD via gh api, not git ls-remote
git ls-remote failed 'Repository not found' on the cross-repo hanzoai/console
lookup: actions/checkout installs a global git http.extraheader carrying THIS
repo's GITHUB_TOKEN (scoped to hanzoai/cloud only), which overrides the URL
creds and 404s. gh api honors GH_PAT (org read) and is unaffected. Unblocks the
console-embed-freshness fix (c97af12) — the release aborted at version-compute
before building.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 17:24:26 -07:00
hanzo-dev f28ff67f93 o11y: dogfood ZAP Router — cloud's own spans -> in-process ClickHouse sink, no socket
cloud already embeds the o11y trace write side (chtraces), so shipping its OWN
spans over the ZAP wire to a collector that then writes the same store is pure
waste. Route them through the ZAP locality-adaptive Router (luxfi/zap v1.2.1):
when sender and sink share this binary, the Cost-0 InProcessInterface wins and
the LIVE proto batch is handed to the sink by value — zero ZAP-wire serialize,
zero socket, no second collector hop.

- clients/o11y/tracesink.go: Router + Cost-0 InProcessInterface on Destination
  "hanzo.o11y.traces"; a chtraces exporter (the REAL o11y_index_v3 writer, reused
  as a consumer.Traces — its pdata->SpanV3 conversion is unexported) fed in
  process. Handler bridges SDK-exporter proto spans -> pdata via one in-memory
  OTLP round-trip. OPT-IN (O11Y_TRACES_ZAP_INPROCESS) + fail-soft: any error
  leaves cloud's spans on the wire; can never take cloud down. NewTraceExporter +
  routerTraceClient own the transport; cmd/cloud stays the composition root.
- cmd/cloud/telemetry.go: install the ONE tracer provider over the Router
  (in-process primary, ZAP wire fallback when the sink isn't registered). Enable
  when the in-process sink is on OR a wire endpoint is set. Composition-root
  single-provider invariant (ai's GenAI tracer inherits it) preserved.
- go.mod: github.com/luxfi/zap v1.2.0 -> v1.2.1 (adds Router/InProcessInterface).

TDD: span from cloud's provider reaches the in-process handler with no wire
client and no socket; proto->pdata round-trip preserves the span; router prefers
in-process, falls back to wire on ErrNoRoute, surfaces ErrNoRoute when neither.
2026-07-09 17:21:29 -07:00
6f12cfb617 refactor(kms): merge clients/kmssvc into clients/kms — one KMS package (#210)
The kmssvc dir was an artificial split: clients/kms is the KMS library
(embeds luxfi/kms + SecretStore + in-process client), clients/kmssvc was
the Fiber subsystem mounting /v1/kms/* — and it was ALSO package kms, dir-
named kmssvc only to dodge a dir-name collision. That svc suffix is a
workaround, not a concept.

Move every kmssvc file into clients/kms (kmssvc.go → mount.go; login.go,
env_required/kms/login_ratelimit/paas_sync/red_*/v6 tests). subsystems.go
imports clients/kms (order 10, /v1/kms/*); exactly one cloud.Register("kms").
Zero kmssvc refs remain. Full cloud build + kms package tests (incl red_*
adversarial) green. (Pre-existing clients/kms/replication test build failure
is unrelated — broken on main before this change.)

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 17:13:54 -07:00
hanzo-devandGitHub 2e68c5cb55 org+idem: fenced single-writer + exactly-once request layer (lift replicas:1 -> N safe) (#201)
Composes the ha lease-round (v0.1.1) and vfs/replica.FencedStore (v0.6.3) into
the cloud per-org substrate, and adds the request-layer exactly-once dedup, so
per-org SQLite is safe under a multi-replica Deployment (not just replicas:1).
Four orthogonal concerns, one home each:

  internal/org/fence.go   CASFencer: the INTERIM monotone round source. A per-org
                          writer lease {round,owner} over the object store's CAS
                          (a single linearizable register); takeover strictly
                          bumps the round, renewal keeps it. Implements ha.Fencer,
                          so the Lux BFT round drops in behind the same seam later.
                          HRW is only an optimization (cuts contention); safety
                          does not depend on a fresh/agreed membership view — a
                          split view costs liveness, never safety, because the
                          fence backstops it.
  internal/org/condstore.go  MinioConditionalStore: the concrete atomic-CAS store
                          (minio If-Match against the SeaweedFS gateway), promoted
                          from the orphaned internal/writefence. satisfies
                          replica.ConditionalStore.
  internal/idem/          exactly-once request execution: request-id PK written in
                          the SAME txn as the effect (atomic dedup+effect), shipped
                          in the per-org snapshot so a retry re-routed after a
                          rolling upgrade is deduped on the successor. 'fail if
                          already done' via ErrAlreadyApplied.
  internal/org/shared.go  re-export FencedStore/ConditionalStore/Lease/Fencer/
                          Round/ErrStaleRound so the org API stays one surface.

Deletes internal/writefence (was orphaned, zero importers): its fence primitive
is promoted to vfs/replica.FencedStore (the storage substrate's rightful home),
its minio store to condstore.go — one and one way, forward-only.

Safety (no data loss + no double-exec) rests on the composition, proven by
handoff_test.go against the four hazards: (a) partition minority cannot advance
the round -> cannot write; (b) rolling-upgrade handoff -> successor CarryForwards
the predecessor's last landed write + dedups; (c) duplicate request -> idem runs
once; (d) deposed writer -> refused by election, and if it still ships, fenced by
FencedStore. Ship-before-ack: a request is 'done' only once its fenced ship lands.

Interim round source = single linearizable register (object CAS) = crash-fault
tolerant. Roadmap: replace readLease/claim with the quasar PQ-BFT agreed round
(Byzantine-tolerant, deterministic finality, 3/5 quorum) — same ha.Fencer seam,
same FencedStore admission.

Cross-repo: pins ha@fence-lease + vfs@fenced-store (pseudo-versions); retag to
ha v0.1.1 + vfs v0.6.3 once those merge. go.sum touches only ha+vfs; the
pre-existing luxfi/keys@v1.2.0 re-tag mismatch (blocks `go mod tidy` on main
today) is unrelated and untouched.
2026-07-09 16:47:19 -07:00
zeekayandClaude Opus 4.8 c97af12f4f fix(embed): re-clone console per build — stop shipping a frozen embed
The console-clone+build layer was keyed only on static text ('git clone
--branch main'), so on the persistent ARC dind BuildKit cache EVERY cloud
build re-embedded the SAME stale console snapshot. New console work — the
native Tracker module, and everything since the cache was first warmed —
silently never shipped: console.hanzo.ai/tracker rendered an old surface
with zero /v1/tracker calls even on a freshly-deployed image.

Fix (values, not places): release.yml resolves hanzoai/console main HEAD
(git ls-remote) at build time and threads it through --build-arg CONSOLE_REF;
the Dockerfile fetches that exact ref (init+fetch+checkout, sha- or branch-
capable). A changed sha moves the layer cache key, so each build embeds the
live console commit — deterministically pinned, never frozen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 16:45:56 -07:00
a1551bf593 feat(admin): operator cockpit — two-scope model, flags/launch, waitlist/access, bases (#192)
admin.hanzo.ai as ONE cockpit for BOTH tiers off ONE identity predicate. scope.go decomplects the rule into a single place (resolveScope/scopedOrgs/descendants): owner==admin (c.IsAdmin, SuperAdmin) => cross-tenant, all orgs; any other validated admin => their OWN org, hard-scoped server-side. guardScoped admits a SuperAdmin OR a validated org-pinned caller and the handler scopes the data; the platform control plane (roles/audit/finance/revenue + launch/release/flags/access) stays s.guard (SuperAdmin only). me/overview/orgs/users/usage/analytics/bases are org-scoped; a non-super caller can never read another tenant for any input (their org is the sanitized, un-forgeable c.Org()).

Feature flags / launch / access via Hanzo Insights (one engine, not two): clients/featureflags is a hot-apply evaluation seam over Insights /flags (env = fallback default, 15s TTL, fail-safe degrade); /v1/admin/flags surfaces the launch switches (public_signup, waitlist_open, waitlist_access_capacity, ...) with deep-links to the Insights flag manager + activity log. /v1/admin/waitlist + /boost proxy the Base waitlist engine (server-authed, KMS secret, audited grant). /v1/admin/bases is the scoped tenant-Base panel seam (honest-empty until the Base engine is embedded).

Fix: waitlist.go shadowed the ok() envelope writer with a local bool (compile error) — renamed to configured. Tests: scope_test.go proves the two-scope invariant (super sees all; org-admin hard-pinned to own org; platform routes 403 an org-admin; users read pinned to own org); featureflags_test.go proves hot-apply + env fallback. go build ./... green; go test ./clients/admin/ + ./clients/featureflags/ green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-09 16:31:39 -07:00
hanzo-devandGitHub 952cb921ab feat(edge): embed the gateway CORS + per-IP rate-limit role in cloud (#181)
* feat(edge): embed the gateway CORS + per-IP rate-limit role in cloud

Fold the hanzoai/gateway edge role into cloud so it can serve api.hanzo.ai
directly, dropping the redundant KrakenD hop. cloud already validates the IAM
JWT + strips/re-mints identity headers (SanitizeIdentity), runs the per-tenant
ScopeRateLimit, and owns balance/spend-cap quota (BillingGate) — the gateway
duplicated the JWT/identity role and added only CORS + a per-IP flood cap.

Adds middleware_edge.go (package cloud), two orthogonal middlewares wired into
the serve.go chain AFTER Logger/sites and BEFORE identity:

- EdgeCORS: credentialed reflect-Origin CORS matching the gateway's policy
  (methods/headers/max-age). DEFAULT OFF (empty CLOUD_CORS_ORIGINS) so the
  shared Traefik ingress `cors-allow-all` stays the sole CORS authority on the
  recommended rollout — enabling both would double the ACAO header. Set
  CLOUD_CORS_ORIGINS only on a direct DO-LB->cloud edge. Handles + short-circuits
  the OPTIONS preflight (204) before any auth work.

- EdgeRateLimit: per-client-IP fixed-window flood cap (default 100/1s, gateway
  service-tier parity, strategy:ip) that runs BEFORE identity — the one gap
  ScopeRateLimit (keyed on the validated tenant) structurally can't see: an
  anonymous flood with no valid JWT. Keyed on the leftmost X-Forwarded-For;
  in-cluster direct callers (no XFF) are exempt, matching the standalone
  gateway's public-only scope. Opportunistic eviction keeps the bucket map
  bounded at edge IP cardinality (default ON, CLOUD_EDGE_RATELIMIT=false to
  disable). This preserves the gateway's protection rather than dropping it.

Config: CORSOrigins, EdgeRateEnabled/PerIP/WindowSec (config.go).
Tests: TestOriginMatcher, TestEdgeCORS_*, TestEdgeRateLimit_* (all green).
CGO_ENABLED=0 go build ./... + go test . green.

* feat(gateway): /v1/gateway runtime-mutable edge-policy plane

Make the embedded gateway role RUNTIME-CONFIGURABLE instead of baked into static
config: an operator/SuperAdmin retunes CORS, the per-IP flood cap, or a tenant's
rate ceiling via PUT /v1/gateway/config with NO redeploy — replacing the gateway's
image-baked KrakenD config.

clients/gatewaypolicy (leaf pkg, stdlib + hanzoai/sqlite only, no cloud import so
both the middleware and the HTTP subsystem share it cycle-free):
- Policy{CORSOrigins, PerIPRPM, WindowSec (platform), OrgRPM (per-org)} — every
  field is enforced by a consumer; no stored-but-ignored knob.
- Store: one encrypted per-tenant SQLite (gateway.db), org-keyed rows. The admin
  org row is the PLATFORM policy, layered over the static env/flag boot defaults.
  Cached resolvers Platform()/OrgRPM()/Effective() (5s TTL, fail-open to static),
  merge(base,over) makes a partial PUT additive. Fail-soft: a store-open error
  degrades to static-only (reads work, writes error) — the edge never goes down.

clients/gatewaysvc: the /v1/gateway subsystem (order 139) — GET/PUT config over
the SAME store, IAM-gated like clients/pricing/enablement.go:
- platform fields (CORS/per-IP) writable ONLY by SuperAdmin (c.IsAdmin()); routed
  to the platform row explicitly (PutPlatform) so an org-switched SuperAdmin still
  lands on it.
- per-org OrgRPM writable by the org admin (own org via principal.Tenant, never a
  raw header) or a SuperAdmin targeting ?org=<slug>.

Wiring: deps.GatewayPolicy (BuildDeps constructs it, layered over staticEdgePolicy;
serve.go closes it at shutdown). EdgeCORS/EdgeRateLimit now read the PLATFORM policy
LIVE (recompiling the CORS matcher only when the allowlist changes; the per-IP
limit/window per request). ScopeRateLimit gains the runtime per-org OrgRPM
override (most-restrictive-wins with the commerce-configured ceiling).

Tests: gatewaypolicy (static-only, platform layering, additive merge, per-org +
platform-default OrgRPM, persist-across-reopen); gatewaysvc (principal required,
org-self OrgRPM, org-admin platform 403, SuperAdmin platform, org-switched-still-
platform, empty-body 400). CGO_ENABLED=0 go build ./... + go test . green.
2026-07-09 16:25:43 -07:00
f842827e0c feat(base): embed base app + waitlist in-process (/v1/waitlist), retire standalone superbase (#193)
Mounts /v1/waitlist/* served in-process off the embedded hanzoai/base app over
the durable cloud PVC — the in-binary replacement for the standalone superbase
pod. STAGED + fail-closed: no-op unless CLOUD_BASE_EMBED=1. Registered as the
"base" subsystem (order 60) in clients/base.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-09 16:21:02 -07:00
40c187a75f fix(sbom): lazily create hanzo.sbom_component (datastore connects after Mount) (#207)
The datastore connects ASYNCHRONOUSLY: ai/object.InitDatastore flips
DatastoreEnabled true only AFTER Mount returns. Mount ran the CREATE TABLE
DDL only when DatastoreEnabled() was already true, so in prod it was skipped
and never retried -> GET /v1/sbom/{ref} 502 'Unknown table expression
identifier hanzo.sbom_component' while /v1/sbom/health reported datastore:true.

Add a lazy, idempotent ensureTable(ctx) guarded by a mutex+bool that latches
ONLY success (a transient failure retries; sync.Once would cache the failure).
It CREATE DATABASE IF NOT EXISTS hanzo then CREATE TABLE IF NOT EXISTS, and is
called from ingest and resolve right after requireDatastore() passes; on error
they return a retryable 503. Mount now routes its best-effort boot DDL through
the same ensureTable and is non-fatal (a Mount-time miss no longer aborts the
subsystem).

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 15:47:23 -07:00
f51ebb5550 fix(brand): map <brand>.cloud/.network hosts to the brand (white-label) (#209)
The live cloud console runs on <brand>.cloud hosts that route straight to the
cloud Service (console.lux.cloud, console.zoo.cloud, …). BrandForHostOK only
matched a brand's primary marketing Domain (lux.network, zoo.ngo), so a request
Host on lux.cloud/zoo.cloud fell through to the deployment brand — emitting Hanzo
branding on a Lux/Zoo surface (agent-skills catalogue + any Host-branded reply).
Add AltDomains per brand (lux→lux.cloud; zoo→zoo.network,zoo.cloud;
hanzo→hanzo.cloud,hanzo.app; pars→pars.ai) and match them in BrandForHostOK.
Base-URL/issuer scoping still uses the primary Domain.

Claude-Session: https://claude.ai/code/session_01CDooqWJiB7yNNaSjGQjdL7

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 15:39:16 -07:00
674c88cb5a feat(agentskills): serve /.well-known/agent-skills discovery, white-labeled by Host (#208)
New subsystem clients/agentskills serves the Agent Skills Discovery surface from
a catalog GENERATED by hanzoai/openapi's skills.py and embedded via go:embed:

  GET /.well-known/agent-skills/index.json        the brand's MASTER catalogue
  GET /.well-known/agent-skills/<skill>/SKILL.md   one skill document

WHITE-LABEL: the brand is decided per request from the Host (new BrandForHostOK,
mirroring platform.ts getWhiteLabelBrand) — api.hanzo.ai serves Hanzo,
api.lux.network serves Lux (lux.id), api.zoo.ngo serves Zoo — never Hanzo
branding on a Lux/Zoo surface. An unmatched Host degrades to the deployment brand
(CLOUD_BRAND), not blindly Hanzo. Order 8 registers these exact routes BEFORE
IAM's /.well-known/* wildcard (50) and the console catch-all, so they win Fiber's
first-match. Public, GET-only, no secrets.

The binary does not re-derive skills — it serves the embedded bytes, so the
sha256 digests in index.json match the served SKILL.md exactly. Only a tiny,
self-consistent `ai` fallback is committed (catalog/.gitignore); `make
agentskills` / the Dockerfile `skills` stage regenerate the FULL catalog (all 68
services × hanzo/lux/zoo) from the openapi SOT before `go build`, mirroring
webui/dist. End-to-end serve test drives the real router (index + SKILL.md +
white-label + digest + 404); cmd/cloud links clean.

Claude-Session: https://claude.ai/code/session_01CDooqWJiB7yNNaSjGQjdL7

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 15:16:36 -07:00
3652a2929b feat(sbom): global SBOM datastore + /v1/sbom ingest & resolve (#206)
Add clients/sbom: a self-contained subsystem riding the ONE shared
ClickHouse client (ai/object.Datastore*) — no second connection — that
ingests CycloneDX SBOMs from CI and serves them by image digest/ref.

The store (hanzo.sbom_component, ReplacingMergeTree) is GLOBAL/cross-tenant
by design: an SBOM belongs to a content-addressed image digest, not a
tenant, so any tenant deploying that image resolves the same component set.
Ingest is gated to the canonical cloud super-admin check (c.IsAdmin(),
owner==AdminOrg) which the build fleet carries; resolve exposes only an
image's immutable bill-of-materials (no tenant data).

  POST /v1/sbom        ingest (super-admin/CI): flatten document.components[]
  GET  /v1/sbom/{ref}  resolve by digest OR ref (FINAL dedupe, type,name order)
  GET  /v1/sbom/health liveness + datastore bool (not JWT-gated)

Registered id "sbom" order 137 with cloud.HealthOwner (binds before the ai
/v1/* catch-all at 150). Mirrors clients/analytics for structure, coercers,
and the honest-503 datastore gate.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 14:28:03 -07:00
36c083b568 chore(deps): pin hanzoai/ai → v1.804.0 (cookie self-heal + one super-admin rule) (#205)
Clean-semver pin bringing three ai releases into the cloud binary:
- v1.803.1 fix(account): cookie-session self-heal (#71) — a signed-in admin
  whose beego session already holds a guest u-<hash> is rebound to the
  canonical identity from hanzo_iam_token, so /v1/admin/* stops 403ing.
- v1.804.0 refactor(authz): ONE super-admin rule — membership in the `admin`
  org (owner == AdminOrg); drops the configurable globalAdminOrgs + built-in.
  Matches cloud's clients/admin (isSuperAdmin canonical, isGlobalAdmin alias)
  and the console isSuperAdminAccount gate.

Supersedes the pseudo-version pin (#197) and the intermediate v1.803.1 pin
(#198, closed). Verified: go build -tags "libsqlite3 sqlite_fts5" ./cmd/cloud.

Claude-Session: https://claude.ai/code/session_01VZbTTNtf4y8y3XUr9wMqTX

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 13:46:20 -07:00
e761b4bb51 feat(platform,sites): pure-Go zip/tar.gz static-site upload + custom-domain serving (#204)
* feat(platform,sites): pure-Go zip/tar.gz static-site upload + custom-domain serving

Adds a self-service static-site deploy to the unified cloud binary's PaaS
surface and lets the site edge serve a customer's own domain from S3.

- projects: walkArtifact accepts a ZIP (archive/zip) as well as tar(.gz),
  sniffed by magic bytes; one deploy contract (index.html at root, same size
  and traversal guards), three container formats. A single wrapping top-level
  directory (a zip made from a project folder) is stripped so index.html lands
  at the root.
- projects: the deploy handler reads the artifact from a multipart file upload
  (a browser <input type=file>) OR the raw request body (a curl one-liner).
- sites: the host edge now serves a bound CUSTOM domain (a customer apex/host
  pointed at this edge) from that project's S3 prefix, resolved by the full
  host. Only external hosts (never one of our self domains) with a LIVE binding
  are served; every other host — our api/console hosts, or an unbound host
  routed here — Continues to the normal pipeline, so the API path pays no
  per-request lookup and a customer binding can never shadow a real Hanzo host.
- projects: POST/GET .../domains binds and lists a site's custom domains
  (admin-gated until DNS-ownership verification is wired here).
- surface: the static engine is exposed under /v1/platform/sites/* (the PaaS
  namespace) in addition to /v1/projects/*, so the one user flow is create a
  site -> upload a zip -> bind a domain -> live.

Pure Go, CGO-off. New unit tests cover the zip walker, format dispatch,
single-root strip, custom-domain routing (served/passthrough/self-host/not
-live), hostname validation, and host binding.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(projects): authorize custom-domain binding by the platform-operator org

A custom-domain bind is authorized for a global admin OR the platform-operator
org (the deployment's brand org, env CLOUD_PLATFORM_OPERATOR_ORGS, default the
brand). The operator manages customer DNS until per-tenant DNS-ownership
verification is wired here. Safe because a bound domain is inert until its owner
points DNS at this edge — the real gate is DNS control.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 13:12:56 -07:00
696e858564 debrand: signoz → o11y (branding) + repoint collector module to hanzoai/otel-collector (#202)
* debrand: signoz -> o11y (branding) + repoint collector module

Drop "SigNoz"/"signoz" where it is BRANDING (comments, docs, prose) to o11y,
and repoint cloud's direct collector import to the renamed module.

- go.mod/go.sum: github.com/hanzoai/signoz-otel-collector v0.144.6 (direct)
  -> github.com/hanzoai/otel-collector v0.144.7 (direct). The old module stays
  as an // indirect dep because hanzoai/o11y v1.5.2 (separate repo, out of
  scope) still imports it; the fork also pulls upstream
  github.com/SigNoz/signoz-otel-collector v0.144.5 // indirect.
- clients/o11y/ingest.go: chlogs/chtraces imports -> otel-collector.
- Branding prose swapped to o11y in telemetry.go, subsystems.go, embed.go,
  logs.go, metricsread.go, scope.go, ingest_test.go, agents.go, LLM.md,
  docs/consolidation.md.

KEPT (not branding):
- ClickHouse schema read by cloud (written by the deployed collector):
  signoz_traces / signoz_logs / distributed_signoz_index_v3, severity_text
  columns. Renaming reads without migrating the live schema breaks them; the
  v0.144.6->.7 patch bump does not migrate table names.
- Upstream API in hanzoai/o11y/pkg/signoz: import path, alias, type SigNoz,
  and signoz.New / SigNoz.Start references (that repo is debranded separately).
- Upstream package names: signozclickhousemetrics.
- Honest attribution: "SigNoz's dd-sketch fork of ch-go".

Build: go build ./... = 0, go vet = 0, go test ./clients/o11y ./clients/admin
= ok. go mod tidy is blocked by a pre-existing luxfi/keys@v1.2.0 go.sum
checksum mismatch (identical on origin/main) -> CI-authoritative.

* o11y: read o11y_* ClickHouse tables + bump collector to v0.144.8

Direct ClickHouse table reads renamed signoz_* -> o11y_* to match the
o11y read plane and the data-preserving RENAME migration (hanzoai/o11y#28):

  o11y_traces.distributed_o11y_index_v3  (was signoz_traces.distributed_signoz_index_v3)
  o11y_logs.distributed_logs_v2          (was signoz_logs.distributed_logs_v2)

Files: clients/o11y/logs.go, clients/o11y/metricsread.go,
clients/o11y/ingest.go, clients/admin/o11y.go (+ o11y_test.go).

Bump github.com/hanzoai/otel-collector v0.144.7 -> v0.144.8 (writer side
now CREATEs/WRITEs the same o11y_* physical schema). Collector go.mod is
unchanged between the two tags (identical go.mod hash) — pure source
rename, so the module graph is unchanged; go mod tidy left to CI
(pre-existing luxfi/keys tidy block is CI-authoritative).

go build ./... = 0. clients/admin + clients/o11y tests green (SQL
assertions now match o11y_* target names). Lockstep deploy: collector
v0.144.8 -> o11y#28 RENAME migration -> o11y+cloud readers.

* cloud: embed o11y v1.5.4 — version-less /v1/o11y + o11y_ schema reads + debrand

Bumps hanzoai/o11y v1.5.2→v1.5.4 (version-less surface + o11y_ ClickHouse table
reads + the signoz→o11y debrand) and repoints embed.go to the renamed runtime
package pkg/signoz→pkg/o11y (type SigNoz→O11y). Pairs with otel-collector v0.144.8
(writes o11y_) + the lockstep cutover migration. go build ./... = 0.

---------

Co-authored-by: hanzo <z@hanzo.ai>
2026-07-09 13:12:34 -07:00
8f0db9093f deps: bump hanzoai/o11y v1.5.1 -> v1.5.2 (o11y /v1/o11y path normalizer) (#199)
Embeds hanzoai/o11y#26: the mount normalizes the /v1/o11y/<resource> public
contract onto the internal SigNoz /api/vN routes (kills the /api/ leak, fixes
the llmobs /v1/o11y/* 404). Pairs with the cloud CR O11Y_GLOBAL_EXTERNAL__URL=""
change (universe#461) — deploy together.

Co-authored-by: hanzo <z@hanzo.ai>
2026-07-09 08:57:35 -07:00
zeekayandClaude Opus 4.8 88f7de5d35 fix(identity): read hanzo_iam_token cookie — unbreak embedded-console org-scoped /v1
The ai (casibase) layer SETS the httpOnly hanzo_iam_token cookie (the IAM JWT) after
login (ai/controllers/account.go iamTokenCookieName), but cloud's own identity
middleware only read [iam_access_token, access_token, hanzo_token] — NOT
hanzo_iam_token. So the embedded console (browser holds ONLY that cookie, no
Authorization header) resolved to no validated principal → every org-scoped /v1
endpoint (agents, gpus, machines, platform, orgs, entitlements, …) 403'd
'X-Org-Id required', and modules rendered empty. Add hanzo_iam_token (first) to
cookieTokenNames so cloud reads the SAME cookie the ai layer sets → validates the
JWT → X-Org-Id from owner → org-scoped surfaces authorize. Verified: the JWT is
present in the browser (1533-char httpOnly hanzo_iam_token); only the name was wrong.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 02:28:51 -07:00
7000bccaec chore(deps): bump hanzoai/ai → e1c4cde0 (cookie-session self-heal, #71) (#197)
Pulls the get-account cookie-path fix (hanzoai/ai#81): a signed-in admin
whose beego session already holds an anonymous guest u-<hash> is now
self-healed from the hanzo_iam_token credential to its canonical identity,
so /v1/admin/* stops 403ing under the console cookie session. Verified:
cloud binary builds with -tags "libsqlite3 sqlite_fts5".

Claude-Session: https://claude.ai/code/session_01VZbTTNtf4y8y3XUr9wMqTX

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-09 00:00:57 -07:00
fe2f9fc091 org: elect via hanzoai/ha; vfs/replica stays replication-only (#196)
internal/org/shared.go split its aliases along the real seam: election
(Member/Owner/IsOwner/Replicas) now re-exports github.com/hanzoai/ha; the
Replicator/Store/DB/DBPath stay github.com/hanzoai/vfs/replica. membership.go
and cipher.go are unchanged (the alias types line up: org.Member = ha.Member).
writefence doc updated to name ha as the election primitive.

One concern, one home: who-writes (ha) vs how-state-ships (vfs). No behavior
change; internal/org + writefence pass with -race.

NOTE: `go mod tidy` is blocked in this repo by a PRE-EXISTING, unrelated
luxfi/keys@v1.2.0 go.sum checksum mismatch; ha was added via `go get` +
marked direct by hand. Re-run tidy once that pin is fixed.

Co-authored-by: hanzo <z@hanzo.ai>
2026-07-08 23:11:34 -07:00
zandGitHub f84f5e2ead Merge pull request #195 from hanzoai/feat/ai-login-manager
feat(cloud): analytics.datastore entitlement gate for paid per-org usage analytics
2026-07-08 17:20:58 -07:00
hanzo-dev b5d8651f72 feat(cloud): analytics.datastore entitlement gate for paid per-org usage analytics 2026-07-08 17:01:45 -07:00
hanzo-dev ff60007ca2 test(cli): uploadOutputs takes active org 2026-07-08 16:38:10 -07:00
hanzo-dev 1153077622 Merge commit 'aef665f' into HEAD 2026-07-08 16:37:47 -07:00
hanzo-dev ac4d0771dc harden(build): -mod=readonly + GOSUMDB-on + digest-pinned bases (RED money-image gate)
Per RED's conditional GO on the encryption image:
- GOFLAGS -mod=mod -> -mod=readonly: the committed go.sum is the SOLE source
  of truth; any needed-hash drift FAILS the build instead of silently
  re-recording an unverified hash. Verified go.sum is complete + sumdb-
  consistent (go build/download clean with GOSUMDB ON).
- Drop GOSUMDB=off: a money image must not blanket-disable the checksum
  database. GONOSUMDB scoped to zap-proto/* only (first-party-direct).
- Digest-pin the three base images (node:24-alpine, golang:1.26-alpine3.22,
  alpine:3.22) @sha256 for a reproducible money image.

The ldd/readelf link proof stays belt-and-suspenders behind the ciphertext
proof (verified at build time on the musl image).
2026-07-08 16:16:07 -07:00
hanzo-dev 93d5eccd54 fix(console-sec): rate-limit keys on validated principal, not spoofable XFF (RED)
The limiter guards the OFF-GATEWAY path where nothing trusted stamps
X-Forwarded-For, so keying on the client-settable XFF let an attacker send a fresh
value per request and reset the 30/min bucket at will. These are all post-auth
money-write routes, so key on the un-spoofable VALIDATED principal (X-Org-Id/
X-User-Id, minted by SanitizeIdentity from a verified JWT); fall back to the socket
peer (L4 RemoteAddr) for an unauthenticated request (which the handler 403s anyway).
Test now rotates XFF during the flood (must NOT reset) and asserts a second principal
keeps its own bucket.
2026-07-08 16:14:38 -07:00
hanzo-dev f43062a3d2 feat(console-sec): CSRF token on money writes + per-IP rate limit (RED hardening)
Cloud-direct/off-gateway money path loses the edge WAF/limiter and the embed
session-bridge's Sec-Fetch-Site gate passes VACUOUSLY when Origin/Referer/SFS are
all absent (RED). Adds two positive controls to the console write surface:

CSRF (csrf.go) — GET /v1/console/csrf issues a token bound to the validated
principal (X-User-Id+X-Org-Id), MAC'd with keyed BLAKE3 (luxfi/crypto,
blake3.KeyedHash) under a server-only KMS key (CONSOLE_CSRF_KEY; ephemeral
per-process fallback). requireCSRF enforces X-CSRF-Token on the AMBIENT-cookie path
ONLY (no Authorization + a Cookie present) — Bearer/Basic/gateway/API callers are
immune to CSRF and skip it, so nothing non-browser breaks. A cross-site page cannot
read the same-origin token (SOP) nor set the custom header (no CORS preflight
granted), and the token is identity-bound so it can't be replayed as another user.

Rate limit (ratelimit.go) — per-IP token bucket (30/min) on mint/rotate/revoke key
+ wallet top-up; distinct from commerce's spend-cap, restores frequency protection
lost off-gateway. Keyed on XFF first-hop.

Wraps POST/DELETE keys, POST onboard, POST topup, POST billing, POST/PUT/PATCH/DELETE
commerce. Reads stay open. Tests: ambient-no-token 403, valid-token 200,
cross-identity replay 403, Bearer-skips-CSRF 200, rate-limit 429; existing suites
unchanged (no cookie ⇒ CSRF skipped). luxfi/crypto for the MAC (NOT stdlib/JWT).

Needs arcd build + RED review; CONSOLE_CSRF_KEY to be provisioned via KMS for
restart/multi-replica-stable tokens (coordinate ac742480).
2026-07-08 16:14:38 -07:00
hanzo-dev 5c5774a4f5 fix(cloud-direct): stamp X-User-Name; mint hk- keys by owner/username not owner/uuid
The in-binary direct-Bearer path (console SPA -> cloud, gateway bypassed) stamps
X-User-Id = the JWT subject (a UUID) via idClaims.userID(). The console key ops
built the IAM id as <owner>/<X-User-Id> = hanzo/<uuid>, but IAM's mint-user-keys /
get-user resolve only <owner>/<name> (hanzo/z) -> 'password or code is incorrect'
-> hk- mint 502 on the cloud-direct path. (The gateway path worked because the
gateway minted X-User-Id == username.)

Fix (narrow blast radius, per RED-preferred approach — does NOT reorder userID()):
- idClaims.username(): the IAM username (name claim, then preferred_username),
  NEVER the subject.
- SanitizeIdentity stamps X-User-Name from the validated username, DISTINCT from
  X-User-Id. X-User-Name is already an authorityHeader (stripped on ingress,
  re-injected only from validated claims -> forgery-proof).
- resolveCaller carries a distinct caller.username (X-User-Name, fallback to
  X-User-Id for the gateway path); new caller.keyID() = <owner>/<username> is used
  ONLY by the user-key ops. caller.id / caller.name are UNCHANGED, so the
  billing/topup/commerce subjects are byte-identical -> zero money-path impact.

Tests: TestKeys_DirectBearerPath_MintsByUsernameNotUUID (mint targets hanzo/z, not
the UUID), TestSanitizeIdentity_StampsUserName, TestSanitizeIdentity_UserNameForgeryStripped;
existing key + identity suites unchanged (gateway path falls back to owner/name).

Needs arcd/CI image build (no local docker) + RED review before deploy.
2026-07-08 16:14:38 -07:00
hanzo-dev 9a5f1f35d5 build: CGO=1 + libsqlcipher encrypted image (was CGO=0 PLAINTEXT) + KAT gates
The unified binary embeds IAM's per-org SQLCipher store and commerce's
per-tenant money DBs; the prior CGO_ENABLED=0 build shipped pure-Go
modernc — PLAINTEXT at rest. Rebuild CGO=1 against system libsqlcipher
(hanzoai/iam's proven recipe: libsqlite3 tag + libsqlcipher symlink +
-DSQLITE_HAS_CODEC), runtime base scratch -> alpine:3.22 + sqlcipher-libs
(CGO needs libc + the codec .so).

Baked-in RED gates (a failing gate = NO image):
- modernc double-registration guard: 0 modernc in the CGO=1 ./cmd/cloud
  graph (the one 'sqlite' driver is mattn/SQLCipher).
- TestEncryptionProof: real ciphertext-at-rest under SQLITE_REQUIRE_CODEC=1.
- cek.go golden-vector KAT (TestUnwrapGoldenFixture + round-trip): a frozen
  pre-luxfi-swap 61-byte DEK sidecar still decrypts under the shipped
  luxfi/crypto-AEAD code — existing encrypted stores stay readable.
- readelf/ldd link proof: the binary binds sqlite3_* to libsqlcipher, never
  a plaintext libsqlite3.

Console embed stage unchanged (same-origin console). RED must review before
the image ships.
2026-07-08 16:03:57 -07:00
hanzo-dev ac366b4ccd deps: converge SQLite onto one driver — bump sqlite/orm/base/commerce/o11y/replicate
Bump the six hanzo modules to their driver-converged releases so the CGO=1
unified binary has EXACTLY ONE database/sql 'sqlite' registration
(mattn/SQLCipher), ending the 'sql: Register called twice for driver
sqlite' panic:
  sqlite     v0.1.5   -> v0.2.3   (SetPersistWAL + OpenPragma primitives)
  orm        v0.5.2   -> v0.6.1
  base       v1.4.6   -> v1.5.7   (+ replicate v0.9.5, the last modernc leak)
  commerce   v1.42.29 -> v1.46.40 (+ go:embed plans fix)
  o11y       (pseudo) -> v1.5.1
  replicate  v0.8.0   -> v0.9.5

Retarget the mattn v2.0.3+incompatible replace v1.14.16 -> v1.14.47 (the
SetFileControlInt/SQLITE_FCNTL_PERSIST_WAL-capable version hanzoai/sqlite
v0.2.3 needs for SetPersistWAL).

Verified CGO=1: 0 modernc in the ./cmd/cloud dep graph; the 517MB binary
builds and boots (--help) with NO double-register panic.
2026-07-08 16:00:21 -07:00
hanzo-dev aef665f260 gpu connect: materialize uploaded inputs + route output to active org
studio.render now (1) writes any inputs shipped with the job into the
local studio input dir via its own /upload/image, so an uploaded photo
(which lives in orgs/{org}/input on the dispatching pod, unreadable here)
resolves for LoadImage before the render; and (2) forwards the job's
active org as the studio_active_org cookie on /upload/output, so the
finished render lands in that org's gallery even when the worker token's
home org differs (a@hanzo.ai home=hanzo, rendering for karma).
2026-07-08 15:50:46 -07:00
hanzo-devandGitHub 0f5270d619 feat(cloud): SuperAdmin canonicalization + per-org entitlements API (#194)
SuperAdmin: /v1/admin/me and /v1/admin/users now emit the canonical
`isSuperAdmin` key alongside the deprecated back-compat alias `isGlobalAdmin`
(both populated with the SAME fact — owner == AdminOrg). The console may read
either during the rename migration and sees the same truth. No DB change: the
signal was always a derived boolean, never a stored column.

Entitlements: new clients/entitlements subsystem (order 139) — the per-org
product-enablement plane the console's paid-product sidebar reads.

  GET  /v1/orgs/:org/entitlements  -> { "enabled": [...] }
  POST /v1/orgs/:org/entitlements  { add?, remove? } -> { "enabled": [...] }

Two authorities, never braided: ENABLEMENT (this store: durable per-tenant
SQLite, (org,product) key, settings-store discipline) vs ENTITLEMENT (commerce:
deps.Commerce.CheckEntitlement at write time). A non-super-admin may only enable
a product the org's plan already grants (402 otherwise); disabling is never
gated; a super admin bypasses the commerce gate and may target any :org. Org
scoping mirrors clients/kms: :org must equal the validated owner claim unless the
caller is a super admin; a bearer-less forge fails the principal gate (403).

Tests (TDD, all green): store tenant-isolation + all-or-nothing Apply;
forged-request 403; cross-org 403; malformed org/product 400 (commerce not
consulted); entitled enable 200; unentitled enable 402 (nothing persisted);
super-admin bypass 200 (commerce not consulted); nil-commerce member-add 503
(fail-closed); remove never gated; empty mutation 400. Plus admin_test asserts
isSuperAdmin present and equal to isGlobalAdmin on both /me and /users.
2026-07-08 15:12:41 -07:00
zandGitHub d8e719bd7a Merge pull request #191 from hanzoai/feat/world-pricing
feat(world): plan enforcement contract + GET /v1/world/limits
2026-07-08 13:55:41 -07:00
hanzo-dev f435b301ab chore: pin hanzoai/plans to released v1.4.0 2026-07-08 13:55:37 -07:00
hanzo-dev 0386536b2e feat(world): plan enforcement contract + GET /v1/world/limits
Bumps @hanzo/plans to the World-pricing catalog (world-enterprise tier +
world.model_api gate) and adds the single-sourced enforcement contract for
the /v1/world data plane.

- clients/plan: export Entitlements(ctx, id) — the one Go seam to read a
  plan's canonical entitlement block from the @hanzo/plans catalog (runs the
  bundle 'entitlements' route; no data duplication, no fromLegacy re-impl).
- clients/world/entitlement.go: WorldLimits + WorldLimitsFromEntitlements
  (pure) + ResolveWorldLimits(ctx, planID) — values sourced from world.*
  entitlements, never hardcoded. FreeWorldLimits is the fail-closed floor
  (catalog outage degrades to Free, never grants model/stream).
- GET /v1/world/limits?plan=<id>: machine-readable contract echo so agents/
  dashboard self-config against the live catalog instead of hardcoding tiers.
- Tests: contract mapping (all tiers), fail-closed on unmounted catalog, and
  end-to-end Entitlements against the real embedded bundle (world.model_api
  present on pro/enterprise, absent on free).

Per-request enforcement (org->plan resolution + rate limiter wiring) is the
documented follow-up owned with feat/world-model-engine; both gates resolve
through ResolveWorldLimits so policy stays single-sourced.
2026-07-08 13:49:29 -07:00
e8a02057a2 fix(wallets): retry Safe deploy on 'wallet not found' (same ring commit race, DRY) (#190)
Proxy capture of cloud->ring proved the Safe flow hits the ring's commit-after-
response read-after-write race TWICE, not once: createVault->createWallet ('vault
not found', already retried) AND createWallet->deploy ('wallet not found', which
502'd custody=safe). With ALL requests pinned to one node (via a debug proxy) the
deploy STILL 404'd, so it is a Postgres commit-visibility lag, not node affinity.

Extract doRetryNotFound(...notFound) (bounded 6x/250ms linear, ctx-aware, fail-fast
on any other error; do() only unmarshals on 2xx so out is safe across retries) and
use it for BOTH createWallet ('vault not found') and deploySafe ('wallet not
found'). go test ./clients/wallets/... green; cmd/cloud builds.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 13:42:44 -07:00
6fbc419c8c fix(kmssvc): require explicit env on secret writes (no silent default) (#189)
The embedded KMS write path POST /v1/kms/orgs/{org}/secrets defaulted a
missing env to "default" (envOr), committing the write to a bucket that
project/env/path readers (the kms-operator, cluster syncs) never resolve.
That split is what let an IAM z-password land in env=default while prod kept
serving the stale value. env is a first-class component of the storage key
(kms/secrets/{path}/{env}/{name}) and cannot be aliased, so a write with no
env now fails loud (400). GET/DELETE/LIST keep the envOr compat default (a
read/delete can't plant a value another reader trusts; legacy readers that
omit env must keep working). No PATCH route exists on this surface.

Regression tests: write without env -> 400 (and lands nowhere); write
env=prod is readable via the operator's project/env/path resolution (sha256
round-trip, values never printed) and is not visible in env=default. The
fail-closed-without-master-key test now sends a valid env so it still
exercises the 503 master-key gate rather than 400-ing on input.

Claude-Session: https://claude.ai/code/session_01D4FSvT3UfhrFJNQjrctjEj

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 12:04:34 -07:00
hanzo-dev f0d9f8cefb feat(config): additive CLOUD_ENABLE_STAGED lever — activate staged subsystems without an allowlist
Enabled() staged path is now orthogonal to the Enable allowlist: a staged
subsystem (iam/ingress) mounts when named in EITHER Enable (strict allowlist) OR
the new EnableStaged (additive). CLOUD_ENABLE_STAGED=iam + empty CLOUD_ENABLE =
all-non-staged prod default PLUS iam — the faithful iam-fold canary/cutover shape
with NO hand-enumerated allowlist that silently drops a newly-added subsystem.

Proven: TestEnabled_StagedActivatesAdditively (iam on, non-staged default intact,
unnamed staged sibling stays off).
2026-07-08 12:01:06 -07:00
3123c009bb deps: bump hanzoai/ai -> #71 session-resolution fix (ai#79); iam stays v1.31.18 (#188)
Completes the #71 auth repair as a clean dep bump (the fix lives in ai + iam, not
the cloud tree):
- github.com/hanzoai/ai v1.802.0 -> v1.802.1-0.20260708185316-0321c35877f0
  (ai#79 0321c358: self-heal get-account identity — stop degrading real logins to
  u-<hash> guests; fail-closed 401). Pseudo-version pins the commit while the
  semantic-release patch tag mints (1 commit ahead of v1.802.0).
- github.com/hanzoai/iam v1.31.18 already pinned in main (iam#109 fail-closed
  guest-mint gate) — MVS keeps it over ai's older iam pin.
go mod tidy added the authentic gopsutil/v4 transitive hashes (iam util); go mod
verify OK; -mod=readonly CGO_ENABLED=0 go build ./cmd/cloud green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 11:58:25 -07:00
hanzo-dev 798a85fddf fix(iam): isolate embedded IAM's SQLite via IAM_DATABASE_URL — unblock iam+ai co-residence
Both the iam and ai casdoor-derived forks resolve their SQLite handle from the
SAME env key (dataSourceName) + the one beego web.AppConfig global. A deployment
sets dataSourceName for ai; with iam enabled, IAM's bootstrap resolved that same
value and xorm-opened ai's DB (auto-migrating casdoor tables into it) -> the
documented boot crash that pinned every post-embed release and kept iam staged.

IAM's conf already honors an IAM-scoped IAM_DATABASE_URL above the shared
dataSourceName; pin it to IAM's own iam.db under DataDir so the two forks get
independent stores, order-independent, NO fork edit. Operator override respected.

Unit-proven: TestIsolateDatabase (iam-owned DSN, != ai dataSourceName, respects override).
2026-07-08 11:55:47 -07:00
hanzo-dev 3771833d90 Merge fix/embed-session-principal-bridge: embed session→principal bridge + RED H2/H3 + iam v1.31.18 (H1)
Makes console.hanzo.ai (go:embed console) authenticate its money surfaces: the
first-party IAM session cookie → validated principal (sessionAccessToken → v.validate),
RED-hardened (H2 Secure cookie, H3 same-origin bridge gate), on iam v1.31.18 (H1
session-regeneration + iam-main security fixes). Pairs with console v8.4.122 which
addresses billing/commerce/keys at the canonical bare /v1 in embed mode.
2026-07-08 10:13:34 -07:00
hanzo-dev 5d18ca8264 deps(embed): pin hanzoai/iam v1.31.18 — H1 session-regen + iam-main security fixes ∪ InitEmbed
v1.31.18 is iam main (guard-leak stamp #108, guest-signin fail-closed #109, capauth
PermAttenuate #106) UNION the InitEmbed line UNION RED H1 (SessionRegenerateID on the
sign-in transition). The prior embed pin v1.31.17 had diverged off an old base and was
MISSING those iam-main security fixes, so pinning v1.31.17+H1 would have shipped the
money embed without them. v1.31.18 ships H1 + guard-leak/guest/capauth + InitEmbed
atomically into this binary's in-process IAM. Transitive indirect bumps (purego/
plan9stats/locafero/gopsutil-v4/viper/tidwall-match) are MVS-driven by iam v1.31.18.
2026-07-08 10:13:16 -07:00
hanzo-dev 00daba19e3 auth(embed): RED fixes H2+H3 on the session→principal bridge
H2 (HIGH) — pin the IAM session cookie Secure. clients/iamsvc/iamsvc.go derived
Secure from web.BConfig.Listen.EnableHTTPS, which is FALSE (the binary listens plain
:8000 behind the TLS-terminating ingress) → the session cookie shipped non-Secure.
The embed bridge turns that opaque sid into a money bearer (hk- mint, balance/top-up),
so a non-Secure cookie is capturable off any plaintext leg and replayable. Pinned
Secure: true (the deployed edge is always HTTPS).

H3 (MED-HIGH) — gate the ambient-cookie bridge to same-origin. billing.go/commerce.go
forward GET verbatim to commerce; a SameSite=Lax cookie still rides a top-level GET, so
a cross-site link could drive the victim's own money action if any commerce GET mutates.
validatedPrincipal now fires the session bridge ONLY for a same-origin request
(sessionBridgeSameOrigin: Sec-Fetch-Site same-origin|none, else Origin/Referer
host==Host) — refusing cross-site AND sibling-subdomain (same-site). Bearer/JWT-cookie
paths (non-ambient) are unaffected. +TestSessionBridgeSameOrigin (7 cases) green.

REMAINING for money: H1 (session-fixation — SessionRegenerateID on the IAM sign-in
transition) lands in hanzoai/iam (compiled into this binary); coordinating.
2026-07-08 09:55:08 -07:00
hanzo-dev b7cfda01fb auth(embed): bridge first-party IAM session cookie → validated principal
The go:embed console (console.hanzo.ai → cloud:8000) authenticates against the
in-process IAM, which sets an OPAQUE, httpOnly session cookie (cloud_session_id)
and stores the user's IAM-minted access-token JWT SERVER-SIDE against that session.
The console's Next BFF token-minting routes are stripped by the static export, so a
browser request to a cloud-native route (/v1/console/keys, /v1/billing/*) carries
only the session cookie — no bearer — and validatedPrincipal refused it, 401ing
every authenticated surface (API keys, billing, every product page = shell).

validatedPrincipal now resolves that session cookie to the server-stored access
token (sessionAccessToken via web.GlobalSessions) as a LAST RESORT (after Bearer/
Basic/JWT-cookie), then validates it through the SAME v.validate (sig/iss/aud/exp).
Identity is bound to the VALIDATED session: the client holds only an unguessable,
httpOnly sid; the session never asserts identity itself. No-op on gateway-fronted
binaries (a bearer is present) and on binaries with no IAM session manager
(web.GlobalSessions == nil) — tested. CSRF: cloud_session_id is SameSite=Lax, so a
cross-site request never carries it; and cookieTokenNames already establishes cloud's
JWT-cookie auth posture. This is the v8.4.5-flagged 'set the cookie the sanitizer
looks for' path, done cloud-side from the session store (no cross-repo IAM release).

RED review requested before it fronts money (session-fixation / CSRF surface).
2026-07-08 09:55:08 -07:00
25609e83ae feat(automations): waitlist points connectors — x/discord verify + award_points seam (#187)
Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 09:21:54 -07:00
3bbc9c51c0 fix(console): default HANZO_CHAIN_ID to genesis-canonical 36963 (#186)
topupConfig defaulted to the placeholder 36900; align to the
genesis-canonical Hanzo mainnet chain id 36963 (lux/genesis, and the
rest of cloud clients/treasury+wallets already use 36963). Still
env-overridable via HANZO_CHAIN_ID.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 09:01:20 -07:00
hanzo-devandGitHub f4cfbbf4f2 refactor(cloud): one /v1/o11y owner (embedded runtime); split settings out of observe (#185)
The observability surface was mounted THREE ways over the same /v1/o11y/* paths:
clients/observe (order 44), clients/o11y's o11yscope (order 69), and the
hanzoai/o11y wildcard runtime (70/71). observe also served /v1/settings/:product,
which is console product config, not observability. Collapse to one and one way.

- ONE owner of /v1/o11y/{logs,metrics,status}: clients/o11y's o11yscope (order 69).
  observe's richer logic is folded IN so nothing is lost — the REAL per-org RED
  metrics + LLM usage (metricsread.go, was a stub in o11y) and the two-view logs
  (admin infra stdout / per-org request-from-traces). Tenant isolation preserved:
  org is principal.Tenant bound as a positional ClickHouse param, the product is
  shape-validated → alias-mapped (console slug → workload) → allowlisted
  (knownServices, SSRF/injection boundary). observe's productAlias merged into
  resolveService so no product loses data. Admin god-view gates on c.IsAdmin()
  (== owner=="admin" SuperAdmin after SanitizeIdentity), never a per-org isAdmin.

- /v1/settings/:product moved OUT of observe into clients/settings (it is NOT
  observability). Behavior/contract preserved verbatim from observe: {config,
  secretKeys} shape, KMS ref orgs/{org}/settings/{product}/{key}, (org,product)
  store isolation, secrets-to-KMS-or-fail-closed. Replaces the orphaned, divergent
  clients/settings stub with the live behavior and wires it in (order 138).

- /v1/query does not exist (no registrant, no consumer) — nothing to fold.
  /v1/observe/health was the auto-derived GET /v1/<id>/health for id "observe";
  it vanishes with the subsystem (o11yscope gets /v1/o11yscope/health; the runtime
  serves its own gate-exempt /v1/o11y/api/v*/health*). Both documented.

- DELETE clients/observe; drop its import; add clients/settings; fix the stale
  subsystems.go o11y comment ("reverse proxy to the dedicated o11y Deployment" →
  the embedded reality: scoped reads 69 + in-process runtime 71 + OTLP ingest 72).

Net -1037 LoC. cmd/cloud + cmd/hanzo build; clients/o11y + clients/settings tests
pass (20/20), covering tenant isolation, secrets-never-plaintext, product
validation, alias resolution, and route precedence over the wildcard proxy.
2026-07-08 08:58:18 -07:00
e98d614b61 refactor(cloud): canonical subsystem names — drop svc suffixes, one noun per capability (#184)
One canonical short-noun name per subsystem (registered name + Go package dir +
route). No public route breaks: renames that change a live /v1 prefix keep the
old route as a back-compat alias (mount both, same handlers).

Renamed (internal-only, route unchanged):
  usagesvc  -> usage        (register string)
  zt        -> zero-trust   (register string; pkg dir kept `zt`, routes /v1/networks|mesh|edge unaffected)
  auditlog  -> audit        (register string; route already /v1/audit)
  s3        -> storage       (dir+pkg+register; route /v1/s3 kept — route-safe)
  tasksvc   -> tasks         (dir+pkg; register already `tasks`)
  iamsvc    -> iam           (dir+pkg; register already `iam`)
  mpcseal   -> mpc           (internal lib dir+pkg; importers repointed, local alias kept)
  gojahost  -> goja          (internal lib dir+pkg; importers repointed)

Renamed with public route + back-compat alias:
  kb        -> knowledge     (dir+pkg+register; canonical /v1/knowledge added, /v1/kb alias kept; framework module id `kb` retained = data-model id)

Log "subsystem" labels aligned to canonical names. Subsystem test enable-lists
and stale clients/<old> path comments updated. stagedSubsystems already
canonical ({iam,ingress}).

Held (route collisions — CTO decision):
  ml -> models       COLLIDES /v1/models (OpenAI-compat catalog owns it) — kept `ml`
  websearch -> search COLLIDES /v1/search (provisioned search resource) — kept `websearch`
  kmssvc dir         register+route already canonical (`kms`, /v1/kms); dir kept
                     to avoid colliding with the `clients/kms` SecretStore core lib.

Not present in repo: gatewaysvc / gatewaypolicy (gateway is a separate deployment).

Build: CGO_ENABLED=0 go build ./... green; go vet green; tests green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 08:55:27 -07:00
hanzo-devandGitHub a98b0f101f refactor(cloud): decomplect subsystem registration — Typed adapter, OwnsHealth flag, generic pick[T], clean ids (#183)
One coherent change to the subsystem-registration layer. Concrete types over
`any` at the call sites, indirection deleted, generics only where they remove
real duplication.

CHANGE 1 — kill the per-subsystem `any`-unwrap boilerplate
  Every in-repo subsystem's init() hand-wrote the identical
    func(app any, deps cloud.Deps) error { a, ok := app.(*zip.App); if !ok {…}; return Mount(a, deps) }
  Add ONE adapter, cloud.Typed(func(*zip.App, Deps) error) MountFunc, that does
  the *zip.App recovery in a single place (fail-closed, never panics). All ~50
  subsystems collapse to `cloud.Register("x", n, cloud.Typed(Mount))` /
  `cloud.RegisterWithShutdown(..., cloud.Typed(Mount), Shutdown)`. Redundant
  shutdown wrappers dropped where Shutdown already matches ShutdownFunc; kept
  only where a no-arg Shutdown() needs signature adaptation.
  MountFunc's param STAYS `any` on purpose: the pinned external subsystem modules
  (hanzoai/ai, authz, base, commerce, metrics, o11y, licensing) register with
  `func(any,…)`, and a `func(any,…)` literal is not assignable to a
  `func(*zip.App,…)` parameter — retyping MountFunc would break those modules at
  compile time. The assertion is now central, not per-subsystem. MountAll takes
  the concrete *zip.App (threaded from Serve).

CHANGE 2 — OwnsHealth flag replaces the "<name>svc" health kludge
  Some subsystems serve their OWN fail-closed /v1/<name>/health; the generic
  always-ok liveness route in Serve would shadow it. The old fix encoded routing
  policy in the id ("kmssvc" parked the generic route at an unrouted path). Now
  Register/RegisterWithShutdown take `opts ...Option`; cloud.HealthOwner sets
  MountSpec.OwnsHealth, and Serve's generic-health loop skips a HealthOwner. The
  id is once again the clean route name. Invariant now uniform and checkable:
  a subsystem serves /v1/<name>/health  IFF  it registers cloud.HealthOwner.
  Migrated every health-owner to it: kms, paas, s3 (named in scope) plus
  analytics, console, platform, ml (same kludge) and notify, plans, pricing,
  security (had coincidental id==route; security's real probe reports a rule
  count the generic route was silently dropping). pickKMSClient gate + all
  tests + stale comments updated from the "kmssvc"/"s3svc"/… ids to kms/s3/….

CHANGE 3 — clean package renames (no collision)
  clients/paassvc → clients/paas, clients/projectsvc → clients/projects
  (package decls, filenames, the sole importer, error strings, userAgent, and
  doc refs repo-wide). clients/kmssvc + clients/tasksvc KEEP their package names
  — the `svc` disambiguates the subsystem from the same-named library it imports
  (clients/kms, hanzoai/tasks); their ids are already clean (kms via CHANGE 2,
  tasks).

CHANGE 4 — generic pick[T]
  The five identical co-resident-or-RPC-or-disabled resolvers (IAM, Base,
  Commerce, O11y, MQ) collapse into one
    pick[T](cfg, log, name, label, zapAddr, rpc func(string)T, disabled func()T) T.
  KMS/AI/VFS/Payments/Vault keep bespoke pickers — their construction genuinely
  differs (embedded store / gateway preference / S3-admin backend / never
  co-resident), so they are left alone.

Verified: CGO_ENABLED=0 go build ./cmd/hanzo/ and ./cmd/cloud/ both exit 0;
go vet clean on every changed package; `hanzo --help` lists kms/paas/projects/
s3/tasks svc-free; cloud root + renamed + health-owner package tests pass; new
build_registration_test.go covers Typed + HealthOwner. Net −199 lines.
2026-07-08 08:13:52 -07:00
hanzo-dev ca4338e6a7 Merge branch 'feat/control-plane-ceremony'
# Conflicts:
#	config.go
2026-07-08 07:59:17 -07:00
hanzo-dev 489efc212e chore(cloud): repin luxfi/consensus v1.35.30 -> v1.35.32 (DoS bound + 1-based fix)
Picks up the increment-2 crypto hygiene: the PartyID<=ValidatorSetSize DoS
bound on the quasar/pulsar Finalize path (Item7a) + the structural-Verify lock
(Item7b). v1.35.32 corrects a 1-based off-by-one in v1.35.31 that rejected the
Nth validator; verified the controlplane N=7 ceremony finalizes under -race.
LOW severity (ingestLeg bounds PartyID upstream) but the fix is now live-pinned.
2026-07-08 07:56:58 -07:00
hanzo-dev 62b7ca17f4 merge: two-plane epoch write-fence primitive (strict-> + atomic CAS) 2026-07-08 07:51:42 -07:00
hanzo-dev 6fd7faf622 merge: controlplane containment cage (CI guard + fail-closed assert + external-cert seam) 2026-07-08 07:51:41 -07:00
cc6d2d17bf feat(ingress): embedded runtime-configurable edge subsystem (/v1/ingress) (#182)
Add clients/ingress — an embedded edge plane in the cloud binary so the ONE
binary can BE the fleet edge: terminate TLS, run ACME, and reverse-proxy by Host
to upstreams, configured LIVE over /v1/ingress with no static routes.yaml and no
restart to change a route (hot-apply via an atomic engine snapshot swap).

Control plane (zip): /v1/ingress/{routes,services,middlewares,tls,status},
SuperAdmin-gated, per-tenant SQLite persistence, route Host globally unique;
every mutation reloads the engine.

Data plane (net/http): :80 (ACME HTTP-01 + router) and :443 (SNI TLS termination
via x/crypto/acme/autocert + router). Started only in edge role
(CLOUD_INGRESS_EDGE_ENABLED); app role keeps the listeners off — role = runtime
config, one binary.

Proxy: github.com/vulcand/oxy/v2 (Traefik lineage) weighted round-robin, the
Traefik router->service->middleware model. Middlewares: redirectScheme,
stripPrefix, addPrefix, headers.

STAGED subsystem (config.stagedSubsystems): linked but mounts ONLY when named in
CLOUD_ENABLE, so prod is untouched. Orthogonal to /v1/gateway (auth/rate-limit).

Build: CGO_ENABLED=0 go build ./... green; go test ./clients/ingress green (11 tests).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 07:45:37 -07:00
hanzo-dev 69cbc858f1 fix(writefence): injective mirror key + single-read Get (red pass)
Red-team findings on the write-fence primitive:
 - HIGH: mirrorKey(plugin,shard) = "writefence/"+plugin+"/"+shard was not
   injective — mirrorKey("kms/tenant-a","secrets") collided with
   mirrorKey("kms","tenant-a/secrets"), so a push framed as one shard could
   overwrite another's epoch/writer/payload. Real shard scopes carry '/'
   (vfs replica.DBPath yields "projects/site"), so it is reachable. Fixed with
   a %d:-length-prefixed key; TestMirrorKeyInjective_NoCrossShardAliasing locks
   it (was red's failing PoC, now green).
 - LOW: MinioConditionalStore.Get did StatObject+GetObject (two round trips);
   tightened to one GET whose obj.Stat() ETag is consistent with the read bytes
   — closes the window rather than relying on the CAS to absorb a stale version.
Core CAS/epoch soundness unchanged (red GO: N=64 same-epoch race → one winner,
retry-bounded, strict-> rejects epoch==recorded). Still shadow-only, unwired.
go test -race -count=200 green.
2026-07-08 07:26:02 -07:00
hanzo-dev 95f3b49aa2 harden(containment): grep also catches -tags negation form (red pass)
Red-pass finding: the check-#1 grep char class [A-Za-z0-9_, ] missed the
build-constraint negation form `-tags '!x,controlplane'` (the `!` broke the
match before reaching controlplane). Add `!` to the class so it is caught.

Verified the deeper guarantees hold (evasion-agnostic), so this is belt-only:
 - ZERO non-test importers of clients/controlplane (grep-confirmed).
 - The package has ZERO untagged files, so importing it into serve code fails
   the untagged `go build ./...` — check #3 catches ANY -tags syntax, incl.
   GOFLAGS=-tags=controlplane (verified: the pkg becomes buildable => check #3's
   'matched no packages' assertion fails => CI red).
Runtime asserts + external-cert selfComposedCert seam confirmed wired through
guarded constructors. No stub-crypto path reaches a serve binary.
2026-07-08 07:18:31 -07:00
hanzo-dev 1471801173 harden(controlplane): CI guard also catches the testing.Testing() spoof vector
Self-review finding: containment.go's runtime guard trusts testing.Testing(),
which is backed by a linker-set string var (testing.testBinary, set by `go
test` itself per cmd/go/internal/load/test.go). Confirmed locally that
`go build/run -ldflags="-X testing.testBinary=1"` spoofs it to true in a REAL
(non go-test) binary — verified with a throwaway program before writing this.

containment.yml's grep step now also fails the build on any reference to
`testing.testBinary` outside the Go toolchain itself, so a build path that
tried to ship that spoof gets caught the same way a `-tags controlplane`
build path does. Documented as a known residual in the workflow's header:
this is a mitigation (CI catches it), not a cryptographic close — that needs
increment-2's real signing, tracked in doc.go.

Also fixed the exclusion patterns to be grep-implementation-agnostic (some
recursive greps don't prefix paths with "./"), verified against a planted
violation for both checks.
2026-07-08 07:09:47 -07:00
hanzo-dev b252c65089 fix(writefence): strict-epoch, atomic-CAS write-fence for the (plugin,shard) mirror
Closes the same-epoch double-write on the HIP-0107 data-plane push path
(github.com/hanzoai/vfs/replica, wired in internal/org): today the only
admission checks are replica.IsOwner (a pure local computation over a
possibly-stale membership view) and the StatefulSet Recreate deployment
shape (role.Role) — both comment-only, non-atomic, and the underlying
Store/Backend.Put is an unconditional overwrite ("Overwriting is allowed").
A deposed/partitioned writer and a freshly-elected one can both push.

internal/writefence/fence.go adds Fence.Push: a single atomic
read-check-CAS that (1) rejects any candidateEpoch <= the epoch currently
recorded for the shard (strict >, closing the same-epoch case) and (2)
performs the epoch-advance and payload append in ONE conditional write
against the store's live version token, so two racing writers cannot both
land — the store is the sole arbiter, never an in-memory cache. Retries
once on a lost CAS race, re-checking strict monotonicity against the new
state, so a same-epoch racer's retry fails ErrStaleEpoch rather than
silently duplicating the admit.

EpochSource is the pluggable seam clients/controlplane's lease epoch drops
into once it graduates from shadow (Stage 1 today) — this package imports
nothing from controlplane. ConditionalStore models the S3 If-Match / GCS
generation-match primitive; store.go backs it for real with minio-go's
native SetMatchETag/SetMatchETagExcept (already vendored at v7.0.100, no
go.mod bump). fake_test.go models the same semantics in-process with a
barrier hook that deterministically reproduces the concurrent-CAS race.

Tests prove: strict-epoch rejection of a same-epoch retry (same and
different writer), the raw CAS rejecting a race loser, the full
concurrent-Push race resolving to exactly one winner, a legitimately
higher epoch being admitted, a stale lower epoch being rejected, and
per-shard scoping. Not yet wired into the live push path (that remains
gated by controlplane's shadow flag per HIP-0116); this is the fence
primitive plus a precise wiring recommendation for hanzoai/vfs's block
layer, which currently exposes no conditional-write capability to adopt.
2026-07-08 07:07:17 -07:00
hanzo-dev ee39b8bce6 harden(controlplane): CI+runtime containment cage + external-cert type seam
Stage-1 ceremony's crypto is stub/forgeable by design (doc.go); this closes
the drift risks doc.go's increment-2 worklist flagged:

- .github/workflows/containment.yml (PR-gated): greps every build/release
  surface in the repo for `-tags controlplane` and fails the build if found,
  plus a positive proof that `go build ./...` links clients/controlplane into
  no cmd/ main and that the package still matches zero packages with no tag.

- containment.go: mustHarnessOnly fail-closed panics the moment this
  package's stub crypto is touched (package-import-time for the
  PartialZVerifier registration, construction-time for NewSigner/
  NewStubComposer) unless ProductionBCCSigningReady() (hardcoded false) or
  testing.Testing() (the Go toolchain's own go-test signal, unspoofable by a
  real build) holds. Proven end-to-end via a real subprocess
  (TestContainment_NonHarnessProcessRefuses), not just in-process logic.

- selfComposedCert typed seam (driver.go/signer.go): CertComposer.Compose now
  returns an unexported wrapper only it can produce; verifyOwnCertStructure
  accepts only that type, never a bare *quasar.QuasarCert. An externally-
  received cert has no way to become one, so it cannot reach the structural
  check even by mistake. VerifyExternalCert is the sole seam for such a cert
  and fails closed (increment-2 crypto not implemented). Locked from a
  black-box vantage in external_cert_test.go.

Containment verified unchanged: `go build ./clients/controlplane/...` (no
tag) still matches zero packages; `go build ./...` still links no cmd/ main
to the package; full `-tags controlplane -race` suite green, no test weakened.
2026-07-08 07:05:39 -07:00
hanzo-dev c03f5c2380 analytics: bake console website-id into the console-embed build
The cloud-embedded console (console.hanzo.ai + team) is built from hanzoai/console
build:embed. hanzoai/console now ships <HanzoAnalytics/> (env-gated on
NEXT_PUBLIC_ANALYTICS_WEBSITE_ID). Default it to the console.hanzo.ai property
(7dce54ee-41f6-4751-96bf-fe005067c7c7, public per-site) in the console build stage
so the one native analytics tag renders on the next cloud build. GA4/Pixel off.
2026-07-08 06:41:24 -07:00
e7cd108e0f fix(anchor): EIP-2 low-S normalize the MPC signature (fixes 'invalid sender') (#180)
The luxfi/mpc threshold signer returns a NON-canonical r|s: s is frequently in the
upper half (s > N/2). luxfi/geth's tx validation (ValidateSignatureValues,
homestead=true) REJECTS high-S signatures, so the anchor's MPC-signed self-tx
failed on submit with 'invalid sender' (live: POST /v1/admin/treasury/anchor ->
status error, note 'submit: send tx: invalid sender'). recoverableSig now
canonicalizes s to N-s when it exceeds N/2 before searching the recovery id, so
the 65-byte r|s|v it hands tx.WithSignature is EIP-2-valid and recovers to the
treasury MPC wallet. Tests: TestRecoverableSig_LowSNormalization (forced high-S ->
low-S, still recovers). go test ./clients/wallets/... green; cmd/cloud builds.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 06:25:30 -07:00
hanzo-dev c25f7429e7 test(controlplane): re-red — lock double-write closure as full-ceremony invariant
Adversarially verify blue's class-A fixes hold under op COMPOSITION inside a
single block (which the original red suite exercised only as separate blocks or
single ops). Six hostile compositions — bare reassign, release+reassign,
release+assign, membership-remove+reassign, remove+release+assign, assign-steal
— are each refused end-to-end through the N=7 ceremony, and the live writer is
unchanged across every voter with its lease mirror consistent. Plus: the
authorized proven-dead handoff stays single-valued under redundant reassigns,
and assign+release of a fresh resource leaves no orphan writer (mirror desync
would be a second authority). GO: the double-write class is fully closed.
2026-07-08 06:09:40 -07:00
b472f8a609 fix(wallets): retry Safe createWallet on 'vault not found' (ring commit-after-response race) (#179)
The ring's :8081 commits a newly-created vault to its DB AFTER writing the
createVault 201 response, so cloud's back-to-back createVault->createWallet (fired
microseconds apart on one keep-alive connection) races the commit and read-misses
the just-created vault -> 404 'vault not found' -> custody=safe 502. A slower
client (curl, separate processes) never observes the gap, which is why manual
repro succeeded. Bounded retry (6x, linear 250ms backoff, ctx-aware) on exactly
that 404; every other error still fails fast. Idempotent per attempt (fresh body).
go build ./cmd/cloud green; go test ./clients/wallets/... green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 05:02:46 -07:00
ec1ac4d040 treasury: bind the reserve MPC wallet as the on-chain anchor signer (#63) (#178)
Wires the #162 BindAnchorSigner seam to a real quorum signer. New:
- wallets.TreasuryAnchorSigner(org,chain): resolves-or-provisions the org's stable
  KindTreasury wallet on the ring (reserved account 'treasury' / wallet
  'reserve-anchor', idempotent) and returns its EVM address + a sign closure.
- The closure produces an EVM-recoverable r‖s‖v signature: the ring returns a bare
  r‖s (64B, no recovery id) but tx.WithSignature needs 65B, so recoverableSig finds
  the v whose recovery yields the wallet address (fails closed otherwise).
- POST /v1/admin/treasury/bind-anchor (global-admin): calls TreasuryAnchorSigner +
  BindAnchorSigner, so subsequent /v1/admin/treasury/anchor commits the ledger root
  signed by the treasury MPC wallet, not the lone KMS key. Returns the bound address
  (fund it for gas on the Hanzo L1).

Tests: TestRecoverableSig (both parities recover to the signer) + _NoMatch (fail
closed). go build ./cmd/cloud green; go test ./clients/wallets/... green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-08 04:37:06 -07:00
zeekayandClaude Opus 4.8 5c937cf046 fix(o11y): restore the missing metrics-query companion — unbreak the cloud build
The o11y-scope landing added clients/o11y/{scope,status}.go referencing a metrics-
query layer (vmClient, newVMClient, promLabel, metricsQuery, queryMetrics,
metricsResult, metricPoint, usageRollup, boundRangeMinutes) whose source file was
never committed → `go build ./cmd/cloud` failed (undefined symbols), taking the
whole deploy plane down (no new cloud image buildable from main). Restore the file
to the surface's own honest-empty contract: newVMClient reads O11Y_VM_URL and an
unset/unreachable VM degrades every query to an honest-empty series (never a
fabricated point); status.go's VM up-inventory works when VM is wired. queryMetrics
returns the honest-empty RED series until the VM query_range wiring lands. Full
`go build ./cmd/cloud` now links; go test ./clients/o11y passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 04:31:12 -07:00
hanzo-devandGitHub 34f1e40458 chore(deps): hanzoai/ai v1.800.10-pre -> v1.802.0 (auto-routing defaults + decision collection) (#177)
Brings the embedded ai subsystem up to v1.802.0:
- #76 opt-in auto-routing (virtual auto/zen-router model, X-Routed-Model)
- #77 per-org enable/disable (OrgSettings precedence)
- #78 admin-settable defaults (reserved "*" row, /v1/get-routing-defaults)
  + RoutingEvent collection (no prompt text) + /v1/export-routing-ledger

Edge contract unchanged; auto_routing_billing_test green against the new
module (ok github.com/hanzoai/cloud). Pre-existing clients/o11y compile
break on main is untouched (fix lands separately).
2026-07-07 23:31:08 -07:00
hanzo-devandGitHub 762c60ec84 refactor(auto): decomplect — remove the /v1/auto reverse-proxy + clients/auto (#176)
Kill the second automation surface. /v1/auto was a per-org reverse proxy
(clients/auto + clients/auto/proxy) to the standalone hanzoai/auto engine
(auto.hanzo.svc) — a duplicate of the native, in-process /v1/automations
Connectors+Automations engine (clients/automations, cloud.EmbeddedTasks,
706-piece catalogue). One engine, one surface: /v1/automations is the ONE
native automation engine. The external engine + its console link-out are
retired (console + universe in paired PRs).

- Remove the order-140 blank import of clients/auto from subsystems.
- Delete clients/auto/ (auto.go + proxy/).

No functional loss: /v1/automations already serves flows/versions/runs/
pieces/MCP natively. clients/kb keeps its own AUTO_UPSTREAM piece-runner
coupling (a separate, pre-existing bridge to a never-implemented engine
endpoint) — reported for a follow-up, not touched here.

go build ./... green, go vet green, go test ./clients/automations + root ok.
2026-07-07 23:11:43 -07:00
b2c9300140 refactor(automations): rename connector catalogue pieces -> connectors (HIP-0126) (#174)
* refactor(automations): rename connector catalogue pieces -> connectors (HIP-0125)

The automations connector CATALOG surface drops the ActivePieces term "pieces" for the ONE Hanzo term "connectors":

- GET /v1/automations/pieces -> /v1/automations/connectors; /pieces kept as a
  byte-identical back-compat alias (same handler) so live clients never break.
- Catalog{PieceCount,Pieces} -> {ConnectorCount,Connectors}; PieceMetadata/
  PieceAuth/PieceAction/PieceTrigger -> Connector*; JSON tags pieceCount/pieces
  -> connectorCount/connectors; embedded catalog.json + OpenAPI updated to match.
- Test proves the /pieces alias mirrors /connectors byte-for-byte.

Deliberately UNCHANGED (persisted @xyflow builder wire contract; renaming would
break live clients + stored flows): the flow-step protocol PieceName/pieceName,
PIECE/PIECE_TRIGGER, corePiece. Aligning those is a staged migration (HIP-0125).

* chore(automations,git,framework): scrub AI-slop placeholder comments (Rob Pike pass)

Comment-only, zero behavior change. Removes agent-note narration and future-work hedges, keeps the real WHY:
- automations.go: drop "a separate agent later OVERWRITES this file" narration; keep the Catalog-is-the-wire-contract invariant.
- framework/naming.go: "value for now" -> "value derived from now" (it reads the now arg, not a hedge).
- git/git.go: drop TODO(billing) + "in the MVP" hedge; state the git.usage meter fact.
- git/storage.go: drop TODO(vfs)/MVP/follow-up narration; keep the WHY osfs (not vfs) is used (vfs.FS does not implement go-billy).
Kept as real WHY/invariants (not slop): connector_core.go loopback-test SSRF guard, connector_slack.go httptest override, affiliates/store.go  sentinel + PendingCents; types.go was already cleaned in the rename commit.

* docs(automations): point connector-rename references at HIP-0126 (0125 was taken)

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 23:01:24 -07:00
acfa8d8597 feat(cloud): kill the /v1/auto ActivePieces reverse-proxy — one native engine (#175)
CTO decision: ONE automation engine = the native Go /v1/automations
(clients/automations on cloud.EmbeddedTasks). This removes the redundant
/v1/auto reverse-proxy subsystem (clients/auto), a per-org proxy to the
standalone ActivePieces Deployment (auto.hanzo.svc).

- delete clients/auto/ (auto.go + proxy/)
- drop the order-140 blank import from subsystems.go

Safe: no live caller of cloud/v1/auto — console link-outs to auto.hanzo.ai,
and clients/kb calls the engine directly via its own AUTO_UPSTREAM client
(untouched here). The native /v1/automations surface is unaffected.

NOTE (does NOT retire the ActivePieces Deployment): clients/kb/sync_piece.go
still executes connector pieces via the engine at /v1/auto/pieces/{piece}/run;
the native engine exposes the piece CATALOGUE but not piece EXECUTION yet, so
auto.hanzo.svc must stay until native reaches piece-run parity.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 22:51:02 -07:00
a2f519e95f chore: cut AI-slop comment narration (Rob-Pike pass) (#173)
Comment-only tightenings, zero behavior change:
- pubsub/o11y: drop the misleading "GC won't collect" narration on the
  package-level server/collector refs; state the real reason (shutdown
  reachability) or the actual invariant (metrics ref is a write-only keepalive).
- iamsvc: condense the 11-line InitEmbed block that verbatim-restated the
  package doc down to the fail-closed WHY that matters at the call site.

No code changed (git diff: comments only).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 22:50:59 -07:00
be8012b048 fix(wallets): Safe custody must create the MPC wallet via the ring PRODUCT API (#172)
Safe deploy (POST /v1/wallets/{id}/smart-wallet) resolves the owner wallet by its
db.Wallet PRIMARY KEY (orm.Get). The :9800 internal /keygen mints a threshold key
but persists NO db.Wallet row, so deploy 404'd 'wallet not found' (live: every
custody=safe create -> 502). The ring's Safe surface is VAULT-scoped: the only
create path that persists a db.Wallet AND returns its id is
POST /v1/vaults/{id}/wallets.

safeCustody.Provision now: createVault -> createWallet (vault-scoped, returns db
id + internal WalletID + EOA) -> deploySafe(dbId). KeyRef stays
<internalWalletId>|<smartWalletId> (owner-sign via :9800 uses the internal id;
propose via :8081 uses the smart-wallet id); the db id is only needed for the
one-time deploy. safeclient gains createVault + createWallet; the stub test now
emulates the vault/wallet-create routes. go test ./clients/wallets/... green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 22:11:00 -07:00
72cf87e4db feat(usage,audit): org-scoped usage summary + audit trail endpoints (#171)
Add two org-scoped cloud-api surfaces for the enterprise console:

- /v1/usage/summary (clients/usage): the org's unified footprint roll-up —
  spend by category over time + wallet (from the commerce ledger) plus LLM
  usage totals (from the warehouse). Composes existing sources server-side;
  each degrades independently to honest zeros with a source marker. Org from
  the validated bearer only (principal.Tenant); a forged X-Org-Id with no
  principal 401s and never reaches commerce.

- /v1/audit (clients/auditlog): the per-org twin of the admin god-view — an
  org admin reads ONLY their own org's events off the SAME tamper-evident,
  hash-chained store. Org PINNED server-side (a client ?org is ignored);
  filters time/actor/action/resource/resourceId/result + pagination.

- audit: extract the shared audit.Wire projection (used by both the admin and
  org routes, one JSON contract) and add a ResourceID filter to audit.Query.

Tests: usage (pure roll-up/categorization + HTTP scoping/honest-zeros),
auditlog (real in-memory recorder: scope isolation, filters, pagination,
401/501), audit (ToWire + ResourceID). CGO_ENABLED=0 go build + go test green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 22:06:00 -07:00
hanzo-dev 0153f9a665 fix(controlplane): close the release+assign double-write sibling
Reviewing my own displacement fix adversarially: red tested release+reassign,
but a standalone release of a LIVE holder was still admitted, and after it the
shard is unowned — so release(victim) at H then assign(attacker) at H+1 puts a
second live writer on the shard (same class, pure policy, survives real crypto).

Fix: a LIVE holder's lease is immutable — releasable only when the holder is
proven dead (ErrUnauthorizedRelease), symmetric with reassign. Closes the whole
double-write class, not just red's two tested paths. + TestPolicy_ReleaseLiveHolderRefused;
TestRSM_DeterministicConvergence now marks the holder proven-dead (out-of-band)
before releasing. Suite green.
2026-07-07 22:02:16 -07:00
5b5df8fc8a clients/world: GDELT + allowlisted-RSS news data plane (/v1/world) (#169)
* treasury: anchor signs through a quorum-gateable seam, not a lone key

anchor_evm.go held the signer's private key in-process and did types.SignTx.
Decouple WHERE the key lives from the tx builder via a txSigner seam:

- keySigner  — the existing local KMS-provisioned key (default; unchanged result,
  proven byte-identical to types.SignTx).
- mpcSigner  — delegates the 32-byte EVM signing hash to a quorum-gated custody
  backend (the reserve's 3-of-5 treasury MPC wallet), bound via BindAnchorSigner
  (the finance seam). The bound signer wins over any local key.

submit() now hashes the tx, delegates the hash to the resolved signer, and
applies the recoverable signature — agnostic to single-sig vs threshold. Fails
closed when neither signer is available (never fabricates a signature).

Test proves both paths recover to the correct sender and the quorum signer is
invoked exactly once; the live ring is a config swap.

* feat(gpu): BYO-GPU worker uploads render outputs to the org gallery

After studio.render completes on the local GPU, the worker fetches each finished
output from the local studio (/view) and POSTs it to the org studio's /upload/output
with the user's IAM bearer — landing it in orgs/{org}/output (S3-mirrored to the
gallery). No S3/rclone credentials ever touch the box; the session token is the only
credential. Upload target resolves from input.uploadUrl, then HANZO_STUDIO_UPLOAD_URL,
then studio.hanzo.ai. Proven end-to-end against studio 0.14.9 (aud hanzo-console).

* feat(gpu): per-machine share policy — advertised on the fleet record, enforced at claim

A linked GPU can be shared to specific orgs/projects/job-types/models with limits via
ONE policy object on the machine record (SharePolicy). It rides in the fleet
registration (input.policy) and is enforced ONCE, at claim: a job outside the policy
is failed back so an eligible worker takes it. nil/zero policy = fully permissive
(unchanged behaviour). Loaded from HANZO_GPU_POLICY (inline JSON) or
HANZO_GPU_POLICY_FILE. Unit-tested (reject matrix + loader).

Server-side multi-org queue fanout + metering-to-org+project remain follow-ups; the
worker enforces its own policy today (workers still claim their own org's queue).

* feat(world): GDELT + allowlisted-RSS news data plane (clients/world)

First vertical slice of the World news backend in the unified cloud binary:

  GET  /v1/world/news       merged, filtered, freshest-first feed  -> {items:[…]}
  GET  /v1/world/pipeline   per-(org,project) pipeline config
  PUT  /v1/world/pipeline   upsert feeds + keyword/region/source filters
  GET  /v1/world/stream     SSE live refresh (ZAP-native, org+project scoped)

- Ports world/api/{gdelt-doc,rss-proxy}.js: GDELT 2.0 Doc artlist + host-
  allowlisted RSS/Atom (~180-domain SSRF allowlist, enforced at PUT boundary,
  at fetch time, and on redirect targets).
- Org/project isolation on every path (principal.Tenant/Project); SQLite
  pipelines table PK(org,project); in-memory TTL feed cache (10m).
- RegisterWithShutdown order 142; one blank-import line in subsystems.go.
- Tests: httptest-stubbed upstreams (deterministic/offline) + live-verified.

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 22:00:29 -07:00
hanzo-dev 2b46815e88 harden(controlplane): quorum-safety assertion, honest cert-verify, domain-sep commit
Follow-up rails from the red pass + the cryptographer audit (all on top of the
class-A fixes):
- checkQuorumSafety(N,quorum,f) asserts N>=3f+1, quorum>=2f+1, 2q>N+f at cluster
  construction (fail closed). The 2q>N+f margin at N=7 is exactly 1 and is the
  whole basis of the no-fork property, so a future sizing change can never
  silently break safety. + TestSafety_QuorumParametersAreByzantineSafe.
- verifyOwnCertStructure: renamed the driver's structural self-composed cert
  check away from 'independent triple-gate verification' and documented that an
  external cert must go through the cryptographic VerifyUnderPolicy (increment-2),
  never this structural path (red #8).
- commitZ: domain-separate the z-share commitment by session + party
  (H(cp-commit||sid||party||z)) so a commitment cannot be replayed across
  sessions/parties (red #4 hardening).
- doc.go: record the red->blue outcome (no-fork core held; 4 class-A closed), the
  CLASS-B caveat (stub secrets are public-seed-derivable -> safety suite meaningful
  only under real crypto), and the increment-2 security worklist (distributed DKG,
  authenticated handoff + KMS fence, RSM-level authz re-verify, external-cert
  crypto verify, CI guard against -tags controlplane releases).

Suite green under -tags controlplane -race; default build unaffected.
2026-07-07 21:58:34 -07:00
hanzo-dev 505539652a fix(controlplane): close red's class-A byzantine findings (blue->red->blue)
Red found a CRITICAL double-write + 3 more class-A breaks (pure orchestration/
policy, survive real crypto) with failing exploit tests. All closed; red's 4
class-A tests now pass without weakening them; class-B (stub-crypto-forgeable)
deferred to the real-crypto increment with explicit t.Skip TODOs.

#1/#2 CRITICAL double-write (policy.go, placement.go): displacement of a LIVE
  shard writer now requires proven-death by out-of-band evidence. A proposer-
  written same-block release authorizes nothing (it is not holder consent), and
  membership removal no longer manufactures proven-dead. Fail-closed increment-1
  posture; authenticated graceful handoff + KMS fence are increment-2.
#3 HIGH barrier forgeable (driver.go, custody.go, signer.go, transport.go):
  Round1 commitments are now proof-of-possession authenticated exactly as Round2
  legs, so one node cannot forge a quorum of spoofed commitments to defeat
  commit-before-reveal.
#4 MEDIUM apply fork gate (rsm.go): RSM.Apply re-checks ParentRoot == the
  applied-state commitment, so a block that does not extend local state can never
  mutate it (defense-in-depth for a future recovery/gossip path).

Corrected TestPolicy_ShardReassign_WithRelease (it asserted the vulnerable
same-block-release-authorizes-displacement behavior) to assert the fix. Updated
rsm_test blocks to extend state properly (the new parent-root gate). Suite green
under -tags controlplane; default build unaffected (package is tag-gated).
2026-07-07 21:54:35 -07:00
f1b5ca8d05 wallets: add Safe (Gnosis-Safe) smart-wallet custody over the luxfi/mpc ring (#62) (#168)
New KindSafe custody composes the ring's TWO planes without importing luxfi/mpc:
- :9800 internal threshold API (mpcclient) — keygen the owner MPC EOA + owner-sign
- :8081 product API (new safeclient) — CREATE2 Safe deploy + EIP-712 Safe-tx propose

safeclient.go mints a SHORT-LIVED HS256 ring JWT (iss=mpc.lux.network, aud=mpc-api,
role=admin, org-scoped) hand-rolled (crypto/hmac, no jwt dep) from the ring's
MPC_JWT_SECRET — resolved from cloud's in-process KMS via
CLOUD_WALLETS_MPC_JWT_SECRET_REF, NEVER a plaintext env value. The deploy route is
role-gated (owner|admin), so role=admin clears it.

safeCustody.Provision: keygen (owner EOA) -> deploy Safe(owners=[EOA], threshold=1)
on the wallet's EVM chain (per-wallet, default Hanzo L1 36963); KeyRef encodes both
ring handles (<mpcWalletId>|<smartWalletId>); Address = predicted Safe contract.
Sign: owner-approval signature via :9800 (uniform /v1/wallets/:id/sign). New route
POST /v1/wallets/:id/safe-tx composes the ring propose (EIP-712 MPC-sign) via a
safeProposer capability type-assert (no Kind switch). Fails closed
(ErrMPCNotConfigured) until CLOUD_WALLETS_MPC_API_ADDR + the JWT secret are wired.

Tests: TestSafeCustody drives a stub emulating both ring planes (asserts the minted
JWT is HS256-valid with correct iss/aud/role/org) + TestSafeCustody_FailClosed.
go test ./clients/wallets/... green; CGO_ENABLED=0 go build ./cmd/cloud green.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 21:45:19 -07:00
77ebb17c3b cloud: register /v1/wallets subsystem + unblock main (Config.Role collision) (#167)
Two coupled changes so main builds green AND the MPC custody surface is live:

1. Fix the broken build on main. #160 (CLOUD_ROLE writer/reader HA split) and
   #163 (Stage-0 control-plane inert config) each added a `Role` field to the
   SAME Config struct on separate branches; the merge left Config.Role
   redeclared (role.Role vs string) + a duplicate struct-literal key, so
   `go build ./cmd/cloud` failed (release lane stuck at v1.786.124). Rename the
   inert #163 field to ControlPlaneRole (env ROLE, consumed by nothing yet). The
   HA Role (role.Role, CLOUD_ROLE, used by serve.go/build.go) is unchanged.

2. Register the wallets subsystem. clients/wallets (#151/#161) was never blank-
   imported into subsystems.go, so its init() never ran and /v1/wallets was
   unrouted (404) despite the code shipping. Add the order-127 blank import so
   the accounts/wallets/custody/keys/sign surface mounts — KMS custody always
   on; mpc/treasury fail closed until CLOUD_WALLETS_MPC_ADDR +
   CLOUD_WALLETS_MPC_API_KEY_REF are wired. This is the seam the treasury anchor
   (#162 BindAnchorSigner) binds through.

Verified: CGO_ENABLED=0 go build ./cmd/cloud green; wallets + config tests ok;
local boot logs 'wallets mounted' (defaultCustody=kms) then 'listening', no panic.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 21:03:30 -07:00
hanzo-dev 2a00823fdc feat(controlplane): Stage-1 increment-1 byzantine ceremony driver + harness
FULL-BFT byzantine ceremony driver for the cloud control plane, built
against published luxfi interfaces (consensus v1.35.30 protocol/quasar +
protocol/quasar/pulsar PulsarRoundSigner, pulsar v1.9.0 pkg/pulsar). Behind
the controlplane build tag, NOT wired into serve.

- Real PulsarRoundSigner drives Round1/Round2/Finalize (canonical
  non-grindable nonce, canonical signer set, z aggregation, ConsensusCert).
- Ceremony driver over an abstract Transport: proposer -> per-voter Round1
  commitment -> ALL-Round1 barrier -> Round2 share -> >=2/3 legs -> compose
  triple-PQ QuasarCert -> independent QuasarCert.Verify -> fail-secure apply.
- One-pod-one-share custody; policy gate refuses invariant-violating blocks
  (shard-writer reassign without lease-release/proven-dead predecessor).
- In-process N=7 harness: happy path, liveness (drop2 finalize / drop3 SAFE
  HALT), safety (equivocation, one-pod-two-shares, rushing, dup/rogue legs).

Stubbed for later increments (drop-in seams): ZAP transport, KMS share
custody, NonceMPC pool, DKG keygen, and pulsar's unshipped SignatureCore +
PartialZVerifier crypto cores + ComposePolaris cert composition.

Supersedes PR #163 classical pins: drops the bft promotion.
go build/vet/test green (CGO_ENABLED=0); race-clean.
2026-07-07 18:15:28 -07:00
hanzo-dev eb829a3102 fix(config): resolve Role field collision from concurrent merge
Two PRs landed on main that both added a Config.Role field — the #160
HA writer/reader role (role.Role, load-bearing in Serve) and the Stage-0
control-plane role (string). The text-merge compiled to a duplicate field
and broke the default build. Rename the inert control-plane field to
ControlPlaneRole (env ROLE unchanged); the HA Role keeps its name and all
cfg.Role.IsReader()/String() consumers are untouched.
2026-07-07 18:12:41 -07:00
hanzo-devandGitHub db5bd0f4c6 feat(cloud): CLOUD_ROLE writer/reader HA split + de-alias ZapDB + writer-pin seam (#160)
* refactor(kms): de-alias badger→zapdb (the embedded store IS ZapDB)

clients/kms/kms.go imported the store as `badger "github.com/luxfi/zapdb"`.
The store is luxfi/zapdb — the canonical Lux embedded KV, a hardened Badger
fork whose Go package is still literally `package badger`. The alias made call
sites read like raw dgraph-io/badger. Rename the alias to `zapdb` so every call
site is self-documenting; behaviour is byte-identical (same package, same API).

Confirms the invariant: `grep -rn dgraph-io/badger` across cloud = 0. There is
no raw Badger anywhere; the one embedded store is ZapDB.

* feat(cloud): CLOUD_ROLE writer/reader split + read-only KMS reader + writer-pin

Introduces an explicit HA role so read replicas can be added WITHOUT ever
risking a second writer opening the RWO stores. Default is byte-identical to
today: unset CLOUD_ROLE ⇒ Writer ⇒ the single pod that owns the RWO PVC.

- role: CLOUD_ROLE ∈ {writer(default), reader}. Serve fails CLOSED on an
  explicitly-invalid value (a wrong guess demotes the real writer or risks a
  second one). Pure, tested, imports nothing from cloud.
- kms: Config.ReadOnly opens the ZapDB store READ-ONLY with the lock guard
  BYPASSED — a reader serves secrets off a restored replica and NEVER takes the
  exclusive write lock (the mechanism proven safe by luxfi/zapdb's
  WithReadOnly + BypassLockGuard; zapdb-replicate uses the same to coexist with
  a live writer). Reader with no restored store / no key fails closed. Tested
  round-trip: writer writes → reader reopens read-only → reads back; reader
  writes rejected.
- writerpin: the single-writer election seam. SingleWriter (production-correct
  for StatefulSet replicas:1) is the default; ConsensusPin (Quasar leaderless
  election) is an HONEST stub that fails closed with ErrNotImplemented rather
  than fabricating a pin. Tested.
- wiring: Serve resolves+logs the role and the backing pin; pickKMSClient opens
  KMS read-only for readers. Writer path unchanged.

NOT YET wired (reported for Red/CTO): consensus election (writerpin gates no
store-open yet — k8s guarantees the single writer); reader gating of the
audit chain / durable tasks / per-tenant SQLite (still open writable) — the KMS
reader path is the completed slice. Data replication runs as sidecars at the
manifest layer (hanzoai/replicate for SQLite, luxfi/zapdb-replicate for ZapDB),
not via in-process import.

* feat(ha): fail-closed reader write-guard + prove in-process KMS backup

ReaderGuard: one boundary middleware rejects mutating verbs on a Reader
(405), gating EVERY store (KMS+audit+tasks+SQLite), not just KMS's
read-only open — a mis-routed write can no longer silently persist to a
reader's ephemeral dir and vanish on restart (H4). No-op on a Writer.

replication_test: real *zapdb.DB writer streams incremental age-encrypted
db.Backup blocks WHILE live; reader Restores into its OWN separate dir —
refutes the C1 'second-process open fails' path and proves the producer.
Fail-closed test: no recipient => no block (never plaintext to S3).

* test(ha): reader-guard verb matrix + replication edge cases

ReaderGuard: GET/HEAD/OPTIONS reach the store, POST/PUT/PATCH/DELETE all
405 without reaching it; Writer path (guard unmounted) serves every verb.
replication: wrong-identity restore fails closed; restore requires manifest
+ identity (unhydrated store never serves empty); repeated/no-op/overwrite
backups restore to the exact latest value (chain-correctness invariant).

* test(config): align IAM single-replica test with staged-subsystem contract

The 'empty list -> iam-enabled' subtest predates IAM becoming a STAGED
subsystem (stagedSubsystems["iam"]=true): the empty-Enable mount-all
default deliberately does NOT mount IAM (it corrupts the shared Beego
global and crashes `ai` with SQLITE_CANTOPEN). So empty list is
iam-DISABLED and >1 replica is allowed; the guard fires only when iam is
EXPLICITLY enabled. Code was correct; the test asserted the pre-staging
behavior. Pre-existing red on main, unrelated to the HA change.
2026-07-07 17:55:06 -07:00
hanzo-devandGitHub 14782628ad feat(cloud): Stage 0 — control-plane deps + inert config (#163)
Promote the luxfi consensus stack (consensus v1.25.15, bft v0.1.5,
p2p v1.21.1, validators v1.2.0) from indirect to direct requires, and add
four INERT control-plane config fields. Zero behavior change, reversible.
Deps + inert config only — no engine imported/started, no routes, no
serve.go/build.go behavior change.

v1.25.15 is the minimal clean tag: it already carries NewBFT (consensus.go:168)
+ engine/bft, its graph pulls validators v1.2.0 (Manager), it requires exactly
pulsar v1.1.1 (which stays v1.1.1 — zero drift), and it is the MVS-selected
version, so promotion is a no-op to the compiled graph. A lower tag would
downgrade the whole build's consensus (behavior change); a higher tag drifts
pulsar + consensus code.

The four are held direct by controlplane_deps.go: blank imports behind the
never-set //go:build controlplane_deps tag, so nothing links into the binary.
go mod tidy keeps them direct (it reads all build tags); deleting the file
reverts them to indirect. NodeID/Peers/Role/ControlPlaneQuorum parse in
LoadConfig (NODE_ID/PEERS/ROLE/CONTROL_PLANE_QUORUM) but no subsystem reads them.

Architecture direction (proposed, not shipped): the control plane is designed
to run Quasar (post-quantum BFT, protocol/quasar Submit->Finalized) under a
strict-PQ cert profile with a Pulsar RoundSigner threshold signer.

tidy also corrected pre-existing drift on main (nats-io/nats.go indirect->direct
via clients/kafka/interop_test.go; pruned 7 superseded go.sum lines) — verified
identical on pristine origin/main.
2026-07-07 17:55:03 -07:00
hanzo-devandGitHub 9106c15b71 fix(cloud): correct luxfi/precompile go.sum hash + ZAP-only telemetry (drop plaintext OTLP fallback) (#165)
Red review findings:
- go.sum: luxfi/precompile v0.5.37 zip hash disagreed with sum.golang.org
  (h1:Yh3dJ+... vs authoritative h1:2v0z...) → cold-cache CI SECURITY ERROR.
  Corrected to the sumdb-vouched hash.
- telemetry.go: remove the plaintext OTLP-HTTP fallback (newTraceExporter) that a
  stray/standard OTEL_EXPORTER_OTLP_ENDPOINT could use to silently downgrade
  tenant-carrying trace spans to cleartext. ONE wire now: ZAP. Dropped the
  otlptracehttp import (also severs its transitive grpc pull) and the dead
  otlpEndpoint parameter. OTLP stays only the collector's interop receiver.
2026-07-07 17:54:54 -07:00
hanzo-devandGitHub 36ef38d08d test(billing): prove auto-routing bills as the resolved model at the edge (#166)
The ai subsystem serves a virtual `auto`/`zen-router` model that resolves to a
concrete model id before pricing/billing, meters its own token cost keyed on the
SERVED model, and reports it via the X-Routed-Model header. The cloud edge prices
/v1/ai/* by PATH (0, self-metered), never by the request model, so `auto` bills
as whatever it resolved to — and the edge passes X-Routed-Model through untouched.

- auto_routing_billing_test.go: TestAutoRoutingBillsAsResolvedModel (edge does not
  double-bill /v1/ai/* + header pass-through) and TestDefaultPriceAiPathModelAgnostic.
- AUTH_BILLING_CONTRACT.md §4a: document the binding.

No code change needed — cloud already meters ai from the subsystem's own usage
record (which keys off the resolved request.Model), so the edge binds correctly.
2026-07-07 17:52:02 -07:00
2f5d164b7d zaptrace: encode OTLP via zap2pb; drop direct google.golang.org/protobuf (#164)
Route ExportTraceServiceRequest wire encoding through github.com/zap-proto/zap2pb
(the sanctioned ZAP<->protobuf boundary) instead of importing
google.golang.org/protobuf {proto,encoding/protowire} directly. Wire bytes are
byte-identical (repeated ResourceSpans under field 1); TestUploadTracesOverZAP
still decodes the spans over the real ZAP transport.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 17:28:07 -07:00
2642264ceb treasury: anchor signs through a quorum-gateable seam, not a lone key (#162)
anchor_evm.go held the signer's private key in-process and did types.SignTx.
Decouple WHERE the key lives from the tx builder via a txSigner seam:

- keySigner  — the existing local KMS-provisioned key (default; unchanged result,
  proven byte-identical to types.SignTx).
- mpcSigner  — delegates the 32-byte EVM signing hash to a quorum-gated custody
  backend (the reserve's 3-of-5 treasury MPC wallet), bound via BindAnchorSigner
  (the finance seam). The bound signer wins over any local key.

submit() now hashes the tx, delegates the hash to the resolved signer, and
applies the recoverable signature — agnostic to single-sig vs threshold. Fails
closed when neither signer is available (never fabricates a signature).

Test proves both paths recover to the correct sender and the quorum signer is
invoked exactly once; the live ring is a config swap.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 16:30:19 -07:00
8a5e5f97bd wallets: reconcile mpc custody to the ring's internal threshold API (#161)
The prior mpcclient targeted a DECIDED-but-nonexistent dashboard route tree
(/v1/wallets/{id}/sign, /v1/treasury/*) authed with a hand-minted HS256 JWT.
The deployed luxfi/mpc ring's real, working server-to-server custody surface is
the internal threshold API (cmd/mpcd/main.go, :9800): POST /keygen + POST /sign,
gated on the static MPC_INTERNAL_API_KEY bearer token — the exact contract the
ring's own /sign handler documents for a custody adapter.

Reconcile cloud to that contract:
- mpcclient.go: keygen + sign over the internal API; static bearer key (KMS),
  no JWT/dependency; deterministic idempotency key per (org,wallet,digest).
- custody.go: mpc + treasury provision via keygen, sign via /sign with the
  wallet's EVM chain id; Rotate preserves the address (ring-managed shares).
  Treasury quorum governance moves to the finance policy layer over this same
  primitive (no separate ring route).
- wallets.go: CLOUD_WALLETS_MPC_API_KEY_REF (KMS ref of the bearer key).
- test: stub emulates the internal /keygen+/sign contract.

Feature-flagged: unset CLOUD_WALLETS_MPC_ADDR ⇒ mpc/treasury fail closed.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 16:20:12 -07:00
a126b2f53f feat(billing): populate per-product usage axis + server-side ?product=/?groupBy=product (#159)
The console per-product Metrics dashboard groups usage on metadata.product /
metadata.agent, but commerce RecordUsage persists only provider/model (no product
field), so the breakdowns rendered honest-empty even though every non-LLM product
already meters+gates per-org via ResourceMeter (provider=<product>, default fee
$1.00, fail-closed 402 on zero balance).

clients/billing/usage.go is the ONE read-side adapter: usage() injects a canonical
metadata.product onto each ledger row (agent->agents, provisioning->kind,
token-metered->inference, else provider) from the SAME charged ledger, and honors
the previously-ignored ?product=<id> (server-side filter) and ?groupBy=product
(per-product spend rollup {product,requests,amountCents}). A row already carrying
metadata.product/agent wins, so it degrades to a no-op once the meter/commerce
persist them natively (forward-compatible).

No change to what is charged or gated; the balance floor stays enforced by default.
scopedBillingQuery is extracted so proxy() and usage() build the subject boundary
one way. AUTH_BILLING_CONTRACT.md documents coverage + the native-field checklist.

Tests: productOf table + enrich/filter/group units + handler-level ?product= /
?groupBy=product through the real route (33 billing tests green).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 16:11:54 -07:00
4c01e7727c feat(cloud): embed the REAL hanzoai/console bundle; fail-hard Dockerfile (#158)
The console image stage now FAILS the build when build:embed does not emit a
real static bundle (non-empty out/index.html + out/_next), instead of silently
degrading to the committed fallback shell. A broken console export can no longer
ship the placeholder to prod. Escape hatch: --build-arg ALLOW_PLACEHOLDER=1 for
a pure-Go dev image with no Node console.

hanzoai/console build:embed produces a real 7.7M static export (361KB index.html
+ 4.3M _next chunks); //go:embed bakes it into the ONE cloud binary. Also drops
the last console2 references (repo is hanzoai/console).

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 15:52:57 -07:00
hanzo-dev 4718ce2ff9 Merge branch 'feat/addon-fast-follows' 2026-07-07 15:11:12 -07:00
hanzo-dev 90bd8fda19 cloud: rename console2→console (one canonical name)
The frontend repo is hanzoai/console (console2 was renamed away). Kill the
dead name across the build path + source so there is one name, one way:
- Dockerfile: clone hanzoai/console.git; ARG CONSOLE_REPO / CONSOLE_REF
- Makefile: CONSOLE_DIR; webui + build-standalone targets
- config.go: drop dead console2.hanzo.ai from the ZAP-WS origin allowlist
- comments across clients/* reference the console repo + its TS modules by
  their real name

No behavior change beyond dropping one unused CORS origin. Root pkg builds.
2026-07-07 15:11:09 -07:00
hanzo-devandGitHub 993e556a4c provisioning: Red low fast-follows (rollback orphan-key, kv-auth + envtest proofs, datastore tag) (#156)
Red review = SHIP; these close the 4 cloud-side low findings so the PR lands
with no known edges.

low-1 (rollback atomicity): createDedicated's inject-failure branch now calls
  removeAddonURL BEFORE tearing the backend down. injectAddonURL is not atomic —
  a strategic-merge PATCH can LAND server-side yet still return err (dropped
  response / post-commit timeout); scrubbing the maybe-written <KIND>_URL first
  means a committed-but-errored inject can't leave the instance pointing at a
  deleted backend (a dangling DSN is worse than Base). Proven by
  TestDedicated_InjectPartialWriteRollsBackOrphanKey (fake now models the
  write-then-error partial failure; asserts inject THEN remove ran, key gone).

low-2 (kv fail-open corner): TestDedicatedKV_RequirepassEnforced boots the REAL
  ghcr.io/hanzoai/kv image with the exact engine.args + mounted requirepass
  config and asserts an UNAUTHENTICATED PING is REJECTED, then that default:<pw>
  authenticates — locking down the one corner where, if the image ignored the
  positional config, the instance would boot unauthenticated. Raw RESP over TCP
  (zero new client deps); gated on CLOUD_KV_SMOKE_IMAGE + docker so the default
  suite stays green, real in CI.

low-3 (strategic-merge sibling preservation): TestPatchAddonSecret_RealAPIServer
  runs the ACTUAL k8sOrchestrator addon methods against a REAL kube-apiserver
  (controller-runtime envtest) — inject KV_URL then SQL_URL => BOTH survive in
  .data; RemoveAddonSecretKey drops one, keeps the other; idempotent on absent
  key/Secret. Replaces the fake orchestrator's assumption with a server-proven
  fact. Gated on KUBEBUILDER_ASSETS (skip without envtest binaries). Adds
  controller-runtime v0.23.3 as a TEST-ONLY dep — pinned to the release that
  keeps k8s.io at v0.35.3 (NO production client-go bump).

low-4 (datastore tag symmetry): dedicated datastore image tag floating ':26' ->
  env("CLOUD_DEDICATED_DATASTORE_TAG", "26.2.3.2"), symmetric with sql/kv/docdb.
  A floating ':26' resolves to whichever datastore lineage (bridge vs fork, distinct
  data dirs) last pushed under it — a per-org instance must boot a deterministic
  image.

go build ./... green; go test ./clients/provisioning/... green (envtest PASS
against a live apiserver, kv-smoke skips without docker).

(cherry picked from commit 04d841c4906b58fa06b1bc407b55c97e6661f169)
2026-07-07 14:50:18 -07:00
963263a2f4 feat(o11y): wire native datastore metrics ingest into the embedded runtime (#157)
* feat(o11y): wire native datastore metrics ingest into the embedded runtime

Bumps hanzoai/o11y to the native datastore metrics driver and starts an
in-process ZAP metric receiver (clients/o11y/metrics.go) that writes metrics to
the datastore over upstream ch-go via o11y/pkg/datastoremetrics — no histogram
fork. Reuses the embedded runtime.TelemetryStore.ClickhouseDB() connection, so
the query plane (read) and metrics (write) share one datastore conn.

Opt-in + fail-soft: gated on O11Y_METRICS_ZAP_LISTEN, a no-op until set, errors
logged and swallowed so metrics ingest can never take the query plane down. This
unblocks retiring the standalone signoz-otel-collector metrics path once verified
(verify-then-cutover). CGO_ENABLED=0 build + vet + existing o11y/observe tests green.

* chore: re-pin o11y@main (native datastore metrics driver merged)

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 14:27:47 -07:00
hanzo-dev c4bf31d865 provisioning: Red low fast-follows (rollback orphan-key, kv-auth + envtest proofs, datastore tag)
Red review = SHIP; these close the 4 cloud-side low findings so the PR lands
with no known edges.

low-1 (rollback atomicity): createDedicated's inject-failure branch now calls
  removeAddonURL BEFORE tearing the backend down. injectAddonURL is not atomic —
  a strategic-merge PATCH can LAND server-side yet still return err (dropped
  response / post-commit timeout); scrubbing the maybe-written <KIND>_URL first
  means a committed-but-errored inject can't leave the instance pointing at a
  deleted backend (a dangling DSN is worse than Base). Proven by
  TestDedicated_InjectPartialWriteRollsBackOrphanKey (fake now models the
  write-then-error partial failure; asserts inject THEN remove ran, key gone).

low-2 (kv fail-open corner): TestDedicatedKV_RequirepassEnforced boots the REAL
  ghcr.io/hanzoai/kv image with the exact engine.args + mounted requirepass
  config and asserts an UNAUTHENTICATED PING is REJECTED, then that default:<pw>
  authenticates — locking down the one corner where, if the image ignored the
  positional config, the instance would boot unauthenticated. Raw RESP over TCP
  (zero new client deps); gated on CLOUD_KV_SMOKE_IMAGE + docker so the default
  suite stays green, real in CI.

low-3 (strategic-merge sibling preservation): TestPatchAddonSecret_RealAPIServer
  runs the ACTUAL k8sOrchestrator addon methods against a REAL kube-apiserver
  (controller-runtime envtest) — inject KV_URL then SQL_URL => BOTH survive in
  .data; RemoveAddonSecretKey drops one, keeps the other; idempotent on absent
  key/Secret. Replaces the fake orchestrator's assumption with a server-proven
  fact. Gated on KUBEBUILDER_ASSETS (skip without envtest binaries). Adds
  controller-runtime v0.23.3 as a TEST-ONLY dep — pinned to the release that
  keeps k8s.io at v0.35.3 (NO production client-go bump).

low-4 (datastore tag symmetry): dedicated datastore image tag floating ':26' ->
  env("CLOUD_DEDICATED_DATASTORE_TAG", "26.2.3.2"), symmetric with sql/kv/docdb.
  A floating ':26' resolves to whichever datastore lineage (bridge vs fork, distinct
  data dirs) last pushed under it — a per-org instance must boot a deterministic
  image.

go build ./... green; go test ./clients/provisioning/... green (envtest PASS
against a live apiserver, kv-smoke skips without docker).

(cherry picked from commit 04d841c4906b58fa06b1bc407b55c97e6661f169)
2026-07-07 14:22:13 -07:00
db991f2520 feat(cloud): embed native PubSub (clients/pubsub :4222) + Kafka adaptor (clients/kafka :9092) — Lux-consensus/no-ZK, disabled-by-default, interop-verified (#155)
Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 14:15:02 -07:00
hanzo-devandGitHub 0af9d16e17 provisioning: uniform on-demand add-on instance binding + <KIND>_URL injection (#154)
Extend the dedicated-instance strategy so all four on-demand data add-ons —
Hanzo KV / SQL / DocDB / Datastore — route through ONE mechanism, and bind an
enabled add-on to an app instance by injecting its DSN as <KIND>_URL into the
instance's addons Secret (disabling reverts to Base).

- store: additive instance column (idempotent ALTER, threaded through Resource/
  cols/scan/Insert) + ListByInstance(org,instance).
- dedicated: add sql (Datastore type=postgresql, POSTGRES_* env, PGDATA subdir)
  and kv (type=valkey, per-instance requirepass via a MOUNTED config Secret since
  the kv-server binary reads no password from env; DSN user=default). Engine
  gains adminUser/env/args/secretMount so the CR builder stays one code path.
- addon_inject: injectAddonURL/removeAddonURL + orchestrator PatchAddonSecret
  (strategic-merge, create-if-absent, key-preserving) / RemoveAddonSecretKey
  (JSON-merge delete, idempotent). Reloader annotation + rev bump on the Secret.
- create: instance bind field (validated); inject AFTER the row Insert as part of
  the atomic provision (rollback on failure). drop: revert to Base BEFORE tearing
  the backend down.
- sql/kv move off the shared-logical registry (each org OWNS its instance); the
  orphaned shared postgres/redis provisioners + pgx/go-redis direct deps removed.

Tests: instance column round-trip + ListByInstance isolation; sql/kv DSN + CR
shape; inject merges (second add-on never clobbers the first); un-bound create
skips injection; drop removes URL before teardown; inject failure rolls back the
whole provision. go build/vet/test green.
2026-07-07 14:08:35 -07:00
hanzo-dev 39c72422dc deps: bump hanzoai/ai -> isglobaladmin in /get-account (8e65b8c3)
Pulls ai's additive isGlobalAdmin field on /get-account so console
recognizes global admins. Pure dependency bump: re-pins re-tagged
luxfi/* modules from source (GOPRIVATE, sumdb-bypassed) after the
documented content-hash drift, prunes cloud.google.com/go/compute and
stale hanzoai/iam v1.31.16 (ai dropped the GCP SDK and requires iam
v1.31.17). go build ./... green (CGO_ENABLED=0).
2026-07-07 12:57:45 -07:00
636159755d o11y: embed in-process OTLP ingest (traces+logs) into cloud (#153)
Fold the standalone otel-collector Deployment into the unified cloud binary:
an in-process OpenTelemetry Collector accepts OTLP (grpc :4317, http :4318) and
writes spans+logs into the same ClickHouse datastore cloud already reads for the
o11y query plane (signoz_traces / signoz_logs, cluster insights). Consumers point
at cloud.hanzo.svc instead of otel-collector.hanzo.svc.

Trimmed, driver-compatible pipeline (reuses the signoz clickhouse exporters that
compile against cloud upstream clickhouse-go v2.44.0):
  otlp -> memory_limiter, resource(namespace=hanzo, env), batch
       -> clickhousetraces (traces), clickhouselogsexporter (logs)

- OFF by default (CLOUD_OTLP_INGEST_ENABLED); fail-soft; ShutdownFunc flushes.
- DSN via env (envprovider), never on disk; metrics self-telemetry off so only
  :4317/:4318 bind (no :9090 class clash).
- telemetry.go: add OTLP-HTTP exporter path so cloud can loop back to the
  in-process ingest at localhost:4318 (ZAP stays default/canonical).

DEFERRED: metrics pipeline (signozclickhousemetrics) needs SigNoz dd-sketch
ch-go fork (chproto.DD/Store/IndexMapping) that will not compile against cloud
upstream ch-go; metrics ingest stays on the standalone collector. See
clients/o11y/LLM.md.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-07 12:12:26 -07:00
hanzo-dev df60569260 Merge branch 'feat/gpu-engine-serve'
# Conflicts:
#	Makefile
#	clients/treasury/anchor_evm.go
#	clients/treasury/ledger/sqlstore/sqlstore.go
#	clients/treasury/treasury.go
#	clients/treasury/treasury_test.go
#	config_iam_replicas_test.go
#	go.mod
#	go.sum
#	subsystems/subsystems.go
2026-07-07 10:43:36 -07:00
616dde3a9c feat(wallets): configurable KMS/MPC/treasury custody subsystem (/v1/wallets/*) (#151)
One custody seam over three orthogonal signing backends selected per-wallet by
Kind:

- KindKMS  single-sig custody IN-PROCESS via the embedded luxfi/kms client
  (deps.KMS). The fully-exercised spine: a real secp256k1 key is generated, its
  private bytes sealed under the KMS envelope, and every Sign recovers to the
  wallet address. No network hop.
- KindMPC / KindTreasury custody DELEGATE over HTTP to the deployed luxfi/mpc
  cluster via a thin typed REST client (the clients/mpcseal precedent). cloud
  never imports github.com/luxfi/mpc. Unconfigured -> fail closed
  (ErrMPCNotConfigured); a signature is never fabricated.

Config seam: KMS always available; mpc/treasury built only when
CLOUD_WALLETS_MPC_ADDR is set and the HS256 JWT secret resolves from a KMS ref
(never a plaintext env). Per-tenant SQLite (org column on every row, every query
filtered by org). Finance seam (WalletForLedgerAccount) is a pure lookup only.

Tests (incl -race): KMS single-sig end-to-end (sig recovers to address, sealed
at rest, rotate changes address), per-tenant isolation, custody seam selects
backend (fail-closed mpc/400 unknown), mpc path wired against a faithful stub.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 20:48:59 -07:00
9e7d00ae42 test(identity): make global-admin gate test config-agnostic on adminOrg (#150)
Reconciles TestGlobalAdminGate_RequiresAdminOrgAndIsAdmin with the task #51 decision
to pin IAM_ADMIN_ORG to the operator org (hanzo). The assertions are unchanged — the
gate is owner==adminOrg AND isAdmin — but the comment/labels no longer editorialize
that owner==admin is the only valid adminOrg. adminOrg is deployment config; the test
pins it to "admin" hermetically and proves the two invariants that hold for ANY
adminOrg: isAdmin is required (a non-admin in the admin org gets nothing) and owner is
required (an admin of any OTHER org gets nothing). Renamed the different-org case off
"hanzo" (which prod now pins AS the admin org) to a neutral "globex" so it reads
unambiguously.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 20:34:43 -07:00
f0a05475d1 feat(treasury): per-tenant Base storage — one SQLite file per tenant, IAM-selected (#149)
The finance ledger of record ran on a single process-wide {DataDir}/treasury.db.
Select the store per request from the validated IAM owner instead, so every
tenant's books live on their OWN Hanzo Base file and one tenant's writes can
never appear in another's read.

- sqlstore.Manager: opens+caches one *Store per tenant (mutex-guarded map). The
  house/reserve ledger is one fixed file ({DataDir}/treasury.db, preserved — no
  migration of live reserve capital); customer ledgers are {DataDir}/finance/{slug}.db.
- tenantSlug: injective (never folds acme/ACME), path-traversal-guarded, reserves
  the house slug. Verbatim stem for a DNS-ish org, else a sha256 slug. Consumes the
  treasury's canonical hanzoai/sqlite opener (Open) — ledgercore's per-tenant opener
  is a test-only helper that would double-register the sqlite driver.
- treasury.Mount binds the ledger of record to the HOUSE store; myAccounts reads the
  caller's OWN per-tenant file (house scope still honours the Formance/Postgres opt-in).
- StorageDriver(): one place decides the driver — sqlite (default, what prod runs) or
  postgres (opt-in via FORMANCE_LEDGER_URL). Postgres option preserved, never the default.

Tests: per-tenant isolation (A's write never in B's read; distinct files; cache
identity; traversal stays in-dir; no case-fold) + default-driver=sqlite + opt-in
preserved. go build ./cmd/cloud green; ./clients/treasury/... green (incl -race).

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 20:05:46 -07:00
a3290f447e fix(config): stage IAM off mount-all (unblock release smoke) + lock global-admin gate (task #51) (#148)
* fix(config): stage IAM off the mount-all default — unblock the release boot smoke

Every cloud release since the IAM embed (#142) has failed its boot smoke and
the fleet stayed pinned to a pre-embed image (v1.786.110), so the treasury +
finance merges (#143/#144/#145/#147) never shipped.

Root cause (from the failed release smoke logs): with CLOUD_ENABLE unset the
binary mounts every registered subsystem, so iamsvc.Mount now runs
iamserver.InitEmbed(). In the smoke/Docker env InitEmbed panics opening its own
SQLite (IAM_DATA_DIR=/data/iam absent on the tmpfs) and is recovered to a
fail-closed 503 — but IAM and the ai subsystem are sibling casibase/casdoor
forks linked against the SAME beego module, so InitEmbed's half-initialised
shared process-global (web.BConfig / xorm adapter) then makes ai's own
bootstrap fail identically:

  iam  ERROR iamserver.InitEmbed: bootstrap panicked: unable to open database file (14)
  ai   INFO  ai: initializing runtime
  cloud: mount: mount ai: ai: bootstrap: unable to open database file (14)  -> SMOKE FAIL

This would crash api.hanzo.ai in prod too (CLOUD_ENABLE is unset there), not
just the smoke.

Fix: make IAM a STAGED subsystem — excluded from the empty-Enable mount-all
default, mounted ONLY when named in CLOUD_ENABLE. This is exactly the HIP-0106
staged-rollout contract iamsvc already documents ('operator adds iam to
--enable only after the fold is verified'), now enforced in code. It restores
the pre-#142 mount-all set (iamsvc is the only subsystem #142 added to it), so
the boot smoke goes green again; hanzo.id keeps being served by the standalone
iam pod until an explicit, verified cutover. Local mount-all boot now reaches
'listening' with iam 'subsystem disabled' and ai mounted clean.

pickIAMClient already falls back to the remote/disabled IAM client when
Enabled("iam") is false (build.go), which is current prod behaviour, so no
deps.IAM regression. One activation mechanism (the enable-list), one place.

* test(identity): lock global-admin = owner==adminOrg AND isAdmin

The cloud admin surfaces (incl. /v1/admin/treasury/*) grant global admin only
to a validated principal whose org IS the admin org AND whose token carries
isAdmin. This locks that invariant end-to-end through the real JWKS-validated
SanitizeIdentity boundary, with the two cases that matter for the treasury flip:

  - a hanzo-org ADMIN (owner=hanzo, isAdmin=true)  -> NOT global admin
  - a NON-admin in the admin org (owner=admin, isAdmin=false) -> NOT global admin

The sole global admin z@hanzo.ai is global admin because IAM promotes @hanzo.ai
into the admin org (owner==adminOrg), NOT because it lives in 'hanzo'. This test
is the guard proving the boundary must NOT be widened to owner==hanzo (e.g.
IAM_ADMIN_ORG=hanzo), which would elevate every hanzo-org admin to see all
tenants' finances. The gate stays owner==adminOrg AND isAdmin; the fix for z is
that its token carries owner=admin, never a wider gate.

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 19:58:06 -07:00
hanzo-dev e09d12da7c build(hanzo): pure-Go recipe for cmd/hanzo so the one sqlite driver registers once
The hanzo CLI (cmd/hanzo) had no build target, so a naive
`go build ./cmd/hanzo` used the machine default CGO_ENABLED=1 and panicked
at init: "sql: Register called twice for driver sqlite".

Root cause: with CGO on, github.com/hanzoai/sqlite (the canonical Hanzo
driver, imported by ~15 clients/*/store.go) compiles its mattn/SQLCipher
backend and registers "sqlite"; the embedded upstream deps that import
modernc.org/sqlite directly (base/core, o11y, commerce/db, orm/db) register
"sqlite" a second time -> panic.

Fix: build cmd/hanzo the same pure-Go way cmd/cloud and the Dockerfile
already ship (CGO_ENABLED=0). hanzoai/sqlite's !cgo backend IS modernc, so
the fork and every modernc importer resolve to a single registration. This
extends the existing CGO_ENABLED?=0 policy (see Makefile header) to the new
binary instead of adding a second way to build; no dependency is dropped and
hanzoai/sqlite stays canonical.

  make hanzo   # -> ./bin/hanzo, pure Go, one 'sqlite' registration
2026-07-05 19:52:05 -07:00
hanzo-dev d376f5eed4 chore(deps): mark luxfi/crypto & luxfi/geth direct
clients/treasury/anchor{,_evm}.go (Phase 2 ledger-root anchor) import
luxfi/geth and luxfi/crypto directly, so they are no longer indirect.
go mod tidy result; no version change.
2026-07-05 19:52:04 -07:00
3c967bad51 feat(treasury): delegate the native ledger to ledgercore — ONE double-entry engine (#145)
Collapse the treasury's separately-written double-entry SQL onto ledgercore
(github.com/hanzo-fi/ledger) — the SAME engine the ledger's own store uses — so
there is exactly one double-entry implementation across the stack (church of
Rich Hickey: one double-entry value, not three places).

- Reimplement clients/treasury/ledger/sqlstore to back the ledger.Store/ledger.Tx
  port with ledgercore instead of hand-rolled treasury_postings SQL. The
  accounting truth — every balance and the reserve overdraw guard — is now
  ledgercore's (postings -> moves -> balances + hash-chained log, idempotency-key
  dedup, WithTx atomic read-then-write). The adapter only maps the treasury's
  vocabulary (int64 cents, Kind/Program/Ref key, signed-Posting Entry) onto it.

- KEEP the port/adapter seam: Open()'s signature is unchanged, so treasury.go and
  the Formance-HTTP opt-in are untouched — native (ledgercore) stays the default
  backend. The engine (ledger.go) and the on-chain Root are UNCHANGED: each Entry
  is round-tripped verbatim (as ledgercore transaction metadata), so the Root is
  byte-identical to the previous store's, independent of ledgercore's own postings.

- Policy (revenue-share bps) stays in a small side table — it is Hanzo config, not
  double-entry accounting, so it does not belong in the shared engine.

- Pin bun to v1.2.9 (replace): ledger-fi floors v1.2.18, which removed
  schema.Formatter/NewFormatter/Append that hanzoai/o11y still uses; ledgercore's
  compiled closure uses no v1.2.18-only API, so v1.2.9 satisfies both. hanzo-fi/ledger
  is pinned to the PR-3 branch commit until it merges.

Tests (all green, incl. -race): overdraw guard, at-most-once payout, snapshot
reconcile, scope isolation, and Tx rollback all pass unchanged against the
ledgercore-backed store. The whole cloud module builds under -mod=readonly, and
the treasury test binary links NO modernc driver (so it does not reintroduce the
"sqlite registered twice" panic).

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 19:14:26 -07:00
4329e17f6f feat(treasury): activate Hanzo L1 (36963) anchor — EIP-1559 gas + deploy tool (#147)
The 36963 coreth fee market pins a 25 gwei min base fee, so a legacy tx priced
at base+1 strands the moment the base fee ticks up. anchor_evm.go now submits a
DynamicFeeTx (1 gwei tip floor, 2x-base-fee cap) — proven accepted on-chain as a
type-2 tx.

Adds clients/treasury/cmd/anchorctl: a one-shot in-cluster tool that provisions
the KMS-held signer (key -> KMS, only the address printed), funds it from a
genesis account, deploys contracts/TreasuryAnchor.sol, and can send anchor(bytes32).
Includes the compiled TreasuryAnchor.bin (solc 0.8.26, optimizer 200, cancun).

Deployed live: contract 0x53141dF42DF13Aad0512f2F08c3E3216EEFac5F2, owner = signer
0x703D4227d58d0b6A20BD721c940CED170470f634 (KMS ref hanzo/treasury-anchor/TREASURY_ANCHOR_SIGNER_KEY).

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 19:11:05 -07:00
0cdf505599 fix(test): canonical make test-race — one sqlite registration under -race (#48) (#146)
The cloud registers the "sqlite" driver exactly once in every build mode EXCEPT
a naive `go test -race`: -race forces CGO=1, which links the fork's mattn
"sqlite" (github.com/hanzoai/sqlite) ALONGSIDE the embedded deps that import
modernc directly (ai/base/commerce/o11y/orm), so both register "sqlite" and the
binary panics at init ("sql: Register called twice for driver sqlite") — the
pre-existing failure in clients/{graph,kmssvc,o11y}.

`make test` (CGO=0) and `make test-cgo` (-tags sqlite_purego) already avoid this
by resolving the whole binary to modernc's single registration. This adds the
missing peer for the race detector: `make test-race` runs
`CGO_ENABLED=1 go test -race -tags sqlite_purego ./...` — CGO on for the race
instrumentation, but the fork forced to its pure-Go backend so mattn never
registers and "sqlite" is registered exactly once. The ONE way to race-test the
cloud.

Proof: `go test -race ./clients/o11y/` panics; `go test -race -tags sqlite_purego
./clients/{graph,kmssvc,o11y}/` all pass.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 18:42:18 -07:00
0c61a8c31f feat(finance): per-org /v1/finance/* projecting the commerce + treasury planes (#144)
The finance.hanzo.ai + console Finance surfaces render real per-org data
instead of preview stubs. This adds no billing system — it PROJECTS the two
that already exist (the commerce customer wallet + the treasury reserve fund)
into the @hanzo/finance-ui contract (USD cents, optional-safe), scoped to the
validated IAM owner.

clients/billing/finance.go — six commerce-projected reads, reusing this
package's commerceProxy + per-org subject-pinning (one commerce read path):
  GET /v1/finance/balance          commerce balance (holds -> pendingCents)
  GET /v1/finance/credits          commerce deposit rows (grants, positive)
  GET /v1/finance/usage?range=     commerce withdraw rows -> series+lines+total
  GET /v1/finance/invoices         honest empty (no invoice ledger exists yet)
  GET /v1/finance/payment-methods  commerce portal, masked to brand+last4
  GET /v1/finance/ledger?range=    commerce ledger -> signed per-org postings

clients/treasury/treasury.go — GET /v1/finance/treasury reshaped from the
reserve Report into the TreasurySummary shape (reserve/committed/available +
honest Hanzo L1 anchor); the transparency policy rides along additively.

Tenant isolation: org A never sees org B (per-org subject pinned server-side,
client cannot widen scope); payment methods re-masked defensively so a PAN can
never leak. Honest empty/typed shapes where a data source does not exist yet.

Tests: go test -race ./clients/billing/... ./clients/treasury/... green;
go build ./cmd/cloud green.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-05 14:19:36 -07:00
4d7344053b feat(treasury): native reserve fund + backed payouts + Formance ledger-of-record + Hanzo L1 anchor (#143)
* feat(treasury): native double-entry reserve fund + backed-payout seam (#treasury)

The platform's OWN fund/reserve accounting, one layer ABOVE the per-org commerce
credit ledger. A store-agnostic, cloud-decoupled double-entry engine
(clients/treasury/ledger) — the SEED of the native hanzoai/finance central ledger
(the Go replacement for the Formance stack) — plus a Base/SQLite adapter
(ledger/sqlstore) and the cloud client (clients/treasury).

Core (clients/treasury/ledger): accounts + balanced journal entries (Σ postings==0,
refused otherwise), ONE shared fund:reserve pool with per-program payout sinks,
revenue-share policy (bps, one place), and the reserve GUARD — a fund debit that
would overdraw is refused, atomically, so growth-loop payouts are backed capital not
unbounded minting. Zero cloud/zip/SQLite imports; persistence is the Store/Tx port,
so it lifts to hanzoai/finance as a directory move.

Surface: GET /v1/treasury (org transparency), GET /v1/admin/treasury (report +
journal + anchor), POST /v1/admin/treasury/{policy,sweep,seed,anchor} (global-admin).
treasury.Reserve(program,ref,memo,cents) is the ONE seam the 3 loops call: backed →
proceed to credit; not backed → honestly pending; unmounted → passthrough
(backward-safe). Idempotent by ref (at-most-once fund debit). ledger.Root commits the
whole journal for the Hanzo L1 anchor (Phase 2 wires the KMS-signed submit).

Tests (-race, green): double-entry balances, revenue-share accrual + per-period
idempotency, reserve guard (backed→blocked), at-most-once, concurrent no-overdraw,
admin gate, Reserve passthrough+enforced, sqlstore round-trip + tx rollback.

* feat(finance): Formance ledger-of-record backend + backed payouts + scope-aware /v1/finance/*

Adopt Formance as the ledger of record behind a ledger.Backend PORT, without
reimplementing double-entry: two adapters satisfy the port — the native Base/SQLite
engine (offline/default, ships the reserve fund today) and clients/treasury/formance
(a real HTTP client to the Postgres-backed Formance Ledger v2 API: world→fund accrual,
fund→payout debit, 400 INSUFFICIENT_FUND→not-backed=the overdraw guard Formance
enforces, reference→idempotency). Select by FORMANCE_LEDGER_URL — a config flip. Root
computed via a SHARED hash so the L1 anchor is backend-agnostic.

Back the growth-loop payouts: referrals/affiliates/authors now DEBIT the reserve fund
via the ONE treasury.Reserve seam before crediting the recipient wallet — fund down,
wallet up, reconciled. Not backed → honestly pending (referrals) or 402 + VoidPayout
restores pending (affiliates/authors). Idempotent by ref (at-most-once). Unmounted →
passthrough (backward-safe; existing loop suites stay green).

Scope-aware /v1/finance/* — ONE engine, three tenancy surfaces (admin/console/finance
product): tenant derived from IAM, house/reserve locked to global-admin under
/v1/admin/finance/*, per-org callers see ONLY their own org:<tenant>:* accounts.
GET /v1/finance/accounts (per-org; admin ?scope=house|?org=<t>). Storage tiers doc'd:
authoritative OLTP ledger (native/Formance) + ClickHouse OLAP projection over the same
o11y event stream (audit mirror — no second metering pipeline).

Tests (-race, green): Formance adapter (accrual+idempotency, debit guard+replay,
snapshot) via a fake Formance server; scope isolation (per-org never sees house);
backed-payout enforced+blocked+at-most-once; VoidPayout restores pending.

* feat(treasury): Phase 2 — Hanzo L1 (36963) ledger-root anchor (contract + luxfi/geth submit + KMS signer)

Make the off-chain books tamper-evident on the LIVE Hanzo L1 (verified running:
network/chainId 36963, hanzod-0 producing blocks, EVM at network-36963).

- contracts/TreasuryAnchor.sol: minimal immutable witness — owner-gated anchor(bytes32)
  appends a timestamped root + emits Anchored; latest()/count for cheap verification.
  No upgradeability, no token — one job.
- anchor_evm.go: real luxfi/geth submitter — dial → chainID/nonce/gasPrice → sign a
  LegacyTx (anchor(bytes32) call when TREASURY_ANCHOR_CONTRACT set, else a 0-value
  self-tx carrying the root) with types.SignTx → send → await receipt → persist. The
  signer key is provisioned from KMS (KMSSecret → env TREASURY_ANCHOR_SIGNER_KEY,
  ref TREASURY_ANCHOR_SIGNER_KMS_REF) — NEVER plaintext in code/manifest.
- ledger.Root/ComputeRoot: deterministic SHA-256 hash-chain over the whole journal +
  reserve, shared by both backends so the anchor is backend-agnostic. A change to any
  historical posting changes the root.
- POST /v1/admin/treasury/anchor submits when wired; else returns the root that WOULD
  be committed + the EXACT remaining step. GET /v1/admin/treasury shows last anchored
  root/tx/block + synced flag. Persisted across restart (treasury_anchor.json).

Honest status: the on-chain submit is COMPLETE + compiling + config-gated but NOT
driven live this pass — the node's external JSON-RPC is unreachable from the build
env and needs an operator to: deploy TreasuryAnchor on 36963, provision the KMS
signer (fund it), set TREASURY_ANCHOR_{RPC_URL,CONTRACT,SIGNER_KEY}. In-cluster the
cloud binary reaches hanzod-rpc-internal:9630, so it's one deploy-config away.

Builds green (cmd/cloud links luxfi/geth); tests -race green; gofmt clean.

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 13:38:29 -07:00
hanzo-dev 16b85808aa feat(cli): hanzo engine install|serve|status
Manage a local hanzo-engine (the `hanzoai` OpenAI + Anthropic model server)
from the canonical `hanzo` CLI:
- install: runs the canonical install.sh / install.ps1 (single source of truth
  for platform detection + signature verification — no re-implementation).
- serve:  launches the installed binary (`hanzoai --port P run -m MODEL`);
  syscall.Exec on Unix so signals + exit code flow through.
- status: probes the local engine, reusing the /v1/models probe that
  `hanzo gpu connect --serve-engine` advertises with.
Tests cover wiring, ready/unreachable status, and binary discovery.
2026-07-05 13:27:21 -07:00
hanzo-dev 69508f550e feat(treasury): Phase 2 — Hanzo L1 (36963) ledger-root anchor (contract + luxfi/geth submit + KMS signer)
Make the off-chain books tamper-evident on the LIVE Hanzo L1 (verified running:
network/chainId 36963, hanzod-0 producing blocks, EVM at network-36963).

- contracts/TreasuryAnchor.sol: minimal immutable witness — owner-gated anchor(bytes32)
  appends a timestamped root + emits Anchored; latest()/count for cheap verification.
  No upgradeability, no token — one job.
- anchor_evm.go: real luxfi/geth submitter — dial → chainID/nonce/gasPrice → sign a
  LegacyTx (anchor(bytes32) call when TREASURY_ANCHOR_CONTRACT set, else a 0-value
  self-tx carrying the root) with types.SignTx → send → await receipt → persist. The
  signer key is provisioned from KMS (KMSSecret → env TREASURY_ANCHOR_SIGNER_KEY,
  ref TREASURY_ANCHOR_SIGNER_KMS_REF) — NEVER plaintext in code/manifest.
- ledger.Root/ComputeRoot: deterministic SHA-256 hash-chain over the whole journal +
  reserve, shared by both backends so the anchor is backend-agnostic. A change to any
  historical posting changes the root.
- POST /v1/admin/treasury/anchor submits when wired; else returns the root that WOULD
  be committed + the EXACT remaining step. GET /v1/admin/treasury shows last anchored
  root/tx/block + synced flag. Persisted across restart (treasury_anchor.json).

Honest status: the on-chain submit is COMPLETE + compiling + config-gated but NOT
driven live this pass — the node's external JSON-RPC is unreachable from the build
env and needs an operator to: deploy TreasuryAnchor on 36963, provision the KMS
signer (fund it), set TREASURY_ANCHOR_{RPC_URL,CONTRACT,SIGNER_KEY}. In-cluster the
cloud binary reaches hanzod-rpc-internal:9630, so it's one deploy-config away.

Builds green (cmd/cloud links luxfi/geth); tests -race green; gofmt clean.
2026-07-05 13:21:41 -07:00
hanzo-dev a49ff2a427 feat(gpu): engine.serve — a connected GPU serves hanzo-engine models
`hanzo gpu connect --serve-engine` advertises a local hanzo-engine (the OpenAI +
Anthropic model server on :1234) on the org fleet, alongside the existing
studio.render worker. The worker probes GET {engine-url}/v1/models, publishes the
endpoint + model list in its presence record, and prints (or with --register-provider
POSTs) the /v1/add-provider call that routes api.hanzo.ai model traffic to this GPU as
an OpenAI-compatible (Type=Local) provider.

- cli/gpu.go: --serve-engine/--engine-url/--engine-endpoint/--register-provider;
  probeEngine, refreshEngine, engineAdvertisement, capabilities, provider hint;
  `hanzo gpu status` shows the engine endpoint.
- clients/visor/fleet.go: byoWorker + fleetRegistration carry capabilities + engine;
  GET /v1/fleet/workers advertises the endpoint (additive, omitempty).
- docs/bring-your-gpu.md: Connect (BYO) vs Deploy (cloud) -> engine.serve + studio.render.
- tests: probe/advertise/registration + full stub-cloud round-trip (no model needed).

One fleet, two job types: engine.serve (model serving) + studio.render (diffusion).
2026-07-05 13:12:30 -07:00
hanzo-dev 419984145b feat(finance): Formance ledger-of-record backend + backed payouts + scope-aware /v1/finance/*
Adopt Formance as the ledger of record behind a ledger.Backend PORT, without
reimplementing double-entry: two adapters satisfy the port — the native Base/SQLite
engine (offline/default, ships the reserve fund today) and clients/treasury/formance
(a real HTTP client to the Postgres-backed Formance Ledger v2 API: world→fund accrual,
fund→payout debit, 400 INSUFFICIENT_FUND→not-backed=the overdraw guard Formance
enforces, reference→idempotency). Select by FORMANCE_LEDGER_URL — a config flip. Root
computed via a SHARED hash so the L1 anchor is backend-agnostic.

Back the growth-loop payouts: referrals/affiliates/authors now DEBIT the reserve fund
via the ONE treasury.Reserve seam before crediting the recipient wallet — fund down,
wallet up, reconciled. Not backed → honestly pending (referrals) or 402 + VoidPayout
restores pending (affiliates/authors). Idempotent by ref (at-most-once). Unmounted →
passthrough (backward-safe; existing loop suites stay green).

Scope-aware /v1/finance/* — ONE engine, three tenancy surfaces (admin/console/finance
product): tenant derived from IAM, house/reserve locked to global-admin under
/v1/admin/finance/*, per-org callers see ONLY their own org:<tenant>:* accounts.
GET /v1/finance/accounts (per-org; admin ?scope=house|?org=<t>). Storage tiers doc'd:
authoritative OLTP ledger (native/Formance) + ClickHouse OLAP projection over the same
o11y event stream (audit mirror — no second metering pipeline).

Tests (-race, green): Formance adapter (accrual+idempotency, debit guard+replay,
snapshot) via a fake Formance server; scope isolation (per-org never sees house);
backed-payout enforced+blocked+at-most-once; VoidPayout restores pending.
2026-07-05 13:08:24 -07:00
hanzo-dev 312d421e34 feat(treasury): native double-entry reserve fund + backed-payout seam (#treasury)
The platform's OWN fund/reserve accounting, one layer ABOVE the per-org commerce
credit ledger. A store-agnostic, cloud-decoupled double-entry engine
(clients/treasury/ledger) — the SEED of the native hanzoai/finance central ledger
(the Go replacement for the Formance stack) — plus a Base/SQLite adapter
(ledger/sqlstore) and the cloud client (clients/treasury).

Core (clients/treasury/ledger): accounts + balanced journal entries (Σ postings==0,
refused otherwise), ONE shared fund:reserve pool with per-program payout sinks,
revenue-share policy (bps, one place), and the reserve GUARD — a fund debit that
would overdraw is refused, atomically, so growth-loop payouts are backed capital not
unbounded minting. Zero cloud/zip/SQLite imports; persistence is the Store/Tx port,
so it lifts to hanzoai/finance as a directory move.

Surface: GET /v1/treasury (org transparency), GET /v1/admin/treasury (report +
journal + anchor), POST /v1/admin/treasury/{policy,sweep,seed,anchor} (global-admin).
treasury.Reserve(program,ref,memo,cents) is the ONE seam the 3 loops call: backed →
proceed to credit; not backed → honestly pending; unmounted → passthrough
(backward-safe). Idempotent by ref (at-most-once fund debit). ledger.Root commits the
whole journal for the Hanzo L1 anchor (Phase 2 wires the KMS-signed submit).

Tests (-race, green): double-entry balances, revenue-share accrual + per-period
idempotency, reserve guard (backed→blocked), at-most-once, concurrent no-overdraw,
admin gate, Reserve passthrough+enforced, sqlstore round-trip + tx rollback.
2026-07-05 12:48:24 -07:00
0c0326f8d4 feat(iam): embed IAM in the unified cloud binary (last binary-consolidation piece) (#142)
* feat(iam): embed IAM in the unified cloud binary as an in-process subsystem

Folds Hanzo IAM -- the identity provider serving hanzo.id (login/authorize/
token/jwks/userinfo, /v1/iam/* admin, OAuth2/OIDC, LDAP/RADIUS) -- into the
unified hanzoai/cloud binary as the LAST binary-consolidation piece
(HIP-0106: "one Go binary embeds IAM + KMS + o11y").

clients/iamsvc wraps IAM's own Beego runtime: iamserver.Init() runs the full
bootstrap without binding a listener, and web.BeeApp.Handlers is mounted
verbatim on cloud's zip.App at every prefix IAM owns (/v1/iam/*,
/.well-known/*, /login/oauth/*, /_/iam/*, /cas/*, /scim/*). No auth logic is
reimplemented -- the same controllers answer, so OAuth/OIDC semantics
(authorize clientId org-resolution, JWT audiences, SuperAdmin owner=="admin",
argon2id password hashing) are preserved byte-for-byte. Registered at order 50
(identity authority, mounts before dependents).

- go.mod: pin hanzoai/iam v1.28.12 -> v1.31.16 (latest; carries the
  authorize-login org-resolution fixes #95/#96 the operator SSO chain needs).
- subsystems.go: blank-import clients/iamsvc; IAM no longer "NOT fused in".

Auth-critical middleware interactions verified: /v1/iam/* prices to 0 in
DefaultPrice (ungated -- the M2M /v1/iam/oauth/token mint is never charged);
SanitizeIdentity strips only forgeable X-User-*/X-Org-* headers, never the
Authorization bearer or iam_session_id cookie IAM's session/oauth logic reads.

Activation is STAGED via the enable-list gate: "iam" is NOT added to the live
--enable until IAM config is present in the cloud runtime and the fold is
verified (login/authorize/token/jwks + operator SSO chain). The standalone iam
pod keeps serving hanzo.id via ingress until then.

Build gate: CGO_ENABLED=0 go build ./... && go test . green. clients/iamsvc
tests prove registration (order 50) + full-path preservation through the mount.

* fix(iam): red-review — embed-mode bootstrap, fail-closed, single-replica guard

Addresses the red review of cloud#142 (mount mechanism approved; activation
blocked on standalone-only side effects in the wrapped entrypoint).

1. [HIGH] Embed-mode bootstrap. iamsvc now calls iamserver.InitEmbed (new in
   iam v1.31.17) instead of the standalone Init: skips StopOldInstance
   (lsof/SIGKILL — panics on distroless, kills a co-resident on shared netns),
   skips LDAP/RADIUS listeners (RADIUS binds unmanaged UDP with an empty shared
   secret), skips export/os.Exit, binds no listener. Standalone hanzo iam / iamd
   is byte-for-byte unchanged (Init delegates to the same shared bootstrap with
   every flag on). Also covers [MED] #3 — directory listeners never start
   in-process.

4. [MED] Fail-closed, not fail-loud. InitEmbed returns an error (recovers
   bootstrap panics); a broken/misconfigured IAM degrades THIS subsystem to a
   503 fail-closed on every IAM prefix (mountFailClosed) — every co-resident
   subsystem (KMS, o11y) stays up. Mirrors the KMS "no master key -> health-only"
   blast-radius isolation.

2. [HIGH] Single-replica enforcement. Embedded IAM uses Beego's process-local
   "memory" session store. Config.Validate now REFUSES to boot iam-enabled above
   CLOUD_REPLICAS=1 (a real runtime guard, not convention); the helm chart pins
   replicas=1 + injects CLOUD_REPLICAS whenever "iam" is in --enable.

5. [MED] Bump verified iam v1.31.16 -> v1.31.17. The slim-JWT change keeps every
   claim cloud reads (owner, isAdmin, email, name kept; aud is a registered
   claim, untouched) — IdentityMiddleware unaffected. authz v1.10.4 policy-API
   swap is IAM-internal (cloud builds green, no direct use). redirect_uri
   exact-match + AutoSignin CC-JWT normalization are version-skew CUTOVER gates:
   version-match the standalone pod + verify registered redirect_uris are exact
   before adding "iam" to the live --enable (runtime-data checklist, not code).

Tests (CGO_ENABLED=0):
- TestIAMEmbedBehindMiddlewareChain — unauth POST /v1/iam/oauth/token, /login,
  jwks + /login/oauth/authorize return 2xx through the REAL SanitizeIdentity +
  BillingGate chain (never 402/503); forged X-User-IsAdmin is stripped; a priced
  control path is denied at zero balance (proves the gate is engaged).
- TestDefaultPriceExemptsIAM — every IAM prefix prices to 0.
- TestValidateIAMSingleReplica — iam + replicas>1 refused; 1/unset/off ok.
- TestMountFailClosed503 — the fail-soft path serves 503 on every IAM prefix.

Build+test green; standalone hanzo iam still links; helm renders replicas=1 for
iam-enabled, replicaCount otherwise. Depends on iam v1.31.17
(hanzoai/iam#feat/iam-embed-entrypoint). STILL STAGED — the standalone iam pod
serves hanzo.id until red GREEN + runtime e2e.

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 12:21:42 -07:00
hanzo-dev cdaee191f0 fix(iam): red-review — embed-mode bootstrap, fail-closed, single-replica guard
Addresses the red review of cloud#142 (mount mechanism approved; activation
blocked on standalone-only side effects in the wrapped entrypoint).

1. [HIGH] Embed-mode bootstrap. iamsvc now calls iamserver.InitEmbed (new in
   iam v1.31.17) instead of the standalone Init: skips StopOldInstance
   (lsof/SIGKILL — panics on distroless, kills a co-resident on shared netns),
   skips LDAP/RADIUS listeners (RADIUS binds unmanaged UDP with an empty shared
   secret), skips export/os.Exit, binds no listener. Standalone hanzo iam / iamd
   is byte-for-byte unchanged (Init delegates to the same shared bootstrap with
   every flag on). Also covers [MED] #3 — directory listeners never start
   in-process.

4. [MED] Fail-closed, not fail-loud. InitEmbed returns an error (recovers
   bootstrap panics); a broken/misconfigured IAM degrades THIS subsystem to a
   503 fail-closed on every IAM prefix (mountFailClosed) — every co-resident
   subsystem (KMS, o11y) stays up. Mirrors the KMS "no master key -> health-only"
   blast-radius isolation.

2. [HIGH] Single-replica enforcement. Embedded IAM uses Beego's process-local
   "memory" session store. Config.Validate now REFUSES to boot iam-enabled above
   CLOUD_REPLICAS=1 (a real runtime guard, not convention); the helm chart pins
   replicas=1 + injects CLOUD_REPLICAS whenever "iam" is in --enable.

5. [MED] Bump verified iam v1.31.16 -> v1.31.17. The slim-JWT change keeps every
   claim cloud reads (owner, isAdmin, email, name kept; aud is a registered
   claim, untouched) — IdentityMiddleware unaffected. authz v1.10.4 policy-API
   swap is IAM-internal (cloud builds green, no direct use). redirect_uri
   exact-match + AutoSignin CC-JWT normalization are version-skew CUTOVER gates:
   version-match the standalone pod + verify registered redirect_uris are exact
   before adding "iam" to the live --enable (runtime-data checklist, not code).

Tests (CGO_ENABLED=0):
- TestIAMEmbedBehindMiddlewareChain — unauth POST /v1/iam/oauth/token, /login,
  jwks + /login/oauth/authorize return 2xx through the REAL SanitizeIdentity +
  BillingGate chain (never 402/503); forged X-User-IsAdmin is stripped; a priced
  control path is denied at zero balance (proves the gate is engaged).
- TestDefaultPriceExemptsIAM — every IAM prefix prices to 0.
- TestValidateIAMSingleReplica — iam + replicas>1 refused; 1/unset/off ok.
- TestMountFailClosed503 — the fail-soft path serves 503 on every IAM prefix.

Build+test green; standalone hanzo iam still links; helm renders replicas=1 for
iam-enabled, replicaCount otherwise. Depends on iam v1.31.17
(hanzoai/iam#feat/iam-embed-entrypoint). STILL STAGED — the standalone iam pod
serves hanzo.id until red GREEN + runtime e2e.
2026-07-05 11:36:15 -07:00
hanzo-dev a4a1eb8b6c refactor(o11y): zaptrace ships OTLP over ZAP with no gRPC dep
The ZAP-native trace exporter marshaled its payload via the generated
otlp/collector/trace/v1.ExportTraceServiceRequest, whose sibling
trace_service_grpc.pb.go (no build tag) drags google.golang.org/grpc into the
graph — contradicting the exporter's own contract (ZAP wire, never gRPC).

Encode the ExportTraceServiceRequest envelope directly from the grpc-free trace
messages with protowire: it is a single 'repeated ResourceSpans resource_spans
= 1', so appending each ResourceSpans under field 1 is byte-identical to the
generated marshaler (proven by the existing round-trip test, which still decodes
with the canonical collector type). go list -deps ./zaptrace now shows no grpc.
Hanzo services speak ZAP/HTTP/WS, never gRPC.

Caveat: the cloud module still pulls google.golang.org/grpc transitively via
hanzoai/ai (sibling-owned), hanzoai/o11y (embedded SigNoz — intrinsically an
OTLP/gRPC collector) and hanzoai/base (GCS gRPC transport). Not removable by a
cloud-local change; tracked separately. go.sum: incidental tidy prune of stale
vfs/age checksums.
2026-07-05 11:19:32 -07:00
hanzo-dev 8ded07e5a1 feat(iam): embed IAM in the unified cloud binary as an in-process subsystem
Folds Hanzo IAM -- the identity provider serving hanzo.id (login/authorize/
token/jwks/userinfo, /v1/iam/* admin, OAuth2/OIDC, LDAP/RADIUS) -- into the
unified hanzoai/cloud binary as the LAST binary-consolidation piece
(HIP-0106: "one Go binary embeds IAM + KMS + o11y").

clients/iamsvc wraps IAM's own Beego runtime: iamserver.Init() runs the full
bootstrap without binding a listener, and web.BeeApp.Handlers is mounted
verbatim on cloud's zip.App at every prefix IAM owns (/v1/iam/*,
/.well-known/*, /login/oauth/*, /_/iam/*, /cas/*, /scim/*). No auth logic is
reimplemented -- the same controllers answer, so OAuth/OIDC semantics
(authorize clientId org-resolution, JWT audiences, SuperAdmin owner=="admin",
argon2id password hashing) are preserved byte-for-byte. Registered at order 50
(identity authority, mounts before dependents).

- go.mod: pin hanzoai/iam v1.28.12 -> v1.31.16 (latest; carries the
  authorize-login org-resolution fixes #95/#96 the operator SSO chain needs).
- subsystems.go: blank-import clients/iamsvc; IAM no longer "NOT fused in".

Auth-critical middleware interactions verified: /v1/iam/* prices to 0 in
DefaultPrice (ungated -- the M2M /v1/iam/oauth/token mint is never charged);
SanitizeIdentity strips only forgeable X-User-*/X-Org-* headers, never the
Authorization bearer or iam_session_id cookie IAM's session/oauth logic reads.

Activation is STAGED via the enable-list gate: "iam" is NOT added to the live
--enable until IAM config is present in the cloud runtime and the fold is
verified (login/authorize/token/jwks + operator SSO chain). The standalone iam
pod keeps serving hanzo.id via ingress until then.

Build gate: CGO_ENABLED=0 go build ./... && go test . green. clients/iamsvc
tests prove registration (order 50) + full-path preservation through the mount.
2026-07-05 11:02:49 -07:00
1723c22aaf feat(authors): native /v1/authors OSS-author deploy-royalty loop over the commerce ledger (#141)
The THIRD growth loop next to referrals (one-time credit) and affiliates
(partner commission): pays open-source AUTHORS a royalty on the metered platform
spend of orgs who DEPLOY their projects on Hanzo. Mirrors clients/affiliates
exactly — one SQLite store, server-side tenant isolation, one Mount (HIP-0106),
the SAME commerce ledger path (a credits payout is a grant, tag grant:author),
and an at-most-once accrual latch.

Flow: connect GitHub (IAM-linked account or supplied login) → verify repo
ownership (OAuth admin-check OR a hanzo.json verify-code file) → a deploy of a
verified author repo by ANY org is recorded (provenance) → sweep accrues 5% of
that org's month-to-date spend, at-most-once per (author, deploying-org, period),
self-deploys excluded → staff pay out as credits (real grant) or cash (record-only),
never exceeding pending.

Surface: GET /v1/authors, POST /v1/authors/{connect,repos/verify,deploys/record};
GET /v1/admin/authors, POST /v1/admin/authors/{sweep,:id/approve,:id/suspend,:id/payout}.

10 tests, all -race green: repo canonicalization, both verify methods, deploy
attribution + idempotency, spend×share accrual + at-most-once, lazy dashboard
sweep, credits-one-grant/cash-record-only/pending-guard payout, admin gate.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 06:11:55 -07:00
1828f4fc26 feat(affiliates): native /v1/affiliates partner-commission loop over the commerce ledger (#140)
Mirrors clients/referrals: one SQLite store, server-side tenant isolation, one
HIP-0106 Mount, admin surface global-admin-gated + enveloped for the console
proxy. Affiliates earn an ONGOING commission (default 20%) on the metered spend
of the customers they refer — the recurring, partner-revenue growth loop beside
referrals' one-time both-sides credit.

- apply (org) -> status applied; staff approve mints the code (vanity opt-in,
  uniqueness-enforced, else a derived slug) + sets the rate.
- attribute (?aff capture) records referred_org->affiliate (first-touch, one per
  referred org, self blocked; approved affiliates only).
- accrual sweep: commission = referred org spend this period x rate, latched
  at-most-once per (affiliate, referred_org, period) in one txn; also lazy on the
  affiliate's own dashboard read.
- payout: a credits method issues a commerce grant (tag grant:affiliate); cash
  methods are record-only; can never exceed pending (accrued - paid), reserved
  atomically before any grant.

Tests (go test -race, 9 green): apply->approve, vanity uniqueness (409),
accrual = spend x rate, idempotent-per-period sweep, payout-as-credits issues one
grant + cash record-only + pending guard, admin gate 403, attribution
self/unknown/first-touch, Mount.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 05:34:03 -07:00
81150fece9 feat(referrals): native /v1/referrals viral loop over the commerce ledger (#139)
* feat(referrals): native /v1/referrals viral loop over the commerce ledger

Per-org referral program mirroring clients/crm's structure (one SQLite store,
server-side tenant isolation, HIP-0106 Mount). Grants promo credit through the
SAME commerce deposit path as clients/admin.grantCredit (trial/Credit bucket,
tag grant:referral).

- Stable deterministic referral code per org (base32 of a hash of the org id) +
  a white-labeled ?ref link; persisted directory for O(1) reverse lookup.
- POST /v1/referrals/claim: record referrer<->referee (referee = validated
  caller), status signed_up. Self-referral blocked, one-per-referee idempotent
  (first-touch wins).
- Qualify signal = referee metered spend (honest 'actually used the product').
  On qualify, grant BOTH sides: referrer +$10, referee +$5. At-most-once via a
  credited_at latch — no sweep and no concurrent read can double-pay.
- Trigger: lazy on the referrer's GET /v1/referrals + POST /v1/admin/referrals/
  sweep (cron path). GET /v1/admin/referrals directory, both global-admin gated.
- Constants (bonus amounts + ledger tag) in one place. Commerce behind an
  interface for testable double-grant/idempotency proofs.

Tests: code derivation, self-ref block, idempotent claim, qualify->double-grant
with balances moving through the (fake) ledger, at-most-once idempotency, lazy
qualify on read, admin gate + directory, real Mount. All green (go test -race).

* feat(referrals): envelope the /v1/admin/referrals surface for the console admin proxy

---------

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 05:01:58 -07:00
hanzo-dev 11a3ae664b refactor(org): use the shared hanzoai/vfs/replica — kill the duplicate Replicator+election
cloud's internal/org was the ORIGIN of the HA-SQLite machinery; it's now promoted to the
shared hanzoai/vfs/replica lib that every service adopts. Delete the duplicated impls
(replica.go Replicator+Store+DB+DBPath, owner.go Member+Owner+IsOwner+Replicas+HRW) and
re-export them as aliases (shared.go). cloud-specific pieces stay: membership.go (live IAM
source), cipher.go (KMS envelope — already satisfies replica.Cipher), vfsstore.go (Store over
deps.VFS, now using the exported replica.Version). One and one way: ONE Replicator + election,
in vfs/replica, used by cloud AND visor. Builds + org tests green (vfs v0.6.2).
2026-07-05 00:43:11 -07:00
da0aaa677d fix(deps): bump hanzoai/ai v1.800.7 → v1.800.9 (zen context length → unblocks console chat) (#138)
Zen models were capped at the 4096 fallback in getContextLength, so every
console chat (grounded assistant ~4190-token system prompt) 402'd
'exceeds maximum token count: 4096'. v1.800.9 special-cases the zen* prefix
to 131072. Fixes the P0 console-chat gate.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-05 00:23:17 -07:00
hanzo-devandGitHub 557ec293e6 Merge pull request #137 from hanzoai/fix/o11y-embed-metrics-port-9090
fix(o11y embed): disable runtime :9090 self-metrics reader — crash-loop guard
2026-07-04 23:15:42 -07:00
hanzo-dev 3d448ebfb6 o11y embed: disable the runtime's :9090 self-metrics reader (crash-loop guard)
The embedded o11y runtime's OTel instrumentation defaults to a Prometheus pull
reader bound to 0.0.0.0:9090 (pkg/instrumentation) — the SAME port as cloud's
health listener (CLOUD_HEALTH_LISTEN=:9090). Activating the embed therefore made
the whole cloud process crash-loop with 'listen tcp :9090: bind: address already
in use' (verified on the canary), taking down all of api.hanzo.ai — a listener the
standalone o11y pod never contended for.

buildEmbeddedHandler now defaults O11Y_INSTRUMENTATION_METRICS_ENABLED=false (via
setenvDefault, operator-overridable to a free port) before construction. Cloud owns
process-level observability (exports its own OTel telemetry), so the embed serves
/v1/o11y in-process without a second metrics listener. Extracted the env defaults
into applyEmbedEnvDefaults + TDD (guard + operator-override).

Verified on the cloud-unified-canary: with this default the .104 embed goes Ready
and serves /v1/o11y in-process (health 200); without it the pod crash-loops on :9090.
CGO=0 go build/test green.
2026-07-04 23:15:22 -07:00
hanzo-devandGitHub bb5c0b9481 Merge pull request #136 from hanzoai/feat/o11y-embed-mainbased
o11y embed: shared community.NewServer (DRY) + health-exempt gate; o11y v1.5.0
2026-07-04 22:46:06 -07:00
hanzo-dev 358492a0aa o11y embed: use shared community.NewServer (DRY); exempt health from the gate
Refactor clients/o11y/embed.go onto o11y v1.5.0's shared builder community.NewServer
+ community.NewConfig — the EXACT construction the standalone o11y pod runs — so
the in-process runtime cannot drift from the pod's auth (pkg/identn/iamidentn,
Hanzo IAM gateway-header identity). Collapses the duplicated ~70-line signoz.New
factory list (drift risk) to one call. Enable signal now reads the flat operator
knob O11Y_DATASTORE_DSN (what the pod sets), falling back to the structured
O11Y_TELEMETRYSTORE_DATASTORE_DSN.

Exempt liveness/readiness paths from gate(): the runtime serves them without
identity (k8s probes pass that way), so gating them only breaks unauthenticated
health probes (admin System Health CLOUD_O11Y_HEALTH_URL, the external o11y.*
hosts) without protecting anything. Data routes stay gated (RED forge test still
403s /v1/o11y/api/v1/query_range).

go.mod: o11y v1.4.1 -> v1.5.0 (identical go.mod hash — no new transitive deps).
Build-gate: CGO_ENABLED=0 go build ./... = 0, go test . = ok, go test ./clients/o11y = ok.
2026-07-04 22:44:04 -07:00
zandGitHub d9b8087093 Merge pull request #135 from hanzoai/feat/o11y-embed-main-iamidentn
feat(o11y): embed the MAIN-based runtime (iamidentn) — auth matches the pod
2026-07-04 22:30:16 -07:00
hanzo-dev 53a5468cea feat(o11y): embed the MAIN-based runtime (iamidentn) — auth now matches the pod
The #133 embed pinned o11y v1.3.13, whose runtime authenticates via o11y-native
JWT (tokenizer.GetIdentity on the Authorization bearer). The live gateway-header
traffic the standalone o11y:0.2.0 pod serves — identity injected as X-Org-Id/
X-User-Id/X-User-Email by the gateway — would 401 against that. So activating the
v1.3.13 embed could not replace the pod.

This repoints the embed to the MAIN o11y line (v1.4.1), which resolves identity
through the IdentN resolver's iamidentn provider (default-enabled) from those
gateway session headers, with iamauthz (Hanzo IAM Casbin) for authorization —
the SAME auth model as the running pod. Gateway-header traffic authenticates
(200), not 401.

- clients/o11y/embed.go: build the runtime via pkg/signoz.New with the SAME
  provider factories the standalone cmd/community server uses (noop zeus,
  licensing, gateway, auditor, meterreporter; iamauthz; ClickHouse
  telemetrystore; sqlite sqlstore; IdentN to iamidentn), then app.NewServer to
  server.PublicHandler (new accessor, o11y v1.4.1). runtime.Start runs the
  registry background services (incl. the ruler/alert-rule-manager)
  non-blocking; we never call server.Start (cloud owns its HTTP listeners; OpAMP
  stays out-of-process). Gate/proxy-fallback structure (clients/o11y/o11y.go) is
  unchanged: still O11Y_TELEMETRYSTORE_DATASTORE_DSN-gated, still fail-soft to
  the reverse proxy.
- go.mod: hanzoai/o11y v1.3.13 to v1.4.1 (main line, iamidentn). Drop the stale
  replace prometheus/alertmanager to hanzoai/alertmanager v0.28.2 — it forced
  o11y's code onto the old fork whose api/v2 returns hanzoai/common types that
  clash with o11y v1.4.1's upstream prometheus/common structs. o11y v1.4.1 (and
  the pod) build against upstream prometheus/alertmanager v0.31.1; cloud has no
  direct alertmanager import, so it now matches.

Telemetry backend (ClickHouse datastore StatefulSet, cluster insights) is
untouched — the embedded runtime queries it over ClickHouse-native :9000.

Build-gate: CGO_ENABLED=0 go build ./... OK; go test ./clients/o11y/... OK; vet OK.
2026-07-04 22:22:49 -07:00
hanzo-devandGitHub a8d7fdd35d Merge pull request #134 from hanzoai/bump/tasks-v1.49.0
chore(deps): bump hanzoai/tasks v1.48.0 -> v1.49.0 (durable social primitives + gated auth)
2026-07-04 21:43:17 -07:00
hanzo-dev a21ebbbf6d chore(deps): bump hanzoai/tasks v1.48.0 -> v1.49.0
v1.49.0 adds the durable workflow primitives social-orchestrator needs to run
on cloud's embedded gated engine (ServeGated :9999): signal-to-running-workflow
re-dispatch, continueAsNew, startChild, typed search attributes, workflowId
conflict policy, and the signalWithStart wire fix. No cloud code change — the
embedded engine + gated listener pick up the fixes on rebuild.
2026-07-04 21:42:56 -07:00
hanzo-devandGitHub 555911ea07 feat(o11y): embed the o11y runtime in-process; retire the proxy path (#133)
Constructs the ONE hanzoai/o11y runtime IN-PROCESS (clients/o11y/embed.go) —
the SAME bootstrap the standalone cmd/server runs (o11y.New with its provider
factories -> app.NewServer -> server.PublicHandler) — and installs it via
o11y.SetHandler, so /v1/o11y/* is served by THIS binary against the ClickHouse
`datastore` (StatefulSet, cluster insights) instead of reverse-proxying a
standalone o11y Deployment. The standalone o11y pod can now retire; the
ClickHouse datastore stays as the telemetry backend.

- clients/o11y/embed.go: buildEmbeddedHandler wires telemetrystore (ClickHouse/
  datastore), sqlstore (sqlite under cloud's data root), querier, dashboards,
  alerts; starts the registry services + the alert rule manager (StartBackground).
  Enabled by O11Y_TELEMETRYSTORE_DATASTORE_DSN (the DSN is the one knob).
- o11y.go Register callback: prefer the in-process runtime; fall back to the
  reverse proxy when the embed is disabled (no DSN) or fails to init — fail-soft,
  zero downtime. Proxy handler + gate + tests retained for the fallback path.
- Bump hanzoai/o11y v1.3.12 -> v1.3.13 (adds Server.PublicHandler + StartBackground).
- Drop the stale `replace gorilla/mux => containous/mux`: it was a copied Traefik
  replace block; Traefik is not in the graph and nothing calls the containous API,
  but the fork lacks mux.MiddlewareFunc that o11y's otelmux needs. Standard
  gorilla/mux v1.8.1 satisfies every consumer.

Deferred (reported, not faked): OpAMP collector management (a second websocket
listener) is not started in-process — telemetry ingest continues on the existing
collector->datastore path. Build/test gate is CGO_ENABLED=0 (as prod ships): o11y
+ hanzoai/sqlite resolve to a single modernc sqlite driver registration.
2026-07-04 21:27:54 -07:00
zandGitHub 9dc7d80508 billing(#70): enforce per-scope spend caps + rate limits at the edge (metering v0.1.4)
Red SHIP; conflicts (only #45 clients/team) resolved to main; 22 money-path+regression tests green; go build clean. Edge calls standalone commerce /authorize; inert by default.
2026-07-04 20:53:45 -07:00
hanzo-dev c5a0a04a05 Merge remote-tracking branch 'origin/main' into feat/scope-spend-limits
# Conflicts:
#	clients/team/account.go
#	clients/team/account_store.go
#	clients/team/account_store_test.go
#	clients/team/account_test.go
#	clients/team/bots.go
#	clients/team/roster_test.go
#	clients/team/store.go
#	clients/team/team.go
#	clients/team/token/token.go
#	clients/team/token/token_test.go
#	clients/team/transactor.go
2026-07-04 20:47:26 -07:00
79a5c38807 chore: pin tasks v1.48.0 (was mutable pseudo-version) (#132)
Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 20:43:20 -07:00
0e9e453fcb feat(durable): expose embedded tasks engine on a gated cluster ZAP listener (#131)
Consolidation: kill the standalone tasksd pod by running its consumers on cloud's
in-process embedded engine. After Embed wires the loopback (ungated, in-process
ai-ingest) listener, call emb.ServeGated(ctx, 9999, validator) to expose the SAME
engine cluster-wide under mandatory identity gating.

RequireIdentity: every request on :9999 must carry an IAM auth_token, validated
against {IAMIssuer}/v1/iam/.well-known/jwks (HIP-0111) and org-scoped to its owner --
the same trust anchor as the HTTP SanitizeIdentity boundary. The loopback dialer for
ai-ingest is untouched (127.0.0.1:19999, ungated, cloud's own trust boundary).

Fail-soft: a missing IAMIssuer or a bind failure logs and leaves the gated surface
down without disturbing ai-ingest. 9999 mirrors the port the retired tasksd exposed,
so a consumer repoint changes only the host (tasks.hanzo.svc -> cloud.hanzo.svc).

Depends on hanzoai/tasks#8 (ServeGated + identity over ZAP). Pinned here to that
branch's commit; repin to the tagged release once #8 merges. universe adds the :9999
Service port.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 20:42:28 -07:00
hanzo-dev 35652cb4da chore: pin tasks v1.48.0 (ServeGated) for the gated cluster ZAP listener 2026-07-04 20:42:24 -07:00
hanzo-dev 0ddfb72094 feat(durable): expose embedded tasks engine on a gated cluster ZAP listener
Consolidation: kill the standalone tasksd pod by running its consumers on cloud's
in-process embedded engine. After Embed wires the loopback (ungated, in-process
ai-ingest) listener, call emb.ServeGated(ctx, 9999, validator) to expose the SAME
engine cluster-wide under mandatory identity gating.

RequireIdentity: every request on :9999 must carry an IAM auth_token, validated
against {IAMIssuer}/v1/iam/.well-known/jwks (HIP-0111) and org-scoped to its owner --
the same trust anchor as the HTTP SanitizeIdentity boundary. The loopback dialer for
ai-ingest is untouched (127.0.0.1:19999, ungated, cloud's own trust boundary).

Fail-soft: a missing IAMIssuer or a bind failure logs and leaves the gated surface
down without disturbing ai-ingest. 9999 mirrors the port the retired tasksd exposed,
so a consumer repoint changes only the host (tasks.hanzo.svc -> cloud.hanzo.svc).

Depends on hanzoai/tasks#8 (ServeGated + identity over ZAP). Pinned here to that
branch's commit; repin to the tagged release once #8 merges. universe adds the :9999
Service port.
2026-07-04 20:35:02 -07:00
hanzo-dev 649c2c5b97 billing(#70): fix Red HIGH-2 project-spoof, MED-4 DenyResource, INFO-7
HIGH-2: principal.ValidatedProject(c) (project, validated) — returns false
today (X-Project-Id is a caller-chosen label, not claim-bound), so the edge
gate + resource meter pass ProjectValidated=false and commerce degrades
project-scoped hard caps to soft. ONE lever to harden when IAM mints a
project claim. MED-4: DenyResource renders ErrSpendCapExceeded -> 402
spend_cap_exceeded (was 503). INFO-7: canonicalService unifies the edge
service label with the resource provider (ml/visor->compute, agents->agent,
security->security.scan) so a cap binds on both surfaces. Bump metering
v0.1.3 -> v0.1.4. Tests green (incl DenyResource spend_cap).
2026-07-04 20:25:04 -07:00
hanzo-dev f32761ebbc fix(team/account): public-URL OAuth callback origin behind the gateway (#45)
Adds TEAM_PUBLIC_URL / PUBLIC_ORIGIN config: callbackOrigin() returns the
configured public origin (e.g. https://hanzo.team) for the OAuth redirect_uri
instead of the request Host, so cloud emits the registered public callback even
behind the gateway (where the request Host is the internal cluster service).
Unset = unchanged (falls back to originOf). Lets hanzo.team route through the
gateway UNIFORMLY like api.hanzo.ai — removes the need for the temporary
direct-to-cloud edge route.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 20:15:12 -07:00
hanzo-dev 59053acf41 billing: enforce per-scope spend caps + rate limits at the edge (#70)
BillingGate uses metering.AuthorizeVerdict (funds+cap, one round trip):
renders a distinct 402 spend_cap_exceeded (scope/cap/spent) and sets
X-Spend-Warn at the soft threshold; gates on the request price. New ONE
ScopeRateLimit middleware composes zip/middleware.RateLimit per-scope
(org/project/service), dynamic rpm from commerce (short-TTL cache,
fail-open), 429 + X-RateLimit-* — wired after identity, before billing.
ResourceMeter threads project + service(=provider) so resource creation
is scope-gated too. Scope always from the validated principal. Bump
metering v0.1.2 -> v0.1.3. Money-path tests green (402/warn/429/isolation).
2026-07-04 19:47:10 -07:00
hanzo-dev 5ee34fec4c feat(vfs): real in-process deps.VFS on SeaweedFS S3 — team files/avatars (#45)
pickVFSClient returns an S3-backed types.VFSClient (clients/s3vfs.go) when
S3_ADMIN_ACCESS_KEY/SECRET_KEY are set, else DisabledVFS (R-7 fail-closed
preserved). Reuses the SAME s3admin.Admin construction as clients/s3 (DRY, one
credential path). Put/Get/Delete over the shared 'team-blobs' bucket, per-tenant
key prefix (files.go builds team/blobs/<verified-org>/<ws>/<blobId>). S3 NoSuchKey
maps to types.ErrBlobNotFound (honest 404/idempotent-204); any other S3 error →
502 fail-closed (never a dishonest 404). Bucket create-if-absent self-heals a boot
blip. Red-reviewed SHIP. This is the repoint gate: hanzo.team avatars/attachments
now work off cloud.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 16:58:04 -07:00
hanzo-dev 873e2f488a feat(team): mount clients/team as native cloud subsystem — port from team-go (#45)
Ports hanzoai/team-go into the unified cloud binary as a zip-native subsystem
(order 138, /v1/team/*): account (IAM OAuth bridge + workspaces/members on SQLite),
transactor (Huly wire over wsx, serverVersion 0.6.0 preserved), bots-as-members
(in-process agents.ListForOrg → Employees, removal-reconcile), files (FrontStorage
contract, org+workspace-membership scoped, byte-derived content-type allow-list).

Security (Red-reviewed, all closed): fail-closed SERVER_SECRET degrade-health-only
(never crashes the binary/CI smoke-boot), token exp/nbf, seg() traversal guard,
setCookie verify, cross-tenant blob isolation, VFSClient.Delete fail-closed (deps.VFS
never nil, R-7). Supersedes the stale clients/team a parallel branch swept onto main.

Real deps.VFS wiring (avatars) follows in the next patch (.97) before the hanzo.team
front repoint, so nothing regresses. Migration + repoint + rip of the standalone
team-go Deployment are the remaining cutover steps.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 16:32:19 -07:00
7b49e15f51 admin: trial/prepaid grant source + /v1/admin/grants (list+issue) (#129)
- POST /v1/admin/customers/:org/credit gains `source` (trial|prepaid). A staff
  comp defaults to TRIAL (non-cash Credit bucket, grant:admin tag → billing/bucket
  DepositKind Credit); only explicit "prepaid" mints real money (admin-grant tag →
  Prepaid). Fail-closed: unknown→trial, so a comp never silently becomes payout-able
  cash. source recorded in the audit before/after + response.
- grantCredit refactored to a shared applyGrant core (ONE credit-write path).
- NEW GET /v1/admin/grants — the credit-grant ledger across all orgs, projected
  from the tamper-evident audit trail (action admin.customer.credit): org, amount,
  source, reason, staff actor, date, txid, result. Honest-empty without a local
  audit store.
- NEW POST /v1/admin/grants — issue a grant to any org from the operator Grants
  view (org in body), funneled through the SAME applyGrant core.
- Both global-admin gated (s.guard). grantTag unit-tested.

go build/vet/test ./clients/admin green.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-04 14:54:39 -07:00
hanzo-dev ff5512171e admin: trial/prepaid grant source + /v1/admin/grants (list+issue)
- POST /v1/admin/customers/:org/credit gains `source` (trial|prepaid). A staff
  comp defaults to TRIAL (non-cash Credit bucket, grant:admin tag → billing/bucket
  DepositKind Credit); only explicit "prepaid" mints real money (admin-grant tag →
  Prepaid). Fail-closed: unknown→trial, so a comp never silently becomes payout-able
  cash. source recorded in the audit before/after + response.
- grantCredit refactored to a shared applyGrant core (ONE credit-write path).
- NEW GET /v1/admin/grants — the credit-grant ledger across all orgs, projected
  from the tamper-evident audit trail (action admin.customer.credit): org, amount,
  source, reason, staff actor, date, txid, result. Honest-empty without a local
  audit store.
- NEW POST /v1/admin/grants — issue a grant to any org from the operator Grants
  view (org in body), funneled through the SAME applyGrant core.
- Both global-admin gated (s.guard). grantTag unit-tested.

go build/vet/test ./clients/admin green.
2026-07-04 14:32:44 -07:00
hanzo-devandGitHub ef71666dfa chore(kms): drop hanzoai/kms/sdk/go straggler, bump luxfi/kms v1.11.6→v1.11.8 (#128)
Align cloud to the target: KMS is the embedded luxfi/kms (clients/kms) alongside
embedded IAM; the last external hanzoai/kms dependency is removed.

- go.mod: bump github.com/luxfi/kms v1.11.6 → v1.11.8 (match the deployed image);
  remove github.com/hanzoai/kms/sdk/go v1.1.1; go mod tidy.
- clients/mpcseal (NEW): the minimal client-side-CEK sealing client for the
  SEPARATE luxfi/mpc node ring — a faithful, behavior-identical inline of the
  subset of the former hanzoai/kms/sdk/go that clients/fleet + clients/provisioning
  use (NewClient/Unlock/Set/Get/Delete + Argon2id→HKDF→AES-256-GCM). luxfi/kms has
  no drop-in equivalent (its pkg/ is server/ZAP/store, not a Vault client), so
  inlining the used subset is the minimal correct change that removes the external
  dep without altering the wire protocol or trust model. Drops the HPKE Wrap/Unwrap
  the callers never used.
- clients/{fleet,provisioning}: swap import path only; call sites untouched.
- clients/kmssvc/login.go + docs/consolidation.md: comment/table refs → luxfi.

Verified: go build ./... = 0, go vet = 0, gofmt clean, clients/provisioning tests
pass. go.mod + go.sum carry zero hanzoai/kms references.

Follow-up (separate, tested change): fold fleet/provisioning sealing into cloud's
embedded deps.KMS once types.KMSClient gains Delete + verified against the live MPC
ring — one KMS surface. Once the universe KMS-collapse PR merges, the deprecated
hanzoai/kms repo/package can be archived.
2026-07-04 14:25:58 -07:00
hanzo-dev 1b301149bb feat(principal,fleet,ml): make the data plane tenant+PROJECT aware
The gateway now mints X-Project-Id (an org SUB-SCOPE) alongside X-Org-Id.
Thread it through the keyed surfaces, backward-compatibly — the default
project ("default", or an absent header) resolves to today's exact keys,
so existing single-project tenants are byte-identical.

- principal.Project(c): the ONE read accessor, mirroring c.Org() (zero-copy
  header read, cloned on retain). Defaults to DefaultProject when the header
  is empty. principal.DefaultProject / IsDefaultProject own the default-scope
  semantics in one place (shared contract value with iamauth.DefaultProject).
- fleet: registry refs shard by project via the ONE scopeRef seam —
  "<org>/fleet/clusters" for the default project, "<org>/<project>/fleet/
  clusters" for a non-default one (index, sealed kubeconfig, cache key).
- ml: tenant namespace is "ml-<org>" for the default project and
  "ml-<org>-<project>" for a non-default one; both org and project are
  validated against strict DNS-label regexes (no lossy fold) and the composed
  label is length-checked against the 63-char ceiling, keeping the
  (org, project) -> namespace map injective. A hanzo.ai/project attribution
  label is stamped for non-default projects.
- visor BYO fleet + ml federation resolve project via principal.Project.

Billing stays keyed on the paying org (a project has no separate prepaid
balance); project is isolation + attribution, not a billing key.
2026-07-04 14:19:15 -07:00
hanzo-devandGitHub 8f7c72b56d fix(deps): repin luxfi/age v1.5.0 -> v1.5.1 (cold-cache checksum SECURITY ERROR) (#127)
luxfi/age v1.5.0 was upstream-retagged (transient files GC'd from the tag
tree), so the tag's zip content on the origin no longer matches the h1 hash
recorded in go.sum. Cold-cache builds (fresh CI, empty GOMODCACHE) fail with:

    verifying github.com/luxfi/age@v1.5.0: checksum mismatch
    SECURITY ERROR

v1.5.1 dereferences the same commit, is immutable, and is sum.golang.org
verified (h1:Gj8iHMMi0lGkKT/mlXV2HVBr2m3vt2v0eKVsTMTtAQM=). Surgical: age
require + go.sum only. go mod verify clean.
2026-07-04 14:15:49 -07:00
aa4b572f7e feat(crm): Startup Program applications — public intake, AI screen, pipeline (#125)
* feat(crm): startup-program applications resource (intake + AI screen + pipeline)

Public unauthenticated intake POST /v1/crm/applications (rate-limited + honeypot)
writes a dedicated crm_applications record (all fields in metadata JSON), a
best-effort CRM Company+Contact projection, and kicks off an AI screen via the
gateway (score / tier1 / suggested credits / summary / draft reply) that
auto-advances applied->screened. Staff GET/PATCH drive a stage machine
(applied->screened->qualified->credits-offered->onboarded, +rejected w/ reason).
Non-fatal if the LLM is unavailable.

* test(crm): startup applications — intake, honeypot, idempotency, AI screen, stage machine

10 tests: public intake creates application+CRM projection with all fields in
metadata; honeypot drop; validation; idempotent resubmit; end-to-end AI screen
with a fake gateway (score/tier1/credits/reply + auto-advance applied->screened);
non-fatal screen on gateway error; staff PATCH stage machine (advance/skip-block/
reject-requires-reason); pure canTransition + parseScreen + detectTier1.

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-04 13:32:59 -07:00
hanzo-devandGitHub 7dd6ba60a9 chore(tasksvc): swap embedded Tasks UI to a fresh from-source build (#126)
PR #124 embedded the last-known-good admin-tasks build as a de-risking
fallback. This replaces it with a FRESH build of current admin-tasks HEAD,
built from source in a combined gui+admin workspace (hanzogui@7.3.x +
@hanzogui/admin@7.3.0 workspace-linked; @hanzogui@7.3.x is unpublished, so it
must build inside that workspace — see clients/tasksvc/ui/README.md).

Same contract (base=/_/tasks/, api=/v1/tasks); full component parity
(namespaces/workflows/schedules/batches/deployments/activities/nexus/history).
Embed tests still assert the real bundle (not the placeholder).
2026-07-04 13:29:39 -07:00
hanzo-dev 2c8b6a66c6 feat(fleet): unify BYO clusters into the ONE /v1/clusters surface (visor)
One and one way: BYO k8s / BYO-GPU / bare-metal attach now lives on the SAME fleet
surface as managed clusters (visor /v1/clusters), not a parallel /v1/ml/clusters.
- clients/fleet: the shared per-org BYO-cluster Registry — kubeconfig sealed in the
  org's KMS, validated by reaching the cluster (node + nvidia/amd GPU inventory),
  tenant-scoped by the ZAP-propagated X-Org-Id. ONE source of truth.
- visor: POST /v1/clusters (attach) + DELETE /v1/clusters/:id (detach), and BYO
  clusters MERGE into GET /v1/clusters beside managed ones. Nominal management fee
  (rides the compute-fee config — no bespoke env var; customer brings the compute).
- ml: deleted the parallel /v1/ml/clusters; dynForOrg federates ML serving onto the
  org's registered cluster via the shared registry (home client when none).
Builds + vet + tests green.
2026-07-04 13:16:34 -07:00
hanzo-devandGitHub 501cad7c57 feat(tasksvc): embed the real Tasks UI, retire tasks-ui pod (#124)
clients/tasksvc served /_/tasks from github.com/hanzoai/tasks/ui, whose
ui/dist is an empty 'No UI build present' placeholder — so tasks.hanzo.ai
still routed to the standalone tasks-ui pod (a Temporal-Web-UI fork).

cloud is the ONE process that serves tasks.hanzo.ai (durable.go's embedded
engine + /v1/tasks surface), so cloud now owns the UI embed too: a local
clients/tasksvc/ui package bakes the real admin-tasks SPA build (base=/_/tasks/,
api=/v1/tasks) into the binary via //go:embed. One binary, one origin, the
real UI — which lets the tasks-ui Deployment/Service/CR be retired.

Tests prove the embedded bundle is the real SPA (not the placeholder), the
SPA deep-link fallback, immutable asset caching, and GET-only.
2026-07-04 13:14:17 -07:00
hanzo-dev 583b04c19a test(observe): red-team route-precedence probe — scoped GET wins over the o11y proxy wildcard (#59)
Companion security test to the observe subsystem: proves a /v1/o11y/logs
request lands on the org-scoped handler (order 44), never falling through to
the unscoped hanzoai/o11y reverse-proxy wildcard (order 70) that would bypass
tenant scoping (attack #4).
2026-07-04 13:03:37 -07:00
hanzo-dev e4f749f738 fix(observe): coerce response_status_code (LowCardinality(String)) before numeric compare
Validated the handler SQL against the live signoz_traces schema: response_status_code
is LowCardinality(String), so a raw >= 500 raises NO_COMMON_TYPE and asInt64 on it
yields 0. Wrap with toInt32OrZero() in the RED errs count and the request-log status,
matching the verified live query (real per-org buckets returned).
2026-07-04 13:02:27 -07:00
hanzo-dev 8c655ca6a9 feat(observe): live per-org Settings/Status/Logs/Metrics for console products (#59)
New /v1/o11y/{logs,metrics,status} + /v1/settings/:product cloud subsystem
(order 44, wins over the hanzoai/o11y proxy wildcard) backing the console
product-detail tabs with REAL, org-scoped data — no stubs.

- Logs   : ClickHouse signoz_logs (admin: raw app stream) / signoz_traces
           org-tagged request stream (every other tenant), live-tail cursor.
- Metrics: per-org RED (rate/errors/p50/p95) from org-tagged spans
           (attributes_string['hanzo.org']) + per-org LLM usage (cloud_usage).
- Status : live in-cluster health probe (latency) + VictoriaMetrics up{service}.
- Settings: per-(org,product) SQLite CRUD; secret fields -> KMS, never SQLite.

Tenant isolation server-side: org = principal.Tenant (validated owner claim),
bound as a positional ClickHouse param / mandatory WHERE org=? — never a client
header/param/raw-query. Only IAM_ADMIN_ORG sees unattributed infra logs.
Reuses the shared ai/object datastore client (one conn, KMS creds).

Tests: 8/8 pass — store isolation, principal gate on every endpoint,
cross-tenant read denial, secrets-never-in-SQLite (fail closed w/o KMS),
product traversal/injection rejection, honest status down.
2026-07-04 13:02:27 -07:00
hanzo-dev 292ef535b5 fix(billing): restore per-item ledger attribution (Meter records kind as Usage.Model)
The fe3a5fd agents-metering refactor split MeterUsage out of Meter and
dropped the Model:kind write, so EVERY per-product debit (functions/invoke,
s3/op, provisioning, ml, tracker, automations, security) recorded an empty
model — losing per-item revenue attribution in the commerce ledger. Restore
the one-place mapping in Meter (all 8 resource callers flow through it).

Also fix two stale test doubles that read the retired X-IAM-Org-Id header;
commerce reads X-Org-Id only (same $0-revenue class as the admin.go fix), so
they saw an empty org. Full suite: 58 ok, 0 fail.
2026-07-04 12:58:32 -07:00
8350a5559e fix(serve): truthful comment — ZAP :9653 is plaintext TCP, needs mesh mTLS (red finding #3) (#123)
Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 12:46:04 -07:00
hanzo-dev f18986ea7f feat(visor,cli): bring-your-own GPU fleet — console surfaces + hanzo gpu CLI
Register a machine's GPU into the cloud fleet with one command and see it on
the console's existing Machines + GPUs pages, tagged provider=byo.

- clients/visor: a BYO worker is a heartbeating presence activity in the org's
  `fleet` tasks namespace (cloud.EmbeddedTasks). fleet.go reads it and folds it
  into the SAME machineView/gpuView the console renders (provider=byo,
  location=on-prem, gpu model + VRAM, online/offline by heartbeat), plus a raw
  GET /v1/fleet/workers. /v1/machines and /v1/gpus union Visor's inventory with
  the BYO workers and degrade gracefully (BYO stays visible if Visor is down).
- cli: `hanzo gpu connect|status|disconnect` — reuses the `hanzo login`
  IAM token (org from its claims; token auto-refresh), detects GPUs via
  nvidia-smi, registers + heartbeats the fleet presence record, and runs an
  outbound worker loop claiming from `gpu-jobs` (pluggable handlers: echo,
  studio.render→local ComfyUI). --daemon installs a systemd --user unit.
- go.mod: hanzoai/tasks v1.46.0 → v1.47.0 (the claim + lease-reaper surface).

E2E (z@hanzo.ai): connect → GB10 'spark' shows provider=byo on
/v1/fleet/workers + /v1/machines + /v1/gpus → echo job claimed + completed.
2026-07-04 12:28:10 -07:00
hanzo-devandGitHub c0e25c2588 fix(bots): auto-create the bound agent on launch so a bot is messageable (#122)
launchBot bound an agent *name* but never created that agent, so
messageBot's in-process run (/v1/agents/:agent/run -> Resolve) 404'd
"agent not found" — a launched bot could not be messaged.

launchBot now create-if-absent's the bound agent via the SAME
POST /v1/agents the console uses (one create path, forwarding the
caller's validated identity -> org-scoped, IDOR-safe), BEFORE launching
the metered machine so a bad request (e.g. a non-catalog model) 400s
before anything is provisioned. Idempotent: an existing agent (409) is
reused. An omitted model takes the deployment default
(deps.AIDefaultModel, a valid catalog model) threaded from config — no
hardcoded model id.

Also add create/update-time model validation: a client-supplied model
outside the gateway's served catalog is a clean 400 (via the optional
types.ModelLister the real gateway client implements) instead of a
confusing run-time 502; fail-open when the catalog can't be enumerated.

Tests: agents model-validation + default (real store); httpAI.Models
against a fake gateway; visor launch->auto-create->message->resolve E2E
incl. the before/after 404->200 gap proof, idempotency, and bad-model
fail-fast (no machine provisioned).
2026-07-04 12:17:29 -07:00
hanzo-devandGitHub 2b435e4005 deps(rag): bump hanzoai/ai v1.800.6 -> v1.800.7 — force gateway embedder at resolution time (fixes RAG ingest hang, #72) (#121) 2026-07-04 11:46:26 -07:00
hanzo-devandGitHub 47421665b3 feat(notify): KMS-only provider creds, remove env fallback (#120)
notify's send surface now reads provider credentials EXCLUSIVELY from cloud's
embedded KMS (cloud.Deps.KMS) at the org-scoped, rotatable ref
orgs/<org>/notify/<svc>/<key> — the same /orgs/<org> namespace
clients/integrations uses, so a cred is seedable + rotatable via
POST /v1/kms/orgs/:org/secrets with no operator-injected env Secret and no
restart. The org is the VALIDATED principal's tenant, never a client header.

Removes the env-first fallback (envCreds/envFirst + the os import): no secret
is ever read from the environment, hard-coded, or logged. A missing key leaves
the value empty and constructProvider fails closed.

Tests rewritten to inject a fake KMS (no env), plus a per-org isolation test
and a regression that creds() ignores the legacy TWILIO_* env entirely.
2026-07-04 11:35:28 -07:00
hanzo-devandGitHub d3ece49517 deps(rag): bump hanzoai/ai v1.800.4 -> v1.800.6 — default embedder targets the Hanzo gateway, not api.openai.com (#119)
Pulls hanzoai/ai#71: the RAG default embedder (object/init.go seed) now points at
the Hanzo gateway (CLOUD_AI_BASE_URL / CLOUD_AI_API_KEY, model text-embedding-qwen3)
instead of an empty ProviderUrl that hit api.openai.com directly. A server-side
embed to api.openai.com from in-cluster crawled ~180-210s and then failed, so RAG
ingest (/v1/rag/embed) hung AND the Qdrant vector collection was never created
(writeDocsToVector sample embed timed out before ensureVectorCollection ran).
Gateway embeddings are <1s (proven live). The seed self-heals an existing
api.openai.com-direct default to the gateway on boot, so this deploy converges the
live default-embed provider with no manual console repoint.
2026-07-04 11:11:47 -07:00
z 8cf2f0683a fix(websearch): admit the validated console principal on /v1/websearch/search
The console (console2 WebSearch module) reaches search through the /cloud proxy
with a signed-in USER BEARER, not the shared X-API-Key. searchGuard required the
key on every call (F2 hardening), so the console got 503/401 — "backend not
initialized" — even though searxng+crawl are deployed and the upstream defaults
are correct.

Reconcile to the ONE-WAY gate the rest of the /v1 data plane uses: at the zip
layer, a request with a validated principal (principal.Validated — X-User-Id
minted by the identity middleware from a verified JWT) proxies straight to
SearXNG; a request with NO principal falls to the unchanged key-based searchGuard
(the hanzo.chat server path). A caller with neither is still refused, so F2 (no
open metasearch proxy) holds — proven by TestSearchNoPrincipalNoKeyRefused.

searchGuard (net/http) is untouched; its 503/401 tests stay green. New coverage:
TestSearchValidatedPrincipalBypassesKey (console bearer, key unset -> 200),
TestSearchNoPrincipalNoKeyRefused (anonymous, key unset -> 503).
2026-07-04 08:50:05 -07:00
zandGitHub 7ffe6dcf67 Merge pull request #117 from hanzoai/fix/agent-run-internal-egress
agent-runner mints M2M inference token from in-cluster IAM (fixes /v1/agents/:ref/run 502). Forward-integrated with main (#118 admin-guard audience). Reconciles live sha-b9639df onto a semver release.
2026-07-04 08:37:34 -07:00
0e960ecaae fix(identity): accept hanzo-admin-guard as a JWT audience (#118)
cloud-api SanitizeIdentity validates the forwarded IAM bearer against
defaultJWTAudiences before granting global-admin (owner==adminOrg). The
admin.hanzo.ai guard is client hanzo-admin-guard, so its tokens carry
aud=hanzo-admin-guard, which was missing from the allowlist -> the bearer
failed validation, resolved anonymous, and the SuperAdmin gate read false
-> 403, even though the token owner IS admin.

Append the guard client_id (forwards-only, mirrors gateway iamauth). Admin
authority still requires owner==adminOrg, so no widening. Pairs with
hanzoai/gateway audience fix.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 06:35:12 -07:00
hanzo-dev b9639dfe7e fix(cloud): agent-runner mints M2M inference token from in-cluster IAM (fixes /v1/agents/:ref/run 502)
pickAIClient built the M2M token URL from cfg.IAMIssuer (=https://hanzo.id), a
Cloudflare-fronted host. In-cluster the runner's server-side POST to
https://hanzo.id/v1/iam/oauth/token 403s with CF edge error 1006, so the
oauth2 client-credentials fetch fails and EVERY POST /v1/agents/:ref/run 502s:
  'cloud: chat completion: oauth2: cannot fetch token: 403 Forbidden / 1006'.

New aiM2MTokenURL resolves the token endpoint split-horizon, mirroring the KMS
login-broker (clients/kmssvc) exactly — one policy, no drift:
  1. CLOUD_AI_IAM_TOKEN_URL override
  2. in-cluster IAM_URL (already wired to http://iam.hanzo.svc for JWKS)
  3. public IAMIssuer fallback (single-process deploys)
IAMIssuer stays https://hanzo.id for JWT iss-validation (untouched). The chat
base URL is pointed in-cluster via CR env CLOUD_AI_BASE_URL (universe).

Proven in-cluster: mint token from iam.hanzo.svc + chat to gateway.hanzo.svc
both 200 (real completion). Unit test pins the 3-branch resolution order.
2026-07-04 05:12:39 -07:00
hanzo-dev 500b9e3afe deps(billing): bump hanzoai/ai v1.800.3 -> v1.800.4 — widget (hz_) keys bill owner org
Pulls in the ai fix that closes the hz_ widget-key free-inference hole: widget
keys now bill the OWNER ORG (object.WidgetKeyOwner), so reserveBudget +
recordUsage + the balance gate all engage instead of running free/unmetered.
Bounded to the restricted widget model set + token cap; fail-secure when a widget
key is unattributable.
2026-07-04 04:41:47 -07:00
hanzo-devandGitHub c68428e87d fix(kms): broker uses in-cluster IAM_URL for token exchange, not public issuer (CF 403s in-cluster loopback) (#116)
The per-tenant KMS secret-sync login broker derived its IAM token-exchange URL from the public issuer (hanzo.id), which Cloudflare 403s for in-cluster server-side POSTs → the sync could never authenticate. Prefer in-cluster IAM_URL (+ CLOUD_KMS_IAM_TOKEN_URL override), fall back to issuer. Unblocks PaaS per-tenant secret env (proven: git-built ai-demo app deployed on maxpower).
2026-07-04 04:05:44 -07:00
bfbedd1bba feat(notify): fold notifyd OTP send surface into the unified cloud binary (#115)
Mounts /v1/notify/{send,send/sms,send/email,health} natively in-process as the
cloud subsystem "notify" (order 139) — the native, in-process replacement for
the standalone notifyd (github.com/hanzoai/notify) Deployment.

notifyd's ONLY production consumer is Hanzo IAM's OTP send
(POST /v1/notify/send?sync=true, event=iam.otp_sent), and the live tenant's
template/provider/event tables are empty, so this folds exactly that contract
and nothing more. It reuses notifyd's OWN public provider packages
(service/{twilio,twilioemail,plivo,mail}) and wire types (pkg/types) — no
duplication of provider plumbing; only the internal-only cred->constructor glue
is mirrored.

Security: unlike the ClusterIP-internal notifyd (which trusted a raw X-Org-Id),
/v1/notify/send is reachable via the public gateway here, so it gates on a
VALIDATED principal and derives the org from principal.Tenant — the same
trust-boundary move clients/auto makes. Credentials come from env (the
KMS-synced notify-twilio Secret) and KMS via cloud.Deps.KMS; none is hard-coded
or logged. Ships a built-in iam.otp_sent template so the fold is strictly more
available than notifyd is today (whose empty store would 400 an OTP send).

Sync-only: the Temporal notify-send async plane is intentionally NOT folded;
async (no ?sync=true) returns 503, exactly as notifyd does without a worker.

Build-gated: go build ./... green; go test ./clients/notify/... green; gofmt/vet
clean. go.mod adds only hanzoai/notify + its provider transitive deps.

Co-authored-by: Hanzo Dev <dev@hanzo.ai>
2026-07-04 03:48:05 -07:00
hanzo-dev 802e4181ef fix(zt): message-hygiene — 503 body names no internal env
The fail-closed 503 body no longer names ZT_CLIENT_ID/ZT_CLIENT_SECRET;
it now reads 'networking is not configured on this deployment' — a
customer-facing string the console renders as a clean 'not available yet'
state. Ops still see the env names in the Warn log at Mount. No behavior
change; the gate() fail-closed contract is identical.
2026-07-04 03:24:53 -07:00
zandGitHub dc4920b79a Merge pull request #114 from hanzoai/feat/slack-integrations-bridge
feat(integrations): @hanzo Slack agent bridge — events/commands/link on /v1/integrations/slack/*
2026-07-04 03:18:33 -07:00
hanzo-dev 7249f79445 fix(integrations): Red delta — recover async turns + shed before dedupe (M-2, M-1)
RED M-2 [MED] — contain panics in the async agent-turn goroutine. The dispatched
turn (handleSlack* → slackAgentReply → agents.RunOnBehalf, a large surface over
UNTRUSTED Slack input) ran UNRECOVERED — middleware.Recover() only wraps the sync
request goroutine — so a panic would crash the ENTIRE shared multi-tenant cloud
binary (every tenant, every subsystem). Introduced slackSpawn: runs an
already-slotted turn in a recovered goroutine (recover defer registered LAST so it
runs FIRST; the slot release still runs after it, so a panicking turn frees its
slot). Test TestSlackTurnPanicRecoveredAndSlotReleased.

RED M-1 [MED] — shed BEFORE burning the dedupe key. The old order was
mark-then-dispatch: MarkSlackEvent recorded the event_id, then a pool-full drop
silently 2xx-acked → Slack never retried and a later retry was deduped away, so
the @mention vanished. New order (events + slash): verify HMAC → resolve org →
TRY-ACQUIRE a pool slot; on shed record NOTHING and return a retriable 429 (Slack
re-delivers when a slot frees — the turn never ran, so no double-run and no burned
key); on acquire → MarkSlackEvent (release the slot on duplicate/error) → spawn.
The fast empty-2xx ack is kept for the normal path. Test
TestSlackShedReturnsNon2xxAndDoesNotRecord.

Also corrected the slack_dedupe.go replica note (we no longer "always 2xx-ack" —
a capacity shed returns a retriable non-2xx and records nothing, so it is not a
double-process).

RED M-3 [MED] deploy single-replica (Recreate + persistent CLOUD_DATA_DIR) — the
universe cloud manifest, owned by the deploy lane; the in-code single-writer
invariant comment is kept accurate here.

go build ./... = 0, go vet ./... = 0, go test ./clients/integrations/
./clients/agents/ -race green (25 tests).
2026-07-04 03:03:36 -07:00
hanzo-dev d49c14d1a0 fix(integrations): address Red review — wire routes, per-org pool, replica scope
RED H1 [HIGH] — wire the bridge into integrations.Mount (was only in a test
helper → the front-door didn't exist in prod). The 5 literal routes are
registered BEFORE the /:provider wildcards (registration-order precedence, same
discipline as clients/agents' static-before-:ref) and are PUBLIC at the JWT
layer: IdentityMiddleware only POPULATES a principal (never rejects) and
DefaultPrice returns 0 for /v1/integrations/* so BillingGate passes through —
reached exactly like /:provider/callback. Auth is HMAC (events/commands) /
signed __Host- cookie (link legs) INSIDE the handler. New test
TestSlackRoutePrecedence proves GET /slack/link hits slackLink (not :provider),
/v1/integrations/slack still resolves the provider view, and the webhook is
reachable with no principal.

RED M1 [MED] — per-org concurrency sub-limit. The agent-turn pool was one
process-global semaphore; one org bursting @hanzo could starve every tenant.
Replaced with orgLimiter (global cap + per-org cap, SLACK_AGENT_ORG_CONCURRENCY
default 8). The org is now resolved SYNC in the webhook path so the pool keys on
the RESOLVED tenant before a slot is taken. New test TestOrgLimiter.

RED M2 [MED] — corrected the false "holds across replicas" dedupe claim: the
table is per-process embedded SQLite (single-writer per HIP-0302), so the billed
webhook path MUST run single-replica (stated as the shipping invariant); a
shared SETNX store is the multi-replica follow-up.

RED L1 [LOW] — moved the dedupe-table DDL into the store's migrate() (store.go)
— fail-loud at Mount, one place — and removed the lazy first-use ensure whose
LoadOrStore-before-run could permanently disable the path on a transient DDL
error. slackBridgeReady now only inits the process pool + link seen-set.

Deferred (flagged for clients/integrations owner): L2 UNIQUE(provider,
external_id)+first-org-wins refusal on duplicate team connect; L3 purge
user:<slackUser>:refresh secrets on disconnect (currently inert after
disconnect, no leak).

go build ./... = 0, go vet ./... = 0, go test ./clients/integrations/
./clients/agents/ -race green (18 + 5 tests).
2026-07-04 02:41:14 -07:00
hanzo-dev 43228b20d6 feat(integrations): Slack agent bridge on the one-binary integrations plane (#45)
Port the hardened @hanzo Slack agent front-door from team-go/pkg/slack into
the unified Hanzo Cloud integrations plane, so Slack is ONE connector aligned
with the one-binary north star. It CONSUMES the existing Slack OAuth provider
(the per-org bot token it seals) and the framework seams
(OrgForExternalID / TokenFor / ConnectionFor); it adds no new custody path and
edits no existing file.

clients/agents:
- onbehalf.go: exported in-process RunOnBehalf(ctx, org, userSub, ref, input) —
  the clean in-process twin of the HTTP run handler (no gateway hop, no
  Cloudflare/IPv6 exposure). Resolves the agent org-scoped, runs it through the
  SAME runAgent -> executeRun -> meter path, bills billingActor(org, userSub)
  against org's ledger. Takes org+userSub DIRECTLY (caller pre-authenticated).

clients/integrations:
- slack_events.go: Slack Events webhook + slash command. HMAC-verified over the
  EXACT raw body with a 5-min replay window; url_verification challenge; routes
  @mention + DM to an on-behalf-of run; durable dedupe on event_id; fast empty
  ack + bounded async worker pool. Posts the reply into the thread with the
  org's bot token, or the link prompt EPHEMERALLY.
- slack_link.go: transplant-safe 3-leg per-user link (__Host- init/link cookies,
  leg1<->leg2 nonce continuity checked BEFORE any exchange, single-use). Binds
  Slack<->Hanzo via hanzo.id OIDC (hanzo-slack client) and seals the refresh
  token per (org, "slack", "user:<slackUser>:refresh").
- slack_verify.go: Slack signature verify + single-use link-state crypto
  (constant-time HMAC over s.stateKey; orthogonal to the OAuth-connect state).
- slack_dedupe.go: durable event-dedupe table as Store methods (no store.go edit).

PER-ORG ISOLATION (ship bar): an event's org comes ONLY from
OrgForExternalID(team_id) — never the payload; the reply uses THAT org's bot
token (TokenFor); the run is THAT org's agent (RunOnBehalf org-scoped). Tests
prove team A's event never resolves/tokens/runs as org B.

Mount wiring (5 routes) is handed to the clients/integrations owner — this
change adds NO Mount edit (clean separation); handlers are (s *svc) methods.

Tests (go test -race, green): HMAC reject (bad/missing/stale), dedupe
idempotency, per-org isolation (end-to-end bot-token capture proves the reply
used the connecting org's token), link transplant-rejected (no/mismatched init
cookie refused before exchange), RunOnBehalf bills the right actor.
2026-07-04 02:10:35 -07:00
hanzo-dev 95cb2ad064 fix(deps): align luxfi/age v1.5.0 go.sum hash with sum.golang.org
The recorded zip h1 for github.com/luxfi/age v1.5.0 (zC/Fw…) did not match
the immutable Go checksum transparency log (sum.golang.org), which records
G69Hb… — the same bits the module proxy and local cache serve. The stale
hash made the ENTIRE module unbuildable: every `go build` failed with a
checksum mismatch / SECURITY ERROR. The /go.mod hash already matched sumdb;
only the zip h1 was wrong. Aligning it to the transparency-log-verified
value unblocks the repo (`go mod verify` -> all modules verified). age is an
indirect dependency; no version bump.
2026-07-04 02:10:18 -07:00
0bef789868 feat(admin): GET /v1/admin/o11y — global fleet observability over the one datastore (#111)
Cross-org fleet o11y for admin.hanzo.ai (global-admin only, s.guard fail-closed):
fleet totals (requests/tokens/cost/errors/orgs/models from hanzo.cloud_usage;
latency p50/p95/p99 + error-rate + services from signoz_traces; log volume from
signoz_logs), usage + log-volume timeseries, and top-N orgs/models/services
leaderboards, plus the fleet Langfuse generation rollup. Un-org-scoped by design
— the one place a fleet operator crosses tenants; a non-admin bearer is refused
403 before a row is read. Reuses the shared aiobject.DatastoreQuery transport
(no second connection) and the compute/analytics honest-empty pattern; admin
reads only, owns no table. Time bounds are positional params, bucket interval a
server-side constant — injection-safe. Pure builders + parsers unit-tested.

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-04 01:54:32 -07:00
zandGitHub 43153cfade Merge pull request #113 from hanzoai/feat/automations-phase1
feat(automations): Connectors+Automations engine — Phase 1 (HIP-0106 #51)
2026-07-04 01:53:55 -07:00
zandGitHub 2f42f5f69d Merge pull request #112 from hanzoai/fix/gosum-luxfi-age
fix(go.sum): realign luxfi/age@v1.5.0 to the proxy content hash (unblocks cloud releases)
2026-07-04 01:53:14 -07:00
hanzo-dev 72a53da165 fix(go.sum): realign luxfi/age@v1.5.0 to the proxy content hash
luxfi/age@v1.5.0 was force-retagged upstream: proxy.golang.org now serves
content hashing to G69HbSV… while go.sum pinned the stale zC/Fw… → every
cloud release fails at `go mod download` with a SECURITY ERROR (checksum
mismatch), blocking the whole pipeline. Dockerfile already sets GOSUMDB=off,
so the mismatch is against the committed go.sum, not the sumdb. Realign to the
exact hash CI computes from the proxy (same fix IAM shipped as fee44857).
2026-07-04 01:53:00 -07:00
hanzo-dev e93b6262bd fix(automations): RED fix set — exactly-once run bookkeeping + SSRF/caps/audit hardening
Addresses CTO's post-RED fix set (isolation boundary already approved airtight).

MED-1 (exactly-once metering/audit/persistence across ALL entrypoints): the
durable path is now the SINGLE owner of run bookkeeping. FlowRunWorkflow runs a
RecordRunStartActivity keyed on the workflow id (workflow.GetInfo — a scheduled
cron mints a fresh id per tick, so each tick is its own metered run despite the
schedule embedding one fixed FlowRunInput.RunID). Store CreateRunIfAbsent (row
idempotency) + ClaimMeter (atomic metered-flag 0->1) meter+audit only the winner,
so manual /run, MCP, and cron never double-bill. Manual /run no longer meters/
audits — it only CreateRunIfAbsent for immediate visibility. RecordRunEndActivity
records terminal status. Proof: TestScheduledRunMeteredExactlyOnce (a tick meters
once + shows in listRuns; two ticks = two distinct runs) + TestRunStartBookkeeping-
Idempotent (recordRunStart twice = one meter, one row).

MED-2 (honest SSRF blocklist): isPublicIP now rejects the IANA special-use ranges
Go's net helpers miss — 100.64/10 CGNAT (Alibaba metadata 100.100.100.200),
0/8, 192.0.0/24, 192.0.2/24, 192.88.99/24, 198.18/15, 198.51.100/24, 203.0.113/24,
240/4, 64:ff9b::/96 NAT64 — plus v4-mapped-v6 normalization. Comment no longer
overclaims a complete cloud-metadata blocklist. TestIsPublicIP covers each range +
public IPs still allowed.

MED-3 + LOW-4: step-count (<=256) + serialized-tree (<=512KB) caps at create /
version / operation time -> honest 422; resume payload bounded (<=64KB) -> 413.

LOW-2: per-org concurrency limiter (429) on run-starts + synchronous MCP tool calls
(bounds the core.delay goroutine lever). TestConcurrencyLimiter + TestFlowStepCap +
TestResumePayloadBounded.

LOW-1: MCP meters/audits AFTER Run, outcome derived from the real result — a failed
/ SSRF-blocked / not-connected call audits as error and is NOT billed. TestMCPAuditOutcome.

LOW-3: updateFlow validates publishedVersionId names an existing version OF THIS
FLOW in-org (else 422). TestUpdateFlowPublishedVersionValidated.

INF-1: register() panics at init on a <connector>_<action> tool-name collision so a
future connector can't silently make MCP dispatch ambiguous. TestToolNameCollisionPanics.

Tests: 25/25 green (CGO=0 build/vet/test; -race clean under cgo). Full module builds;
cmd/cloud links. catalog.json untouched.
2026-07-04 01:38:15 -07:00
hanzo-dev f3d2ece9f0 feat(integrations): Slack connect lights up on the public client_id alone
Authorize needs only SLACK_CLIENT_ID (a public value in every consent URL);
the SECRET is required only at the callback token exchange. Gate available/
connect on client_id so an org reaches Slack's Allow screen as soon as the
public id is set, while a deployment still missing SLACK_CLIENT_SECRET fails
the exchange with an honest ?error=slack (never a dead-end).
2026-07-04 01:31:54 -07:00
zeekayandClaude Fable 5 bc89be43ac fix(deps): bump hanzoai/ai v1.800.2 -> v1.800.3 for brand .cloud CORS fix
Pulls the cors_filter static-allowlist fix so console.lux.cloud (and
zoo/pars brand consoles) stop getting 403 "origin is not allowed" on
/v1/signin. Cleared stale sum.golang.org-poisoned go.sum entries for
re-tagged luxfi/{age,precompile,keys} (GOPRIVATE direct re-records the
current content hashes; matches the repo's GOSUMDB-off CI recipe).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 01:20:55 -07:00
hanzo-dev 47f58c0e11 feat(automations): merge full 701-piece catalog + /v1/automations OpenAPI
- catalog/catalog.json: 706 pieces (5 Tier-A executable connectors + 701
  ActivePieces catalogue entries); action/trigger props normalized string[]
  -> []PropSpec so PieceMetadata unmarshals at Mount (boot-parses green).
- docs/automations-openapi.yaml: OpenAPI 3.0.3, 13 paths all under /v1/automations.
- http_test: assert catalogue invariant (PieceCount==len, Tier-A present) not
  the seed-pinned count.
2026-07-04 01:09:57 -07:00
hanzo-dev 42c995c077 feat(automations): Phase-1 Connectors+Automations engine (HIP-0106 #51)
Native-Go /v1/automations/* subsystem in the unified cloud binary. Composes
three existing seams, never reinvents them:

- clients/integrations  — per-org connector creds via integrations.TokenFor
  (KMS-sealed, fail-closed); connectors never touch KMS directly.
- cloud.EmbeddedTasks    — the ONE shared in-process durable engine; a flow
  runs as a durable workflow in the OWNER's namespace (per-org lazy worker,
  mirroring ai/object/ingest_tasks.go).
- clients/principal      — the ONE tenant gate on every data handler.

Isolation is physical: ONE SQLite file, org column + org-led index on every
table; the durable activity's SOLE credential scope is FlowRunInput.Owner —
the VALIDATED org set at flow-start, never a client-supplied field.

Surface: pieces catalogue (go:embed), flows CRUD + versions + FlowOperation
apply, durable runs (start/list/get/resume via SignalWorkflow), enable/disable
(POLLING -> CreateSchedule), and a HIP-0300 MCP JSON-RPC tool surface
(/v1/automations/mcp) exposing every connector action as <connector>_<action>.

Connectors (Tier-A, self-registering): core (http_request SSRF-guarded via a
dialer Control hook, delay, code data-mapper, wait_for_approval signal
waitpoint), slack (send_message), github + google_sheets/drive (fail closed
until integrations custodies their tokens).

Metering + audit on flow-run start and MCP tool call. Order 148 (after
integrations 137, before ai's /v1/* catch-all 150).

Tests (16, all green with -race): store org-isolation, HTTP org-gating (403),
durable flow run reaching SUCCEEDED with threaded step outputs on an embedded
tasks engine, connector token isolation (in.Owner is the sole cred scope),
MCP tools/list + gated tools/call dispatch, pieces catalogue.
2026-07-04 01:03:06 -07:00
0b407430c5 feat(o11y): HTTP request + LLM/agent traces over ZAP (single provider) (#110)
* feat(o11y): emit an OTel SERVER span per /v1/* request over the ZAP wire

Cloud installed a ZAP tracer provider (cmd/cloud initTelemetry) but nothing in
the handler chain opened a span, so no request ever flowed through it — the o11y
Monitoring tab saw zero hanzo-cloud request traces (receiver="zap" span count
was flat-zero while logs streamed over ZAP).

TracingMiddleware (middleware_tracing.go) opens one SERVER span per /v1/*
request off the GLOBAL tracer (= the ZAP provider), records the OTel HTTP
semantic-convention attributes (method, route, status) + request_id/org, maps
error/5xx to an error span status, and writes the span context back onto the
request via SetContext so every downstream span (agent.run -> agent.step -> the
chat client span in clients/aihttp) parents under it: one trace tree per
request. Health/readiness/metrics + non-/v1 paths are skipped so probes never
flood the trace store. Wired right after RequestID in the canonical pipeline
(serve.go) so the whole authenticated chain nests under it.

c.Path()/c.Method()/headers are zero-copy views over the fasthttp request
buffer, which is recycled for the next request BEFORE the batch span processor
serializes the span asynchronously — so retained views corrupt (live: a
GET /v1/models span exported with http.route="/v1/chat/c..."). strings.Clone
pins our own copy for every retained attribute. Tests cover emission, attribute
mapping, error status, parent/child propagation, the skip set, and an env-gated
on-wire live test (CLOUD_ZAP_LIVE_ENDPOINT) that ships real spans to a ZAP
receiver — the async-export + ctx-reuse path the in-memory recorder can't model
(and the one that surfaced the corruption).

* feat(o11y): make cloud the single tracer-provider owner — one wire (ZAP)

The fused cloud binary set the ZAP provider first, then ai.Bootstrap (during
MountAll) called hanzoai/ai object.InitTelemetry which, seeing the CR's
OTEL_EXPORTER_OTLP_ENDPOINT, installed a SECOND, competing OTLP provider. OTel
global delegation is first-writer-wins for handles created before the first
SetTracerProvider (cloud's package-level tracers keep ZAP), but the ai GenAI
tracer is resolved lazily AFTER the second Set, so its spans stranded on
OTLP(:4318) while ZAP owned the rest — the split that left receiver="zap" span
count at zero for hanzo-cloud (verified live: spans arrived only via
receiver="otlp").

Composition-root fix: once cloud installs the ZAP provider, clear the
OTLP-exporter env (OTEL_EXPORTER_OTLP_ENDPOINT / _TRACES_ENDPOINT) so no embedded
subsystem installs a competing OTLP provider. Exactly one provider (ZAP), one
wire, deterministic regardless of CR env drift. In the fused binary OTLP is only
ever the collector's interop RECEIVER, never cloud's exporter; standalone
cmd/aid (no ZAP endpoint) is unaffected and keeps its OTLP path.

---------

Co-authored-by: hanzo-dev <dev@hanzo.ai>
2026-07-04 00:56:42 -07:00
hanzo-dev 5998e664ff fix(kb): RED H1/M1 — inject X-Piece-Run-Secret on the auto piece-run call
The auto engine now gates /v1/auto/pieces/{piece}/run on a shared secret (it
trusts X-Org-Id absolutely, so the write+SSRF surface needs an in-band caller
proof). cloud is the ONLY legitimate caller — it resolves each org's real token
and pins the provider URL — so it presents the secret (from KMS, the same
PIECES_RUNNER_SECRET) as X-Piece-Run-Secret. pieceSync fails closed if the
secret is unset (a doomed call the engine would 403 anyway).
2026-07-04 00:05:48 -07:00
hanzo-dev b004b2327d feat(auto+kb): hybrid connector layer — /v1/auto proxy + activepieces long-tail
Mounts workflow automation + the ~280-app activepieces long tail in-platform,
per-org, through the ONE knowledge store. Go core + JS on-demand.

clients/auto: /v1/auto/* per-org REVERSE PROXY to the standalone Hanzo Auto
engine (one engine, one store — not re-embedded). The auto engine trusts
X-Org-Id absolutely, so this proxy IS the trust boundary: it GATES on a
validated principal (refuses the anon-forge X-Org-Id-with-no-credential path)
and re-stamps outbound identity from validated values only (strips every
smuggled authority alias). Pure gate+proxy in clients/auto/proxy (5 isolation
tests: anon-forge 403, per-org forward, smuggled-header strip, path preserved).

clients/kb: the first LONG-TAIL connector (notion). Identical OAuth lifecycle
(HMAC-org-bound state, KMS token path) but its PULL runs the activepieces JS
piece through the auto engine's on-demand runner (sync_piece.go) instead of
native Go — then files each record via the SAME framework.Ingest path. One
ingestion path; a JS-sourced doc lands in the same per-org store+index as a
Go-sourced one. clients/kb/notion is the pure record-shaper (6 tests).

ONE catalog: /v1/kb/connectors/catalog lists native Go + long-tail piece
connectors in one list, each badged kind native|piece (3 tests).

RED LOW-1: collection() + kmsRef() now route org through provisioning.SanitizeOrg
(the codebase's ONE normalizer) so the physical Qdrant namespace + KMS path are
injective in the owner ("a b" != "a_b") — defense in depth under the payload.org
filter. Injectivity tests + KB integration tests updated to derive the collection
through the helper (robust to the normalizer).

All tests green under CGO=0 (production config). Full binary boots; /v1/auto
mounted, anon-forge 403, catalog gated, spine (kb/framework health) 200.
2026-07-04 00:05:48 -07:00
1257 changed files with 189644 additions and 12199 deletions
+12
View File
@@ -0,0 +1,12 @@
# ~7-line canonical caller — all real config lives in /hanzo.yml.
# Test gate on OUR arc pool; release.yml owns the image + v* tags.
name: CI/CD
on:
workflow_dispatch:
push:
branches: [main]
pull_request:
jobs:
cicd:
uses: hanzoai/ci/.github/workflows/build.yml@v1
secrets: inherit
+133
View File
@@ -0,0 +1,133 @@
name: containment
# Guards the Stage-1 byzantine ceremony containment (clients/controlplane,
# build tag `controlplane`). Its increment-1 crypto is stub/forgeable BY
# DESIGN (SHA256-of-public-inputs commitments, symmetric-HMAC
# proof-of-possession, seed-derived threshold shares — see
# clients/controlplane/doc.go) and MUST NEVER reach a release/serve binary.
# Three independent checks; any one failing blocks the PR:
#
# 1. grep (tag) — no build/release invocation anywhere in the repo
# (Dockerfile, Makefile, shell scripts, any workflow) may pass a `-tags`
# value containing `controlplane` to go build/vet/run/install. The
# package's own `//go:build controlplane` tag declarations
# (clients/controlplane/*) are the thing being guarded, not a violation,
# and are excluded by path.
# 2. grep (spoof) — no build/release invocation may pass
# `-X testing.testBinary=1` (or any -ldflags containing it) to a REAL
# `go build`. That linker flag is what `go test` itself uses to make
# testing.Testing() report true (cmd/go/internal/load/test.go) — the
# runtime guard in containment.go trusts that signal, so this is the one
# concrete way to spoof it in a non-test binary. This grep is what turns
# "someone could type this" into "CI fails the PR that types it".
# 3. build — `go build ./...` (no tag — exactly what the Dockerfile
# and Makefile run) must not link clients/controlplane into any cmd/
# main, and `go build ./clients/controlplane/...` with no tag must match
# zero buildable packages (proves the tag still gates every file in it).
#
# Runtime belt-and-suspenders (defense in depth, not a substitute for the
# above): clients/controlplane/containment.go fail-closed panics if its stub
# crypto is ever constructed outside a go-test binary (testing.Testing()==
# false) — see TestContainment_NonHarnessProcessRefuses in
# containment_test.go. KNOWN RESIDUAL: testing.Testing() is a linker-set
# string var (testing.testBinary), not cryptographically bound to "actually
# is a test" — `-ldflags="-X testing.testBinary=1"` spoofs it in a real
# binary. Check #2 above is the mitigation: it fails the PR that would ship
# that flag. Closing the residual for real needs a signal `go build` cannot
# produce at all (increment-2, tracked in doc.go) rather than one merely
# absent by convention.
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
controlplane-containment:
runs-on: [hanzo-build-linux-amd64]
steps:
- uses: actions/checkout@v4
- name: grep — no build/release path may set -tags controlplane, or spoof testing.Testing()
run: |
set -euo pipefail
hits=0
# NOTE: exclusions are plain substring matches on the path (not
# anchored to a leading "./") so this is robust across grep
# implementations that format recursive-search paths differently.
# char class includes `!` so a build-constraint negation form
# (`-tags '!x,controlplane'`) cannot slip the grep. (Belt only: the
# positive-proof step below is the syntax-agnostic guarantee — the
# package has zero untagged files, so importing it into serve code
# fails the untagged `go build ./...` regardless of any -tags syntax.)
if grep -RnE -- '-tags[= ]*["'"'"']?[!A-Za-z0-9_, ]*\bcontrolplane\b' \
--exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.claude --exclude-dir=vendor \
. 2>/dev/null \
| grep -v '\.git/' \
| grep -v 'clients/controlplane/' \
| grep -v '.github/workflows/containment.yml:'; then
echo "::error::found a build/release invocation passing -tags controlplane — clients/controlplane's stub crypto must never enter a release/serve binary (see clients/controlplane/doc.go)"
hits=1
fi
if grep -RnE -- 'testing\.testBinary' \
--exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.claude --exclude-dir=vendor \
. 2>/dev/null \
| grep -v '.github/workflows/containment.yml:'; then
echo "::error::found a reference to testing.testBinary outside the Go toolchain itself — this is the linker var that spoofs testing.Testing() in a real (non go-test) binary; the containment.go runtime guard trusts that signal, so setting it anywhere in a real build path defeats it (see doc.go)"
hits=1
fi
if [ "$hits" -ne 0 ]; then exit 1; fi
echo "OK: no build/release path sets -tags controlplane or spoofs testing.Testing()"
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: go env for private modules
env:
GH_PAT: ${{ secrets.GH_PAT }}
# GOPRIVATE names exactly the namespace that is private. github.com/hanzoai/*
# is: ai, account, commerce, orm, xorm, beego, csqlite and ~30 more are
# private repos, so they must resolve direct+authenticated and skip a sumdb
# that cannot see them. Everything else stays on the public proxy + checksum
# db, which is what makes a module hash immutable: zap-proto (all 55 repos)
# and luxfi (all 37 deps here) are public and proxy-served.
#
# This previously named zap-proto — public, and never the reason anything
# here was direct — and then set GOSUMDB=off to compensate for hanzoai/*
# being absent, which disabled checksum verification for EVERY module in the
# build, public ones included. Naming the private namespace is what the off
# switch was standing in for.
run: |
git config --global url."https://x-access-token:${GH_PAT}@github.com/".insteadOf "https://github.com/"
{
echo "GOPRIVATE=github.com/hanzoai/*"
echo "GOPROXY=https://proxy.golang.org,direct"
} >> "$GITHUB_ENV"
- name: positive proof — clients/controlplane is unreachable from the default build
run: |
set -euo pipefail
go build ./...
for m in $(go list ./cmd/...); do
if go list -deps "$m" | grep -qx 'github.com/hanzoai/cloud/clients/controlplane'; then
echo "::error::$m links clients/controlplane into a real binary — containment breach"
exit 1
fi
done
out="$(go build ./clients/controlplane/... 2>&1 || true)"
if ! printf '%s' "$out" | grep -q 'matched no packages'; then
echo "::error::clients/controlplane built successfully WITHOUT -tags controlplane (containment breach): $out"
exit 1
fi
echo "OK: containment holds — clients/controlplane has zero buildable files by default and is linked into no cmd/ binary"
+319 -45
View File
@@ -67,8 +67,12 @@ jobs:
# ARC ephemeral runners match jobs targeting the scale-set NAME as a label.
runs-on: [hanzo-build-linux-amd64]
outputs:
version: ${{ steps.ver.outputs.version }}
version_v: ${{ steps.ver.outputs.version_v }}
# The FINAL assigned version comes from the Tag step (atomic free-version
# assignment), NOT the compute step — under concurrency the compute value may
# have been superseded. notify-universe must roll the version that was actually
# tagged + whose image was actually retagged.
version: ${{ steps.tag.outputs.version }}
version_v: ${{ steps.tag.outputs.version_v }}
steps:
- name: Checkout (full history + all tags — the version floor is read from tags)
uses: actions/checkout@v4
@@ -92,9 +96,9 @@ jobs:
# an image (even from a run that died before tagging) is never reused.
cont_max=""
if command -v gh >/dev/null 2>&1; then
cont_max="$(GH_TOKEN="$GH_PAT" gh api --paginate \
'/orgs/hanzoai/packages/container/cloud/versions' \
--jq '.[].metadata.container.tags[]' 2>/dev/null \
cont_max="$(GH_TOKEN="$GH_PAT" gh api \
'/orgs/hanzoai/packages/container/cloud/versions?per_page=100' \
--jq '.[].metadata.container.tags[]?' 2>/dev/null \
| sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1 || true)"
fi
@@ -106,12 +110,12 @@ jobs:
major="${max%%.*}"; rest="${max#*.}"; minor="${rest%%.*}"; patch="${rest##*.}"
version="${major}.${minor}.$((patch + 1))"
# Refuse to proceed if the number we intend to mint already exists as a
# git tag (a concurrent run beat us — the serialized lane makes this a
# can't-happen, but fail loud rather than clobber).
# This version is a STARTING HINT only. It labels the smoke-built image and
# seeds the OCI metadata; the FINAL version is assigned atomically in the Tag
# step (which recomputes + retries on collision), so a taken number here is
# NOT fatal — the Tag step finds the next free one. Just note it and proceed.
if git rev-parse -q --verify "refs/tags/v${version}" >/dev/null; then
echo "::error::computed v${version} already exists as a git tag — aborting to avoid collision"
exit 1
echo "note: hint v${version} already tagged — the Tag step will assign the next free version"
fi
echo "version=${version}" >> "$GITHUB_OUTPUT"
@@ -120,12 +124,65 @@ jobs:
echo "sha_short=$(git rev-parse --short "$GITHUB_SHA")" >> "$GITHUB_OUTPUT"
echo "Next release: v${version} (git_max='${git_max:-none}' container_max='${cont_max:-none}')"
# Console-embed cachebust. The console clone+build layer is keyed on this;
# prefer hanzoai/console main HEAD so a CONSOLE-ONLY change re-embeds without
# needing a cloud commit (cloud-sha alone froze the embed between cloud pushes).
# git ls-remote must CLEAR the extraheader actions/checkout installs (it carries
# THIS repo's GITHUB_TOKEN, which 404s the cross-repo console lookup); gh is not
# on the runner. If resolution yields nothing, fall back to the cloud sha — still
# unique per cloud commit, so the embed is never frozen. Either way THIS build
# busts (new value) and re-clones console main fresh.
console_head="$(git -c 'http.https://github.com/.extraheader=' ls-remote \
"https://x-access-token:${GH_PAT}@github.com/hanzoai/console.git" refs/heads/main 2>/dev/null | cut -f1 || true)"
cachebust="${console_head:-$GITHUB_SHA}"
echo "cachebust=${cachebust}" >> "$GITHUB_OUTPUT"
echo "console cachebust: ${cachebust} (console_head='${console_head:-none}')"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker-container
driver-opts: network=host
- name: Mirror credential (registry.hanzo.ai)
# Dual-host: pull the KMS deploy kubeconfig (same Universal Auth flow
# the hanzoai/ci reusable uses), read the cluster-synced
# registry-credentials dockerconfig, and log in. Best-effort: absent
# creds → GHCR-only release, never a blocked tag.
env:
KMS_CLIENT_ID: ${{ secrets.KMS_CLIENT_ID }}
KMS_CLIENT_SECRET: ${{ secrets.KMS_CLIENT_SECRET }}
KMS_ENDPOINT: ${{ vars.KMS_ENDPOINT || 'https://kms.hanzo.ai' }}
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: |
set -uo pipefail
# Direct credential first (repo/org secret — works on private repos,
# where the Free plan hides org KMS secrets); KMS kubeconfig fallback.
if [ -n "${REGISTRY_USER:-}" ] && [ -n "${REGISTRY_PASSWORD:-}" ]; then
echo "$REGISTRY_PASSWORD" | docker login registry.hanzo.ai -u "$REGISTRY_USER" --password-stdin
echo "MIRROR_OK=1" >> "$GITHUB_ENV"; exit 0
fi
[ -z "${KMS_CLIENT_ID:-}" ] && { echo "no KMS creds — mirror skipped"; exit 0; }
TOKEN=$(curl -sf "$KMS_ENDPOINT/v1/kms/auth/login" -H 'Content-Type: application/json' -d "{\"clientId\":\"$KMS_CLIENT_ID\",\"clientSecret\":\"$KMS_CLIENT_SECRET\"}" | jq -r '.accessToken // empty')
[ -z "$TOKEN" ] && { echo "KMS login failed — mirror skipped"; exit 0; }
KC=$(curl -sf "$KMS_ENDPOINT/v1/kms/orgs/hanzo/secrets/deploy/KUBECONFIG?env=prod" -H "Authorization: Bearer $TOKEN" | jq -r '.secret.value // empty')
[ -z "$KC" ] && { echo "no KUBECONFIG in KMS — mirror skipped"; exit 0; }
echo "$KC" | base64 -d > "$RUNNER_TEMP/kubeconfig"
command -v kubectl >/dev/null 2>&1 || {
KVER=$(curl -fsSL https://dl.k8s.io/release/stable.txt)
mkdir -p "$HOME/.local/bin"
curl -fsSL "https://dl.k8s.io/release/${KVER}/bin/linux/amd64/kubectl" -o "$HOME/.local/bin/kubectl" && chmod +x "$HOME/.local/bin/kubectl"
export PATH="$HOME/.local/bin:$PATH"
}
CFG=$(KUBECONFIG="$RUNNER_TEMP/kubeconfig" kubectl -n hanzo get secret registry-credentials -o jsonpath='{.data.\.dockerconfigjson}' 2>/dev/null | base64 -d || true)
[ -z "$CFG" ] && { echo "registry-credentials unreadable — mirror skipped"; exit 0; }
UP=$(echo "$CFG" | jq -r '.auths["registry.hanzo.ai"].auth // empty' | base64 -d)
[ -z "$UP" ] && { echo "no registry auth — mirror skipped"; exit 0; }
echo "::add-mask::${UP#*:}"
echo "${UP#*:}" | docker login registry.hanzo.ai -u "${UP%%:*}" --password-stdin
echo "MIRROR_OK=1" >> "$GITHUB_ENV"
- name: Log in to ghcr.io (GH_PAT — writes the cloud package despite its ai-repo linkage)
uses: docker/login-action@v3
with:
@@ -159,10 +216,15 @@ jobs:
load: true
tags: cloud:smoke
labels: ${{ steps.meta.outputs.labels }}
# gh_token: BuildKit secret the Dockerfile consumes to fetch private
# Bust the console clone+build layer every release (the cloud commit sha is
# unique per push) so the embed re-fetches console main HEAD fresh — never the
# frozen snapshot the persistent BuildKit cache would otherwise serve forever.
build-args: |
CONSOLE_CACHEBUST=${{ steps.ver.outputs.cachebust }}
# GIT_AUTH_TOKEN: BuildKit secret the Dockerfile consumes to fetch private
# cross-org Go modules (hanzoai/*, luxfi/*) over authenticated git.
secrets: |
gh_token=${{ secrets.GH_PAT }}
GIT_AUTH_TOKEN=${{ secrets.GH_PAT }}
- name: Smoke test — the binary MUST boot to "listening" with no crash signature
run: |
@@ -231,6 +293,158 @@ jobs:
echo "SMOKE PASS: cloud:smoke booted to \"listening\" with no crash signature"
# ── Functional smoke — authenticated per-subsystem probe (the REAL gate) ─────
# The boot check above proves the process REACHES "listening"; this proves the
# mounted HTTP surface actually WORKS. /smoke (cmd/smoke, baked into the image)
# hits ONE side-effect-free read per core subsystem and FAILS the release on any
# broken code — above all a 402 on a READ (the balance-gate-over-blocks-reads
# regression) or a 5xx (a crash, e.g. the /v1/billing/usage self-dispatch 500).
# So a release can never ship with chat/billing/projects/kms/... down.
- name: Functional smoke — per-subsystem probe (fails the release if a core endpoint is broken)
env:
KMS_CLIENT_ID: ${{ secrets.KMS_CLIENT_ID }}
KMS_CLIENT_SECRET: ${{ secrets.KMS_CLIENT_SECRET }}
KMS_ENDPOINT: ${{ vars.KMS_ENDPOINT || 'https://kms.hanzo.ai' }}
# A KMS-provisioned short-lived smoke bearer, injected as a secret (NEVER
# hardcoded). Absent → the anonymous matrix still gates public/authed and
# catches every 402-on-read / 5xx.
SMOKE_TOKEN: ${{ secrets.SMOKE_TOKEN }}
run: |
set -euo pipefail
IMAGE=cloud:smoke
CID=""
cleanup() { [ -n "$CID" ] && docker rm -f "$CID" >/dev/null 2>&1 || true; }
trap cleanup EXIT
KEY="$(head -c 32 /dev/urandom | base64 | tr -d '\n')"
CID="$(docker run -d \
--tmpfs /data:rw,size=64m \
-e CLOUD_DATA_DIR=/data -e CLOUD_ENV=smoke -e CLOUD_KMS_MASTER_KEY_REF="$KEY" \
"$IMAGE")"
# Wait for the HTTP listener to bind (or the process to die).
up=0
for _ in $(seq 1 60); do
lg="$(docker logs "$CID" 2>&1 || true)"
printf '%s' "$lg" | grep -q '"message":"listening"' && { up=1; break; }
[ "$(docker inspect -f '{{.State.Running}}' "$CID" 2>/dev/null || echo false)" != "true" ] && break
sleep 1
done
if [ "$up" != 1 ]; then
echo "::group::boot logs"; docker logs "$CID" 2>&1 || true; echo "::endgroup::"
echo "FUNCTIONAL SMOKE INFRA FAIL: image never reached \"listening\""
exit 1
fi
# Token: prefer the injected secret; else mint from KMS (a provisioned smoke
# identity); else run the anonymous matrix. Never hardcoded.
if [ -z "${SMOKE_TOKEN:-}" ] && [ -n "${KMS_CLIENT_ID:-}" ]; then
KT=$(curl -sf "$KMS_ENDPOINT/v1/kms/auth/login" -H 'Content-Type: application/json' \
-d "{\"clientId\":\"$KMS_CLIENT_ID\",\"clientSecret\":\"$KMS_CLIENT_SECRET\"}" | jq -r '.accessToken // empty' || true)
[ -n "$KT" ] && SMOKE_TOKEN=$(curl -sf "$KMS_ENDPOINT/v1/kms/orgs/hanzo/secrets/smoke/TOKEN?env=prod" \
-H "Authorization: Bearer $KT" | jq -r '.secret.value // empty' || true)
fi
if [ -n "${SMOKE_TOKEN:-}" ]; then echo "::add-mask::$SMOKE_TOKEN"; echo "smoke: AUTHENTICATED matrix"; else echo "smoke: ANONYMOUS matrix (no SMOKE_TOKEN wired)"; fi
# /smoke is baked into the image (Dockerfile) — exec it INSIDE the container,
# so it probes the real mounted surface at localhost:8080 with no port/network
# plumbing. A non-zero exit here fails the release BEFORE any image is pushed.
docker exec \
-e SMOKE_BASE_URL=http://127.0.0.1:8080 \
-e SMOKE_TOKEN="${SMOKE_TOKEN:-}" \
"$CID" /smoke
# ── Migration smoke — the gate the v1.800.1 crashloop would have tripped ─────
# The plain smoke above boots on a FRESH /data, so every subsystem's migrate()
# takes its CREATE-TABLE path and no forward-migration is exercised — which is
# exactly why a DDL valid on a fresh store but broken on a pre-existing one (an
# index over a not-yet-ADDed column: affiliates referrer_org in v1.800.1, wallets
# project/agent before it) sailed through CI and took api.hanzo.ai down. This
# step reproduces the REAL prod upgrade path: boot the PRIOR released image to lay
# its on-disk (cek-encrypted) SQLite schema into a persistent volume, then boot
# the candidate over that SAME volume and require it to still reach "listening".
# A migrate() that assumes a fresh store dies here, before any image is pushed.
- name: Migration smoke — candidate MUST boot over the PRIOR release's on-disk schema
env:
# The image whose on-disk schema a prod upgrade migrates FROM — the tag the
# fleet runs today. Bump to the last-DEPLOYED tag as releases roll (override
# without a code change via the SMOKE_MIGRATION_BASELINE repo/org variable).
BASELINE: ${{ vars.SMOKE_MIGRATION_BASELINE }}
run: |
set -euo pipefail
BASELINE="${BASELINE:-ghcr.io/hanzoai/cloud:v1.799.19}"
CANDIDATE=cloud:smoke
VOL="cloudmig-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
B1=""; B2=""
cleanup() { docker rm -f "$B1" "$B2" >/dev/null 2>&1 || true; docker volume rm "$VOL" >/dev/null 2>&1 || true; }
trap cleanup EXIT
docker volume create "$VOL" >/dev/null
# ONE throwaway 32-byte master key for BOTH boots: cek seals each per-db DEK
# under it on the baseline boot and unwraps it on the candidate boot. A
# mismatched key fails closed (never opens), so sharing it is what puts the
# MIGRATE path — not a decrypt error — under test.
KEY="$(head -c 32 /dev/urandom | base64 | tr -d '\n')"
boot() { # $1=image $2=name -> prints container id
docker run -d --name "$2" \
-v "$VOL":/data \
-e CLOUD_DATA_DIR=/data \
-e CLOUD_ENV=smoke \
-e CLOUD_KMS_MASTER_KEY_REF="$KEY" \
"$1"
}
wait_listen() { # $1=container -> 0 if "listening", 1 if it died / timed out
for _ in $(seq 1 90); do
lg="$(docker logs "$1" 2>&1 || true)"
printf '%s' "$lg" | grep -q '"message":"listening"' && return 0
[ "$(docker inspect -f '{{.State.Running}}' "$1" 2>/dev/null || echo false)" != "true" ] && return 1
sleep 1
done
return 1
}
# A fresh docker named volume is root:root 0755, but the cloud image runs
# NON-ROOT, so it cannot create cek's <db>.cek.lock under /data (the single-boot
# smoke only worked because --tmpfs is world-writable). Make the shared volume
# writable for BOTH boots, re-opening it between them so the candidate can read
# the baseline's files even if their runtime UIDs differ.
chmod_vol() { docker run --rm --user 0 -v "$VOL":/data --entrypoint sh "$CANDIDATE" -c 'chmod -R 0777 /data'; }
# Boot 1 — the prior release writes its real schema into the volume. It must
# reach "listening" (proof every subsystem migrated + its DB is on disk); if
# the pinned baseline can't boot in this env the gate is blind, so fail loud.
echo "migration baseline: $BASELINE"
pulled=0; for _ in 1 2 3; do if docker pull "$BASELINE"; then pulled=1; break; fi; sleep 5; done
[ "$pulled" = 1 ] || { echo "MIGRATION SMOKE INFRA FAIL: cannot pull baseline $BASELINE"; exit 1; }
chmod_vol
B1="$(boot "$BASELINE" cloudmig_base)"
if ! wait_listen "$B1"; then
echo "::group::baseline boot logs"; docker logs "$B1" 2>&1 || true; echo "::endgroup::"
echo "MIGRATION SMOKE INFRA FAIL: baseline $BASELINE did not reach \"listening\" — cannot stage the prior schema (inspect/bump SMOKE_MIGRATION_BASELINE)"
exit 1
fi
docker stop "$B1" >/dev/null
chmod_vol
# Boot 2 — the candidate migrates that on-disk schema IN PLACE. This is the gate.
B2="$(boot "$CANDIDATE" cloudmig_cand)"
listening=0; wait_listen "$B2" && listening=1
logs="$(docker logs "$B2" 2>&1 || true)"
echo "::group::candidate migration boot logs"; printf '%s\n' "$logs"; echo "::endgroup::"
# 'no such column'/'no such table' is the exact index-before-ADD-COLUMN crash;
# 'panic' catches any generic Mount failure. The load-bearing check is the
# "listening" assertion below — a migrate() crash exits before it.
if printf '%s' "$logs" | grep -Eiq 'panic|no such column|no such table'; then
echo "MIGRATION SMOKE FAIL: candidate logged a DDL/migration error over the prior schema (the v1.800.1-class regression)"
exit 1
fi
if [ "$listening" -ne 1 ]; then
echo "MIGRATION SMOKE FAIL: candidate did NOT reach \"listening\" over the $BASELINE schema — a subsystem's migrate() crashes on a pre-existing store"
exit 1
fi
echo "MIGRATION SMOKE PASS: candidate booted to \"listening\" over the $BASELINE on-disk schema"
- name: Push (cache hit from the smoke build — publishes the tested image)
id: push
uses: docker/build-push-action@v6
@@ -238,49 +452,109 @@ jobs:
context: .
platforms: linux/amd64
push: true
# Push ONLY the immutable, per-commit sha- tag (always unique — never races)
# and the floating latest. The v<X.Y.Z> version is NOT pushed here: the
# compute-step version may be claimed by a concurrent release between compute
# and now, and pushing it would clobber that release's :vX image (mutable tag
# corruption). The version is assigned + the proven sha-image retagged to it
# ATOMICALLY in the Tag step below, so :vX exists iff its git tag exists.
tags: |
ghcr.io/hanzoai/cloud:${{ steps.ver.outputs.version_v }}
ghcr.io/hanzoai/cloud:${{ steps.ver.outputs.version }}
ghcr.io/hanzoai/cloud:${{ steps.ver.outputs.major_minor }}
ghcr.io/hanzoai/cloud:sha-${{ steps.ver.outputs.sha_short }}
ghcr.io/hanzoai/cloud:latest
labels: ${{ steps.meta.outputs.labels }}
# SAME cachebust as the smoke build → every layer is a cache hit from step 1
# and the pushed image is byte-identical to the one the smoke test proved.
build-args: |
CONSOLE_CACHEBUST=${{ steps.ver.outputs.cachebust }}
secrets: |
gh_token=${{ secrets.GH_PAT }}
GIT_AUTH_TOKEN=${{ secrets.GH_PAT }}
# THE RECEIPT: reached only because build + smoke + push all succeeded. If
# any of them failed the job already stopped and no tag was minted.
- name: Tag the proven image (git tag = receipt for a pushed, smoke-passed image)
# THE RECEIPT + ATOMIC VERSION ASSIGNMENT (race-safe). Reached only because
# build + smoke + push all succeeded, so a proven image exists under the unique
# sha- tag. Here we assign the next FREE v<X.Y.Z> and retag that proven image to
# it — atomically, with the git-tag push as the serialization point:
# * Recompute the next version FRESH (compute-step's value may have been claimed
# by a concurrent release in the build window).
# * If that version's git tag already exists, bump and retry.
# * Retag the proven sha-image → :vX (+ :X.Y.Z + :X.Y) via imagetools (metadata
# only, NO rebuild — byte-identical to the smoke-passed image).
# * Push the git tag; the FIRST pusher of vX wins, a loser deletes its local tag
# and recomputes. So concurrent releases each grab a distinct free number and
# the invariant "git tag vX ⇔ image :vX pushed+smoke-passed" holds under race.
- name: Tag the proven image (atomic free-version assignment — race-safe)
id: tag
env:
GH_PAT: ${{ secrets.GH_PAT }}
run: |
set -euo pipefail
V="${{ steps.ver.outputs.version_v }}"
git config user.name "hanzo-dev"
git config user.email "dev@hanzo.ai"
git tag -a "$V" -m "release $V — image ghcr.io/hanzoai/cloud:$V pushed and smoke-passed (${GITHUB_SHA})"
git push "https://x-access-token:${GH_PAT}@github.com/${GITHUB_REPOSITORY}.git" "$V"
echo "Tagged $V → ghcr.io/hanzoai/cloud:$V"
SHA_IMG="ghcr.io/hanzoai/cloud:sha-${{ steps.ver.outputs.sha_short }}"
PUSH_URL="https://x-access-token:${GH_PAT}@github.com/${GITHUB_REPOSITORY}.git"
for attempt in $(seq 1 8); do
git fetch --tags --force --quiet
git_max="$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' \
| sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1 || true)"
# Newest page only — NOT --paginate. Container versions are created
# newest-first and version tags are monotonic, so the highest version
# is always among the most-recent versions; paginating the WHOLE
# registry history is what livelocked this step as tags accumulated.
cont_max=""
if command -v gh >/dev/null 2>&1; then
cont_max="$(GH_TOKEN="$GH_PAT" gh api \
'/orgs/hanzoai/packages/container/cloud/versions?per_page=100' \
--jq '.[].metadata.container.tags[]?' 2>/dev/null \
| sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1 || true)"
fi
max="$(printf '%s\n%s\n%s\n' "1.786.0" "$git_max" "$cont_max" \
| grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)"
major="${max%%.*}"; rest="${max#*.}"; minor="${rest%%.*}"; patch="${rest##*.}"
VER="${major}.${minor}.$((patch + 1))"; V="v${VER}"
if git rev-parse -q --verify "refs/tags/$V" >/dev/null; then
echo " $V already tagged — recomputing (attempt $attempt)"; sleep 3; continue
fi
docker buildx imagetools create \
-t "ghcr.io/hanzoai/cloud:${V}" \
-t "ghcr.io/hanzoai/cloud:${VER}" \
-t "ghcr.io/hanzoai/cloud:${major}.${minor}" \
"$SHA_IMG"
# Dual-host: mirror the release tags to OUR fleet registry (server-
# side copy) so the cluster never depends on GHCR to deploy. crane,
# not buildx imagetools: the IAM token realm doesn't answer buildx's
# multi-scope token request (spec gap, tracked), crane's single-scope
# flow works. Best-effort — a mirror hiccup never blocks the receipt.
if [ "${MIRROR_OK:-}" = "1" ]; then
command -v crane >/dev/null 2>&1 || {
curl -fsSL https://github.com/google/go-containerregistry/releases/download/v0.20.2/go-containerregistry_Linux_x86_64.tar.gz \
| tar -xz -C "$HOME/.local/bin" crane 2>/dev/null || {
mkdir -p "$HOME/.local/bin"
curl -fsSL https://github.com/google/go-containerregistry/releases/download/v0.20.2/go-containerregistry_Linux_x86_64.tar.gz \
| tar -xz -C "$HOME/.local/bin" crane
}
export PATH="$HOME/.local/bin:$PATH"
}
for MT in "${V}" "${VER}" "${major}.${minor}"; do
crane copy "$SHA_IMG" "registry.hanzo.ai/hanzoai/cloud:${MT}" \
|| echo "::warning::mirror registry.hanzo.ai/hanzoai/cloud:${MT} failed"
done
fi
git tag -a "$V" -m "release $V — image ghcr.io/hanzoai/cloud:$V (retagged from sha-${{ steps.ver.outputs.sha_short }}, smoke-passed ${GITHUB_SHA})"
if git push "$PUSH_URL" "$V" 2>/dev/null; then
echo "Tagged $V → ghcr.io/hanzoai/cloud:$V"
echo "version=${VER}" >> "$GITHUB_OUTPUT"
echo "version_v=${V}" >> "$GITHUB_OUTPUT"
exit 0
fi
echo " push of $V lost the race — recomputing (attempt $attempt)"
git tag -d "$V" >/dev/null 2>&1 || true
sleep 3
done
echo "::error::could not acquire a free version tag after 8 attempts"
exit 1
# Notify universe so the GitOps pipeline rolls the new image to prod — same
# image-update contract every service uses (gateway, iam, …). Runs ONLY after
# build-amd64 succeeds, i.e. only for a version whose image is proven pushed and
# tagged. A failed release never reaches here, so universe is never asked to
# deploy a phantom tag.
notify-universe:
needs: build-amd64
runs-on: [hanzo-build-linux-amd64]
steps:
- name: Repository dispatch (image-update)
uses: peter-evans/repository-dispatch@v3
with:
token: ${{ secrets.UNIVERSE_DISPATCH_TOKEN }}
repository: hanzoai/universe
event-type: image-update
client-payload: |
{
"service": "cloud",
"image": "ghcr.io/hanzoai/cloud:${{ needs.build-amd64.outputs.version_v }}",
"sha": "${{ github.sha }}",
"env": "all"
}
# Deploy = a declared-tag bump in hanzoai/universe crs/cloud.yaml — Hanzo CD
# (the ArgoCD instance in ns hanzo-cd) syncs universe→cluster and the operator
# reconciles the CR. The old notify-universe repository_dispatch hub is retired
# (its flagged-sender dispatches were silently suppressed anyway); the native
# release path (release.go rolloutRelease) and deliberate promote commits own
# the bump.
+1
View File
@@ -34,3 +34,4 @@ Thumbs.db
.shots/
.claude/
native/flags/target
+208
View File
@@ -0,0 +1,208 @@
# Unified IAM Auth + Tenant Billing Contract
The ONE way every Hanzo product surface authenticates a user and bills their
usage. hanzo.chat, hanzo.app, studio.hanzo.ai, and console.hanzo.ai all
implement THIS contract against `hanzoai/cloud` (api.hanzo.ai). There is no
per-app billing, no shared API key, and no second way to do any of it.
## The chain, end to end
```
Browser (a surface)
│ 1. OIDC Authorization Code + PKCE, PUBLIC client (no client secret)
IAM (hanzo.id / lux.id / zoolabs.id / pars.id …)
│ 2. issues user tokens. owner claim = the user's org (the tenant).
Surface backend / SPA
│ 3. holds the user's IAM token server-side (session / httpOnly cookie).
│ UI's actively-selected (org, project) = the tenant context.
│ 4. EVERY call to cloud forwards THAT user's IAM bearer, unchanged:
│ Authorization: Bearer <user IAM token>
│ X-Project-Id: <active project> (optional; org comes from token)
cloud (api.hanzo.ai) — SanitizeIdentity → BillingGate
│ 5. validates the JWT (JWKS sig + issuer-set + audience + exp).
│ 6. derives (org, project): org is PINNED from the verified `owner`
│ claim (client-supplied X-Org-Id is stripped); project is the
│ claim-bound X-Project-Id (else soft-scoped).
│ 7. meters against the org's shared plan allowance; overflow →
│ pay-as-you-go on the org's linked billing account.
commerce (billing/pricing) — ONE ledger, keyed on (org, project)
```
One identity (the user's IAM token), one tenant key (org from the token's
`owner`, project from the active selection), one ledger. Every surface is a thin
client of this; none of them holds a shared key or bills anything itself.
## 1. Login — OIDC Authorization Code + PKCE, PUBLIC client
- **Public client, no client secret.** The token endpoint auth method is `none`;
security comes from PKCE (`code_challenge_method=S256`) + the signed `state`,
not a shared secret baked into a browser-delivered app. A public client cannot
leak a secret it does not have.
- Strategy registration MUST NOT be conditioned on a client secret. (The chat
login outage was exactly this: `configureOpenId` was gated on
`OPENID_CLIENT_SECRET`, so a secretless public client never registered the
`openid` passport strategy → "OpenID strategy not registered".)
- The `owner` claim is the tenant org. `sub` is the user. A surface reads the org
from `owner` (fallback `organization`), never from a client-set field.
- Reference implementation: `studio/middleware/iam_auth_middleware.py`
(`_authorize_redirect` builds the PKCE authorize URL; `handle_callback` adds a
`client_secret` to the token exchange ONLY if one is configured — public by
default).
## 2. Tenant context — active (org, project)
- A user belongs to one or more orgs; the token's `owner` is the home org, and
IAM may carry the full set (`organizations`/`orgs`/`groups`).
- The UI's actively-selected org + project is the tenant context for the session.
Studio carries the active org in the `studio_active_org` cookie and validates
it against the token's org set (`middleware/session.py: resolve_org`) — a user
can only ever select an org their token authorizes.
- cloud pins the billing org from the VERIFIED `owner` claim, so even a forged
active-org header cannot move spend to another tenant. The active project is
forwarded as `X-Project-Id` and is honored as a hard scope only when it is
claim-bound; otherwise it degrades to a soft scope (cannot hard-stop, cannot be
evaded). See `middleware_billing.go: identityFromCtx`.
## 3. Forwarding to cloud — the user's token, never a shared key
- EVERY request to cloud carries `Authorization: Bearer <the signed-in user's IAM
token>`. The token is held server-side (session / httpOnly cookie) and is never
exposed to the browser JS.
- The forwarded token MUST be principal-bound to the authenticated user (`sub`
equals the session principal) and unexpired. Fail secure: if no such token is
available, DENY (401 / "sign in") — never fall back to an ambient or service
credential, which would run as the wrong principal or drain a shared org.
- NO shared keys. NO per-app keys. NO per-user minted `hk-` keys for chat. The
IAM token IS the credential and the billing identity.
- Reference implementations:
- `chat/api/server/routes/agents/cloud.js` +
`chat/packages/api/src/endpoints/custom/tenantBearer.ts` — the ONE resolver
(`resolveTenantBearer`) both the agents path and the chat-completion path use.
- The chat-completion endpoints declare `apiKey: "{{LIBRECHAT_OPENID_TOKEN}}"`;
the custom-endpoint initializer substitutes the resolved session bearer at
request time (`chat/packages/api/src/endpoints/custom/initialize.ts`).
## 4. Billing — ONE path keyed on (org, project)
cloud is the single meter and gate. `SanitizeIdentity` (mirrored in-binary by
`auth_identity.go`) validates the token and exposes `c.Org()` / `c.User()` /
`ValidatedProject(c)`. `BillingGate` (`middleware_billing.go`) then:
- **Billing key = org.** Prepaid balance is per-org: one org credit covers the
whole org. `identityFromCtx` sets `User = org` (bare `sub` only when org is
absent). Keying per-user would 402 a fully funded org.
- **Scope axes = (project, service).** `project` is the caller's claim-bound
`X-Project-Id`; `service` is SERVER-derived from the route (`/v1/ai/*` → `ai`),
never a client field, so a caller cannot spoof another service's cap.
- **Shared plan, then PAYG.** `AuthorizeVerdict` checks the org's shared plan
allowance and per-scope spend caps in one round trip; overflow bills
pay-as-you-go against the org's linked billing account. Outcomes map to a frozen
HTTP contract:
- `200` allowed (with `X-Spend-Warn: <pct>` at a soft cap threshold),
- `402 insufficient_balance` — add credits at console.hanzo.ai,
- `402 spend_cap_exceeded` — raise the scope cap at console.hanzo.ai/limits,
- `503 balance_unavailable` — commerce unreachable, fail-closed.
- **Single charge.** `/v1/ai/*`, `/v1/agents/*`, and the other self-metering
subsystems record their own per-org usage; the edge gate returns price 0 for
them so nothing is billed twice (`DefaultPrice` / `selfMeteredPrefixes`).
## 4a. Per-product metering + the product/agent cost axes
Two metering seams share the ONE commerce ledger (`Deps.Metering`):
- **`BillingGate`** (`middleware_billing.go`) — the request EDGE, priced by PATH
(`DefaultPrice`). `/v1/ai/*` self-meters token spend upstream (gateway/ai), so it
is price-0 here to avoid double-billing.
**Auto-routing binds to the resolved model.** ai serves a virtual `auto`
(alias `zen-router`) model that it resolves to a concrete model id *before*
pricing/billing, then meters its own token cost keyed on the SERVED model and
reports it via the `X-Routed-Model` response header (echoed in the body
`model`). Because the edge prices `/v1/ai/*` by PATH (0), never by the request
model, `auto` bills as whatever it resolved to — the ai per-token meter is the
single source of the charge. The edge passes `X-Routed-Model` through untouched,
so the model reported to the client equals the model billed. Proven end-to-end:
`auto_routing_billing_test.go` (`TestAutoRoutingBillsAsResolvedModel`,
`TestDefaultPriceAiPathModelAgnostic`).
- **`ResourceMeter`** (`resource_billing.go`) — IN-HANDLER, priced per-org after the
caller's org is resolved. Every non-LLM product uses it: `Gate` (fail-closed
pre-auth, `available >= fee`, default fee $1.00 / `DefaultResourceFeeCents`) then
`Meter`/`MeterUsage` (debit-on-success, `provider = <product>`). Balance floor is
enforced BY DEFAULT — a zero/negative-balance priced call → **402** (proven:
`clients/{functions,s3,agents,ml,provisioning}/billing_test.go` `*RefusesUnfundedOrg`).
Metering+gating coverage (each meters its OWN org, debits on success):
| Product | provider label | fee knob | code |
|---|---|---|---|
| functions | `functions` | `CLOUD_FUNCTIONS_FEE_CENTS` | `clients/functions/invoke.go` |
| s3 | `s3` | `S3_*` | `clients/s3/s3.go` |
| agents | `agent` | `CLOUD_AGENT_FEE_CENTS` | `clients/agents/agents.go` |
| compute / GPU | `compute` | provision knobs | `clients/ml/ml.go`, `clients/visor/*` |
| provisioning (sql/kv/vector/docdb) | `provisioning` | `CLOUD_PROVISION_FEE_CENTS[_KIND]` | `clients/provisioning/*` |
| automations | `automations` | `CLOUD_AUTOMATIONS_FEE_CENTS` | `clients/automations/automations.go` |
| tracker | `tracker` | fee knob | `clients/tracker/tracker.go` |
| security | `security.scan` | — | `clients/security/security.go` |
**Product/agent read axes.** The console's per-product Metrics dashboard groups on
`metadata.product` (and `metadata.agent`). Commerce's `RecordUsage` persists the
metering SURFACE (`provider`) and billed UNIT (`model`) but has **no `product`
field** (its `usageRequest` drops `project`/`service`/`product`/`agent`). So the
customer read handler `clients/billing/usage.go` is the ONE read-side adapter:
`usage()` fetches the org-scoped ledger and, on 200, injects a canonical
`metadata.product` onto every row (`productOf`: `agent→agents`,
`provisioning→<kind>`, token-metered→`inference`, else `provider`) so the
breakdowns POPULATE from the SAME charged ledger. It also honors, server-side (was
silently ignored):
- `GET /v1/billing/usage?product=<id>` — filter to one product,
- `GET /v1/billing/usage?groupBy=product` — per-product rollup
`{product,requests,amountCents}`.
A row that already carries `metadata.product`/`agent` wins, so this degrades to a
no-op when the meter/commerce persist them natively (forward-compatible).
**Remaining checklist** (each is the same seam):
1. **Native `product`/`agent` fields** — add `Product`/`Agent` to
`commerce/metering.Usage` + `commerce` `usageRequest`/metadata, have each
`ResourceMeter` caller pass its product id, and drop the read-side `productOf`
derivation (decomplect: the meter KNOWS its product; record it, don't re-derive).
Cross-repo (commerce) — additive/backward-compatible.
2. **Agent-NAME axis** — needs (1): the agent run debit records `provider=agent` +
`model=<llm>` but not the agent name, so `metadata.agent` stays honest-empty
until commerce persists an `agent` field the agents meter sets to `a.Name`.
3. **compute split** — `ml` (predict) and `visor` (GPU) both meter `provider=compute`;
read-side can't split `inference` vs `gpus`. Needs (1) so each sets its product id.
4. **exec / containers** (`clients/exec`, Code Interpreter) — authed by a shared
service key (X-API-Key), NO per-org identity, so it can't meter per-org; its
compute is billed upstream at the chat/agent layer that invokes it.
5. **playground** — routes to `/v1/ai/*`, already metered as AI inference.
## 5. Secrets
- Per-tenant, KMS-managed only (`kms.hanzo.ai`, KMSSecret CRDs). No shared
service key stands in for a user. The only service tokens that exist are
narrow, per-tenant, and never used to impersonate a user for LLM spend.
- A surface's own OIDC registration is a PUBLIC client — there is no client
secret to store.
## Surface conformance (as of this contract)
| Surface | Login (PKCE public) | Forwards user token | Org from `owner` | Billed via cloud (org,project) |
|---|---|---|---|---|
| **studio.hanzo.ai** | ✅ reference | ✅ (validates locally) | ✅ | ⚠️ renders run on studio's own GPU workers and self-report to commerce keyed by org via a per-tenant commerce token — org-keyed, but not the forward-bearer-to-gateway path (studio does not call the cloud LLM gateway for its core renders) |
| **console.hanzo.ai** | ✅ | ✅ same-origin `/v1` through the gateway | ✅ | ✅ (it IS the canonical consumer) |
| **hanzo.chat** | ✅ (this change) | ✅ (this change: `resolveTenantBearer`) | ✅ | ✅ (this change: forwards bearer to `/v1/ai/*`) |
| **hanzo.app** | ❌ confidential client (`IAM_CLIENT_SECRET`, userinfo/introspect) | ✅ to its own backend; org from token `owner` | ✅ | ❌ builder AI runs on OpenRouter with an apiKey (`lib/llm/generation-api.ts`), NOT the cloud gateway — off the unified meter |
hanzo.app is the remaining gap: it needs the same treatment chat just got — switch
its IAM registration to a PKCE public client, and route its builder AI generation
through api.hanzo.ai forwarding the user's IAM bearer so usage meters against the
org plan instead of a shared OpenRouter key.
</content>
</invoke>
+155 -90
View File
@@ -2,112 +2,177 @@
#
# This image is a SINGLE artifact that serves BOTH the /v1 API AND the console
# UI from one process: the console is compiled into the Go binary via
# //go:embed (see webui.go). The pipeline is:
# //go:embed (see webui.go). The final `/cloud` binary already carries the UI —
# no separate console Service, no second origin; the embedded console calls /v1
# on its own host.
#
# 1. console stage → build the hanzoai/console2 static bundle
# 2. (copied) → into webui/dist/ of the Go build context
# 3. build stage → `go build` bakes webui/dist into the binary (go:embed)
#
# so the final `/cloud` binary already carries the UI. No separate console
# Service, no second origin — the embedded console calls /v1 on its own host.
#
# ── console UI stage ─────────────────────────────────────────────────────────
# Builds the console2 SPA and emits a STATIC bundle at /out. console2 is fetched
# at a pinned ref (CONSOLE2_REF) using the same gh_token BuildKit secret the Go
# build uses for private modules.
#
# console2 exposes `npm run build:embed` (scripts/build-embed.mjs): it prunes the
# Next server route handlers (BFF proxies — they collapse to the cloud /v1/* the
# SPA calls same-origin), wraps the client catch-all pages for output:'export',
# and neutralizes the root layout's request-time headers() read (the per-host
# <title>, resolved client-side in the embed) so the STATIC export prerenders
# clean — emitting out/. This stage runs it and copies out/ into /out, which the
# Go build drops into webui/dist so //go:embed bakes the FULL @hanzo/gui console
# into the ONE binary. The stage still degrades to the committed fallback shell,
# non-fatally, if build:embed is ever absent or fails (a console2 export
# regression must never take down the cloud backend image) — but the intended,
# working path is the real bundle.
FROM public.ecr.aws/docker/library/node:24-alpine AS console
ARG CONSOLE2_REPO=https://github.com/hanzoai/console2.git
ARG CONSOLE2_REF=main
RUN apk add --no-cache git
WORKDIR /console
# The static export prerenders every page (webpack compile + export prerender);
# give the heap headroom so a large @hanzo/gui build never OOMs into the stub.
ENV NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=8192
RUN --mount=type=secret,id=gh_token \
if [ -s /run/secrets/gh_token ]; then \
git config --global url."https://x-access-token:$(cat /run/secrets/gh_token)@github.com/".insteadOf "https://github.com/"; \
fi && \
git clone --depth 1 --branch "${CONSOLE2_REF}" "${CONSOLE2_REPO}" . && \
npm install --no-audit --no-fund --fetch-retries=5 --fetch-retry-mintimeout=20000 --fetch-timeout=120000
# Always emit /out. When console2 exposes a static-embed target AND it builds, /out
# holds the real bundle; otherwise /out stays EMPTY so the Go build keeps the
# committed fallback shell. Never fail the image — a static target that is missing
# OR that fails to build is a degrade, not an error (the standalone console2
# Deployment is the primary console; this embed is a same-origin convenience). A
# console2 prerender/export crash (e.g. /signin Server-Components error) must NOT
# take down the cloud backend image.
RUN mkdir -p /out && \
if npm run 2>/dev/null | grep -q ' build:embed'; then \
echo ">> console2 build:embed → static bundle"; \
if npm run build:embed && [ -d out ]; then \
cp -r out/. /out/; \
echo ">> embedded console2 static bundle"; \
else \
echo ">> console2 build:embed FAILED — degrading to committed fallback shell (non-fatal)"; \
fi; \
else \
echo ">> console2 has no static-embed target yet; cloud embeds the fallback shell"; \
fi
# ── prebuilt decomplection artifacts (cloud compiles ONLY Go) ────────────────
# The console SPA, the agent-skills catalog, and the native flags staticlib are
# each built by THEIR OWN CI as a versioned immutable image and PULLED here,
# instead of rebuilding node + python + rust from scratch every cloud release.
# The heavy one (console: a cold `npm install` + full Next.js static export,
# force-cache-busted every build) used to dominate the ~20-min build; it is now
# a registry pull.
# console-embed (hanzoai/console Dockerfile.embed) → /dist → webui/dist (go:embed)
# agent-skills (hanzoai/openapi Dockerfile.skills) → /catalog → clients/agentskills/catalog (go:embed)
# cloud-flags (native/flags Dockerfile) → /libhanzo_flags.a → CGO link (clients/featureflags)
# Pinned to ghcr.io so BOTH buildx lanes (release.yml + platform arcbuild) pull
# it directly; the SAME tags are mirrored to registry.hanzo.ai (S3-backed) for
# GET-flow consumers (docker/kaniko/crane). Override any pin with
# --build-arg <NAME>_IMAGE=… — release.yml resolves CONSOLE_IMAGE to a fresh
# console-embed digest, exactly as CONSOLE_CACHEBUST re-fetched console before.
ARG CONSOLE_IMAGE=ghcr.io/hanzoai/console-embed:latest
ARG SKILLS_IMAGE=ghcr.io/hanzoai/agent-skills:latest
ARG FLAGS_IMAGE=ghcr.io/hanzoai/cloud-flags:latest
# ── Go build stage ───────────────────────────────────────────────────────────
# ECR Public mirror of the Docker library image — Docker Hub's unauthenticated
# pull rate-limit (429 toomanyrequests) fails the build on shared CI runners.
FROM public.ecr.aws/docker/library/golang:1.26-alpine AS build
RUN apk add --no-cache ca-certificates tzdata git
# ── toolchain base images: the golang + alpine FROMs below pull from our own
# GHCR mirror (ghcr.io/hanzoai/mirror/*), pinned by digest. WHY: public.ecr.aws
# rate-limits anonymous pulls (HTTP 429) on shared CI runners and a 429 on ANY
# base pull aborts the release. The mirror packages are 1:1 amd64 copies of the
# upstream public images, digest-pinned for immutability; release.yml logs the
# build into ghcr.io (GH_PAT) before building so they resolve. REFRESH on a
# toolchain bump: crane/regctl copy the new upstream into
# ghcr.io/hanzoai/mirror/<name>:<tag> and repoint the digest below. Canonical
# long-term home is registry.hanzo.ai/hanzoai/mirror/* — repoint once the runners
# carry its IAM pull credentials (follow-up).
# ── console SPA static export (prebuilt → /dist) ─────────────────────────────
FROM ${CONSOLE_IMAGE} AS console
# ── agent-skills catalog (prebuilt → /catalog) ──────────────────────────────
FROM ${SKILLS_IMAGE} AS skills
# ── native flags evaluator staticlib (prebuilt → /libhanzo_flags.a) ──────────
FROM ${FLAGS_IMAGE} AS flagslib
FROM ghcr.io/hanzoai/mirror/golang:1.26-alpine3.22@sha256:47d47cb5cc3c7dac409dcb6c3a98a6263571218046cd02d709527feef804a77c AS build
# CIPHER-FORMAT FREEZE (cek depends on this). The data-plane stores are
# SQLCipher pages in a fixed on-disk format (cipher_compatibility 4). An at-open
# compat pin is infeasible (mattn keys via URI before any pragma), so the format
# is frozen by pinning sqlcipher-dev to an EXACT version. A repo bump then fails
# the build LOUDLY (never a silent prod brick); on such a failure, bump the pin
# AND confirm cek's frozen-fixture test still opens (format unchanged)
# before shipping. A MAJOR bump (4.x → 5.x) changes the default format and would
# orphan existing encrypted stores — migrate/rewrap them first.
RUN apk add --no-cache ca-certificates tzdata git gcc musl-dev sqlcipher-dev=4.6.1-r0 pkgconfig binutils
RUN addgroup -g 65532 -S nonroot && adduser -u 65532 -S nonroot -G nonroot
# mattn/go-sqlite3's `libsqlite3` tag hard-codes `-lsqlite3`, but alpine's
# sqlcipher-dev ships ONLY libsqlcipher (no libsqlite3.so). Symlink so the link
# resolves -lsqlite3 to libsqlcipher — REAL encryption. Do NOT `apk add sqlite-dev`
# (a plaintext libsqlite3 would silently disable the codec; the gate below catches it).
RUN set -eux; \
SC="$(find /usr/lib /lib -name 'libsqlcipher.so*' 2>/dev/null | sort | head -1)"; \
test -n "$SC"; \
ln -sf "$SC" /usr/lib/libsqlite3.so; \
ln -sf "$SC" /usr/lib/libsqlite3.so.0
WORKDIR /src
# hanzoai/* and luxfi/* are PUBLIC and resolve via the IMMUTABLE public proxy +
# sumdb — go.sum pins those canonical hashes, so a force-re-pointed tag can never
# break the build. Routing them DIRECT (the old GOPRIVATE approach) re-fetches a
# re-tagged tree (e.g. luxfi/age@v1.5.0) whose hash differs from go.sum's proxy
# hash → "checksum mismatch / SECURITY ERROR". This matches the drop-GOPRIVATE
# fix already shipped in hanzoai/iam + luxfi/kms. Only zap-proto/* stays first-
# party-direct (kept in GOPRIVATE) — authenticated git via gh_token. GOPROXY
# still routes nested-path monorepo tags (e.g. tencentcloud-sdk-go) through the
# proxy. The committed go.sum is the single source of truth.
ENV GOPRIVATE=github.com/zap-proto/* \
GONOSUMDB=github.com/zap-proto/* \
GOSUMDB=off \
# zap-proto/* (all 55 repos) and luxfi/* (all 37 deps here) are PUBLIC and resolve
# via the IMMUTABLE public proxy + sumdb — go.sum pins those canonical hashes, so a
# force-re-pointed tag can never break the build. GOSUMDB stays ON (a money image
# must not blanket-disable the checksum database); github.com/hanzoai/* is the
# exempt namespace — ai, account, commerce, orm, xorm, beego, csqlite and ~30 more
# are PRIVATE repos, so they resolve direct+authenticated (git over gh_token) and
# skip a sumdb that cannot see them. GOPRIVATE named zap-proto until now, which is
# public and was never the reason anything was direct; the private namespace it
# stood for went unnamed and worked only on the GOPROXY `direct` fallback.
# -mod=readonly means the committed go.sum is the SOLE source of truth: any drift
# (a needed hash not present) FAILS the build instead of being silently
# re-recorded. CGO_CFLAGS/LDFLAGS enable the SQLCipher codec + URI keying.
ENV CGO_CFLAGS="-DSQLITE_HAS_CODEC -DSQLITE_USE_URI=1 -I/usr/include/sqlcipher" \
CGO_LDFLAGS="-lsqlcipher" \
GOPRIVATE=github.com/hanzoai/* \
GOPROXY=https://proxy.golang.org,direct \
GOFLAGS=-mod=mod
GOFLAGS=-mod=readonly
COPY go.mod go.sum ./
# With go.sum recorded against live tag content and our orgs routed direct, this
# verifies cleanly — no runtime go.sum regeneration. (The old `rm -f go.sum`
# self-heal masked a stale go.sum and silently re-recorded unverified hashes on
# ANY transient error; removed in favor of a correct, committed go.sum.)
RUN --mount=type=secret,id=gh_token \
if [ -s /run/secrets/gh_token ]; then \
git config --global url."https://x-access-token:$(cat /run/secrets/gh_token)@github.com/".insteadOf "https://github.com/"; \
# The cache mounts carry an EXPLICIT id so they can be busted. Without one,
# BuildKit keys the cache by target path alone, and a poisoned entry is immortal:
# a module resolved while its tag did not yet exist is remembered as "unknown
# revision" forever, so `go mod download` keeps failing on a tag that now exists
# and resolves fine from a clean cache. That is exactly what wedged the release
# on otel-collector v0.144.10. BUMP THE SUFFIX (-v4 -> -v5) to force a cold
# module cache the next time a phantom pin poisons it.
RUN --mount=type=secret,id=GIT_AUTH_TOKEN \
--mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
if [ -s /run/secrets/GIT_AUTH_TOKEN ]; then \
git config --global url."https://x-access-token:$(cat /run/secrets/GIT_AUTH_TOKEN)@github.com/".insteadOf "https://github.com/"; \
fi && \
go mod download
COPY . .
# Drop the console static bundle into the embed path BEFORE `go build`, so
# //go:embed all:webui/dist bakes it into the binary. /out from the console stage
# is either the real static build (then it overlays the committed fallback shell)
# or empty (then webui/dist keeps the shell that `COPY . .` already brought). The
# committed assets/.gitkeep keeps the embed's assets/ dir present either way.
COPY --from=console /out/ /src/webui/dist/
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /cloud ./cmd/cloud
# //go:embed all:webui/dist bakes it into the binary (same-origin console).
COPY --from=console /dist/ /src/webui/dist/
# Overlay the FULL agent-skills catalog before `go build` so //go:embed all:catalog
# bakes the complete set (all services × brands), not the committed `ai` fallback.
COPY --from=skills /catalog/ /src/clients/agentskills/catalog/
# The native flags staticlib at the exact ${SRCDIR}-relative path the cgo
# directive in clients/featureflags/engine.go links.
COPY --from=flagslib /libhanzo_flags.a /src/native/flags/target/release/libhanzo_flags.a
# RED gate — modernc double-registration guard: 0 modernc under CGO=1, else the
# "sqlite" driver is registered twice (mattn + modernc) → panic at init.
RUN --mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,id=cloud-gobuild-v4,target=/root/.cache/go-build,sharing=locked \
MODERNC="$(CGO_ENABLED=1 go list -tags "libsqlite3 sqlite_fts5" -deps ./cmd/cloud 2>/dev/null | grep -c 'modernc.org/sqlite' || true)"; \
[ "$MODERNC" = "0" ] || { echo "SQLITE-GATE FAIL: cmd/cloud links modernc.org/sqlite ($MODERNC pkgs) under CGO=1 — double-registers \"sqlite\" with hanzoai/sqlite(mattn) and panics at init."; exit 1; }
# RED gate — ENCRYPTION PROOF + the cek.go GOLDEN-VECTOR KAT, under the SAME CGO +
# libsqlcipher build this image ships. TestEncryptionProof asserts real
# ciphertext-at-rest (SQLITE_REQUIRE_CODEC=1 makes a plaintext link FAIL → NO
# image). TestUnwrapGoldenFixture asserts a FROZEN pre-luxfi-swap 61-byte DEK
# sidecar still decrypts under the shipped luxfi/crypto-AEAD code — existing
# encrypted stores stay readable, or NO image.
RUN --mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,id=cloud-gobuild-v4,target=/root/.cache/go-build,sharing=locked \
SQLITE_REQUIRE_CODEC=1 CGO_ENABLED=1 go test -count=1 -tags "libsqlite3 sqlite_fts5" \
-run 'TestEncryptionProof|TestUnwrapGoldenFixture|TestWrapUnwrapRoundTripPinsLayout' \
github.com/hanzoai/sqlite
# RED gate — cek FROZEN-FORMAT guard, run INSIDE the image under the pinned Alpine
# libsqlcipher: opens the committed encrypted fixture and reads its canary row. A
# sqlcipher-dev pin/base bump that changes the on-disk format fails the IMAGE build
# HERE (not only Go CI) → a silent prod brick of existing stores becomes a red build.
RUN --mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,id=cloud-gobuild-v4,target=/root/.cache/go-build,sharing=locked \
SQLITE_REQUIRE_CODEC=1 CGO_ENABLED=1 go test -count=1 -run TestFrozenFixtureOpens \
-tags "libsqlite3 sqlite_fts5" ./cek
RUN --mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,id=cloud-gobuild-v4,target=/root/.cache/go-build,sharing=locked \
CGO_ENABLED=1 go build -tags "libsqlite3 sqlite_fts5" -ldflags="-s -w" -o /cloud ./cmd/cloud
# The functional smoke prober (cmd/smoke) — a stdlib-only, static binary shipped
# alongside /cloud so the release gate can `docker exec` it against the freshly-built
# image (and any deployment can be smoked via `docker run --entrypoint /smoke ...`).
RUN --mount=type=cache,id=cloud-gomod-v4,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,id=cloud-gobuild-v4,target=/root/.cache/go-build,sharing=locked \
CGO_ENABLED=0 go build -ldflags="-s -w" -o /smoke ./cmd/smoke
# Prove the SHIPPED binary binds sqlite3_* to libsqlcipher, not a plaintext libsqlite3.
RUN readelf -d /cloud | grep -qE 'NEEDED.*(sqlcipher|sqlite3)' || { echo "FATAL: /cloud links no sqlite/sqlcipher .so"; exit 1; }; \
! ldd /cloud 2>/dev/null | grep -E 'libsqlite3' | grep -vq 'libsqlcipher' || { echo "FATAL: /cloud resolves a NON-sqlcipher libsqlite3 (plaintext risk)"; exit 1; }
# ── final image ──────────────────────────────────────────────────────────────
FROM scratch
# ── final image (alpine, NOT scratch — CGO needs libc + libsqlcipher) ─────────
FROM ghcr.io/hanzoai/mirror/alpine:3.22@sha256:7c8cb692ae09657cbc4a3f3cbd0e8d5a2690ba38386aaaf252dbb060bf5eb2e6
ARG REVISION=unknown
LABEL org.opencontainers.image.revision="${REVISION}" \
org.opencontainers.image.source="https://github.com/hanzoai/cloud"
# Runtime needs libsqlcipher (the codec the binary links). It must NOT also carry
# a plaintext libsqlite3 — the binary's -lsqlite3 DT_NEEDED would then bind to
# plaintext sqlite and silently no-op PRAGMA key. sqlcipher-libs ships
# libsqlcipher.so.0; alias libsqlite3.so.0 to it so sqlite3_* binds there.
#
# `git` backs the git object plane (clients/git): the heavy paths — clone/fetch
# serve, push receive, mirror-in — shell out to the streaming git CLI
# (upload-pack / receive-pack --stateless-rpc / fetch) so multi-GB packs stream
# to and from disk with bounded memory instead of buffering whole packs in RAM.
# The `git` apk package carries upload-pack/receive-pack/http-backend/git-remote-https.
# libgcc: the hanzo-flags Rust staticlib (clients/featureflags FFI) references the
# _Unwind_* unwinder symbols; musl needs libgcc_s at load time or the binary fails
# relocation ("Error relocating /cloud: _Unwind_GetIP: symbol not found").
RUN apk add --no-cache ca-certificates tzdata sqlcipher-libs git libgcc \
&& SC="$(find /usr/lib /lib -name 'libsqlcipher.so*' 2>/dev/null | sort | head -1)" \
&& test -n "$SC" \
&& ln -sf "$SC" /usr/lib/libsqlite3.so.0
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=build /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=build /etc/passwd /etc/passwd
COPY --from=build /etc/group /etc/group
COPY --from=build /cloud /cloud
COPY --from=build /smoke /smoke
EXPOSE 8080 9090 9653
USER 65532:65532
ENTRYPOINT ["/cloud"]
+186
View File
@@ -0,0 +1,186 @@
# LLM.md — hanzoai/cloud
Guidance for AI agents working in this repo. `hanzoai/cloud` (HIP-0106) is ONE Go
binary + CLI that mounts every Hanzo subsystem into a single process; the same
artifact serves `api.hanzo.ai`, `api.lux.cloud`, `api.zoo.cloud`, `api.osage.cloud`
and every white-label reseller. Brand, enabled subsystems, and org scope are
deployment configuration.
## Framework doctrine
One way to do everything. Composable, orthogonal, DRY. A new subsystem is a
package under `clients/<name>` that obeys these seams — nothing more.
- **Subsystem shape.** A subsystem exposes `func Mount(app *zip.App, deps cloud.Deps) error`
and is listed in `apps.Wire()` as a `cloud.MountSpec{Name, Mount: cloud.Typed(Mount)}`
(plus `Shutdown`/`OwnsHealth` where it owns them). `Mount` wires that subsystem's
`/v1/<name>/*` routes onto the shared `*zip.App`; `cloud.Deps` carries the
process-wide handles (Logger, DataDir, the subsystem `Client` seams). No
subsystem reaches into another's internals. There is no init()-registry and no
`cloud.Register` — subsystems do NOT self-register.
- **Client seams.** Cross-subsystem calls go through a narrow in-process interface
published in `types` and aliased at the provider, e.g. `commerce.Client =
types.CommerceClient` (`GetOrgConfig` + `CheckEntitlement`). Consumers depend on
the interface, never the implementation; the seam rides zap-proto/zip. Keep each
interface minimal — add a method only when a consumer needs it.
- **Composition root.** `apps/apps.go:Wire()` returns `[]cloud.MountSpec` — every
linked subsystem, in mount order, as ONE explicit slice read top-to-bottom.
Slice position IS the order: there is no `Order` field and `MountAll`
(build.go) does NOT sort; it iterates as-given and mounts each ENABLED spec
(`cfg.Enabled`). To add a subsystem you add one line to `Wire()`.
`apps/wire_test.go` freezes the sequence, so a reorder/drop/add fails there.
- **Route precedence.** The router is zap-proto/fiber (zip v1.8.3). Most-specific
route wins regardless of mount order, so subsystems may mount in any order and
still compose deterministically. But precedence is NOT a conflict guard: two
registrations of a byte-identical pattern do NOT panic — fiber MERGES them into
ONE route with both handlers chained, resolving by first-registration. That is
invisible to a `GetRoutes()` entry count (see the bots note below), and it is
NOT distinguishable from a legitimate middleware chain: `app.Post(path, mw1,
mw2, mw3, handler)` is one registration with four handlers (apps/commerce.go:151),
and the whole `/v1/store/*` surface is that shape. A high handler count is
therefore evidence of nothing on its own; only a subsystem that never chains
middleware (bots/visor/runtime) can read `len(Handlers) > 1` as a collision.
- **Per-org data.** The ONE way any subsystem opens a per-org SQLite file is
`cloud.OrgDB(dataDir, org, project, sub)` — or the cached `cloud.OrgStore[T]`
(`NewOrgStore` + `For(org, project)`). Path convention:
`{DataDir}/orgs/{org}/{sub}.db`, or `{DataDir}/orgs/{org}/projects/{project}/{sub}.db`
when project-scoped. Isolation is PHYSICAL: a distinct `(org[, project])` is a
distinct file. `org`/`project` MUST be the VALIDATED principal values
(`principal.Org(c)`, `principal.Project(c)`) — never a raw body/header — and are
folded through `SanitizeOrg`, the ONE injective org slugger. hanzoai/sqlite is
the SOLE driver (blank-imported once, in orgdb.go); subsystems never import a
SQLite driver themselves. The caller owns its schema/migration and Close.
## The route table has three projections, and the router is the source
`serve.go` composes ONE route table and projects it three ways, all after
`MountAll` so each sees a complete table: `/zap` REPLAYS the /v1 handlers
(zapface), the console RENDERS them, and `GET /v1/openapi.json` DESCRIBES them
(`openapi.Mount`). None holds a second copy of anything; none can drift.
- **The spec IS the router.** `openapi.Live(app)` reads
`app.Fiber().GetRoutes(true)` — fiber's own filter drops `Use()` middleware —
and every other function in `openapi/` is a pure function of that `[]Route`.
There is NO checked-in spec file to hand-maintain and no second registry. The
drift guard is `cmd/cloud/openapi_test.go`: a BIJECTION over the fully-mounted
`apps.Wire()` (983 operations / 692 paths / 109 products) — every live route
appears as an operation, every operation is backed by a live route. It is the
only test whose failure means the document lies.
- **Reading the LIVE router is the only total source.** `POST /v1/kms/auth/login`
is registered as `Group("/v1/kms/auth").Post("/login")` — no grep can find that
path; only the assembled router knows it. And the route set is a function of
deployment config (`cfg.Enabled`, plus internal gates like kms's `if kc != nil`),
so **the spec VARIES PER DEPLOYMENT** — correctly: a deployment that does not
mount admin does not advertise it. That is why the document is generated
per-process at request time, not built once in CI.
- **The product axis is mechanical.** The first path segment after `/v1/` IS the
product (`openapi.Product`), tagged onto each operation so a CLI can build
`hanzo <product> <resource> <verb>` with no judgment. It is deliberately NOT the
subsystem name: `clients/billing` also serves `/v1/finance/*`.
- **What the router CANNOT tell you — do not try to fix this in the generator.**
Method, path, path params, and product are derivable; request/response schemas,
query/header params, status codes, and auth are NOT. The router holds a
`func(*zip.Ctx) error`; the request type is a LOCAL inside the handler
(`var req secretPutRequest; json.Unmarshal(ctx.Body(), &req)`), and Go cannot
reflect from a func value into its body. `cloud.Handle[S]` does not help — `S`
is the SERVICE (service.go:90), not the payload; `cloud.Typed` is an
`any→*zip.App` mount adapter. The ONE path to schemas is zip's typed ops
(`zip.Get[In,Out]`), which carry the In/Out types and also yield an MCP tool
from the same registry (zip/openapi.go, zip/mcp.go — today `len(a.ops) == 0`,
so zip's own generator emits nothing here). `GetRoutes()` is a superset of
`app.ops`, so migrating a handler to a typed op adds schema without changing
this pipeline.
- **Catch-alls are opaque, by construction.** `app.Post("/v1/billing/*")` proxies
to another service, so `POST /v1/billing/deposit` is NOT a route in this process
and cannot appear. Measured on the live table: 3 products are wholly opaque
(`bot`, `licensing`, `sentry` — the catch-all IS the product) and 12 more mix
concrete ops with a catch-all hiding an unknown remainder.
## Cross-subsystem seams that are values, not places
- **The per-principal MCP plane is callable in-process.** `clients/automations`
decomplects tool dispatch from its front doors: `dispatchTool` is the ONE core
(resolve `<connector>_<action>` → run with a Token bound to the VALIDATED org),
and TWO doors share it — the HTTP JSON-RPC handler (`POST /v1/automations/mcp`)
and the exported `automations.InvokeTool(ctx, org, tool, args)`. A sibling
subsystem that must ACT AS a caller (the Business AI guide's "do it for me")
calls `InvokeTool` with `principal.Org(c)` — same 403 gate, per-org concurrency
bound, one metered unit, one audit record as the HTTP door — so it can never
exceed the caller's authority. Use this seam; never re-implement tool dispatch.
- **"Bot" is three values; each has one home and one namespace.** Do not merge
them and do not let them share a route prefix — they did once, and the router
resolves byte-identical patterns by first-registration with no panic (it MERGES
the handlers, so counting `GetRoutes()` entries cannot see it), and visor's
machine list silently answered the console's run list.
(1) A bot RUN — a task the runtime executes on a surface — is `clients/bots` at
`/v1/bots`. (2) A bot MACHINE — visor-provisioned compute of kind=bot plus its
agent binding — is `clients/visor` at `/v1/compute/bots`; what it rents you is
compute, so it nests in visor's domain. (3) The runtime SERVICE — the TS bot
(channels/skills), never reimplemented in Go — is reached through
`clients/runtime`, which is a TRANSPORT, not a domain: base address, identity,
framing, cleartext policy, and the `/v1/bot/*` ops face. It is named for what it
does, not for the host it dials, and it must never import `bots`/`coding` — each
of those owns its own wire stub (`bots/wire.go`, `coding/task.go`) and speaks
through the seam. That isolation is what makes the HIP-0106/HIP-0120 ZAP swap a
seam swap instead of a rewrite.
- **Cloud owns policy; the runtime owns the run. Do not copy state you do not
own.** `clients/bots` holds NO store. The sandbox lives in the bot runtime,
keyed in the runtime's own tenant store, which is the only thing that knows
whether a run is alive — so list and stop PROXY it, gated by cloud's
principal/org. A cloud-side registry was tried and was wrong: it minted an id
the runtime had never heard of, so it listed runs that did not exist and
"stopped" runs that were never started. Isolation holds because the org is the
validated one cloud sends, never a client's, and the runtime keys every run
under `tenants/{org}/`.
- **Absence is only meaningful from a callee that could have said otherwise.**
`runtime.ErrNotFound` (the operation ANSWERED "no such target") is separate from
`runtime.ErrNotServed` (the operation does not exist). Conflating them makes a
stop that cannot fail: a runtime without the route reports absent for EVERY run,
so "already gone" becomes permanently true. A bare 404 is 502, never success.
- **The Business AI Guide (`clients/guide`, `/v1/guide/*`)** is the on-site launch
checklist: a pure engine (`curriculum.go` — parse/validate/next-step/dependency
gating over plain data) + per-org progress (`cloud.OrgStore[*Store]`) + an
injectable auto-detect registry (`detect.go``acted` reads the agent action
ledger, `analytics` probes the shared warehouse) + the agent (`agent.go` — drafts
with `deps.AI`, executes the step's bound tool via `automations.InvokeTool`). The
curriculum is a machine-readable contract (embedded `default.yaml`; org-custom via
PUT replaces it) so `hanzoai/marketing` can author the full `checklist.yaml`
against the same `Step`/`Curriculum` shape.
## Identity vocabulary is IAM-native
Identity is expressed ONLY in IAM-native nouns: **org, user, project, billing
account**. The word **"tenant" is banned** in cloud identifiers, strings,
comments, and filenames. Resolve org/project scope through `clients/principal`
(`principal.Org(c)`, `principal.Project(c)`) and user identity through `c.User()`
— all gateway-minted, JWT-validated values (X-Org-Id / X-Project-Id / X-User-Id,
HIP-0026); never read a raw request header for scope.
- **The one gated exception.** `clients/platform` derives customer-app Kubernetes
namespaces, registry image refs, and quota/limit objects from a live `tenant-<org>`
string prefix. Renaming that prefix orphans deployed namespaces + built images,
so the literal `"tenant-"` string (and its directly-adjacent comment) is retained
behind a `// NAMING(gated)` note in `clients/platform/k8s.go`. The surrounding
identity vocabulary is org-native regardless; only the on-cluster string waits on
an infrastructure migration.
## Hanzo Company (`clients/company`, `/v1/company`)
The Stripe-Atlas-class incorporation + fundraising product: ONE formation state
machine per org. `machine.go` is the PURE core — a `transitions` table with a guard
per edge, `Advance(f, to)` the only mutator — so transitions, the payment gate, and
the skip path are unit-testable with no I/O. The HTTP surface is decomplected: ACTION
endpoints populate data (structure/founders/kyc/payment/documents/esign/genesis/
import), and ONE `POST /v1/company/advance {to}` runs the guarded transition.
Every external dependency is a narrow provider interface (`providers.go`) so the
machine composes them identically in prod and tests: billing → the shared
`ResourceMeter` ($999 one-time fee); documents → `dataroom.Ingest` (new in-proc
facade); cap table → `captable.*` (new in-proc facades: SetIncorporation /
AddStakeholders / EnsureShareClass / IssueShares / RecordRound); equity genesis →
a KMS-signed Hanzo-L1 anchor mirroring `clients/treasury` (honest pending when
unwired); KYC + state filing → honest stubs (no fabricated verification/filing).
Import path (already-incorporated orgs): Google Drive → data room, a Google Sheet →
captable, via the `google` OAuth provider now completed in `clients/integrations`
(token custodied in KMS; the automations `google` connector shares the same token).
Runbook: `docs/company-dogfood.md`.
+26 -10
View File
@@ -7,8 +7,10 @@ PKG ?= ./cmd/cloud
DOCKER_IMAGE ?= ghcr.io/hanzoai/cloud
DOCKER_TAG ?= dev
LDFLAGS ?= -s -w
# Path to a hanzoai/console2 checkout used to build the embedded console bundle.
CONSOLE2_DIR ?= ../console2
# Path to a hanzoai/console checkout used to build the embedded console bundle.
CONSOLE_DIR ?= ../console
# Path to a hanzoai/openapi checkout — the SOT the agent-skills catalog is generated from.
OPENAPI_DIR ?= ../openapi
# The shipped binary is pure Go (Dockerfile: CGO_ENABLED=0 → scratch). Default all
# build/test targets to that mode so `make build`/`make test` exercise exactly
@@ -22,27 +24,38 @@ CONSOLE2_DIR ?= ../console2
# forces the fork to modernc too so the whole binary registers "sqlite" once.
CGO_ENABLED ?= 0
.PHONY: help webui build build-standalone run smoke test test-cgo vet tidy docker docker-push clean
.PHONY: help native webui agentskills build build-standalone hanzo run smoke test test-cgo vet tidy docker docker-push clean
help: ## Show this help.
@awk 'BEGIN{FS=":.*##";printf "\nUsage: make <target>\n\nTargets:\n"} /^[a-zA-Z_-]+:.*##/{printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
webui: ## Build the real console2 static bundle into webui/dist (go:embed source). CONSOLE2_DIR=<path to console2>.
webui: ## Build the real console static bundle into webui/dist (go:embed source). CONSOLE_DIR=<path to console>.
@command -v npm >/dev/null 2>&1 || { echo "npm is required to build the console bundle"; exit 1; }
@test -f "$(CONSOLE2_DIR)/package.json" || { echo "console2 checkout not found at $(CONSOLE2_DIR) — set CONSOLE2_DIR=<path>"; exit 1; }
@test -d "$(CONSOLE2_DIR)/node_modules" || (cd "$(CONSOLE2_DIR)" && npm install --no-audit --no-fund)
cd "$(CONSOLE2_DIR)" && NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=8192 npm run build:embed
@test -f "$(CONSOLE_DIR)/package.json" || { echo "console checkout not found at $(CONSOLE_DIR) — set CONSOLE_DIR=<path>"; exit 1; }
@test -d "$(CONSOLE_DIR)/node_modules" || (cd "$(CONSOLE_DIR)" && npm install --no-audit --no-fund)
cd "$(CONSOLE_DIR)" && NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=8192 npm run build:embed
# Overlay the fresh static export onto webui/dist, keeping only the tracked
# fallbacks (.gitignore + assets/.gitkeep); the real bundle is build-time-only.
find webui/dist -mindepth 1 -maxdepth 1 ! -name .gitignore ! -name assets -exec rm -rf {} +
cp -r "$(CONSOLE2_DIR)/out/." webui/dist/
@echo ">> embedded real console2 bundle into webui/dist (index.html $$(wc -c < webui/dist/index.html) bytes)"
cp -r "$(CONSOLE_DIR)/out/." webui/dist/
@echo ">> embedded real console bundle into webui/dist (index.html $$(wc -c < webui/dist/index.html) bytes)"
agentskills: ## Regenerate the FULL agent-skills catalog into clients/agentskills/catalog (go:embed source) from the openapi SOT. OPENAPI_DIR=<path to openapi>.
@test -f "$(OPENAPI_DIR)/skills.py" || { echo "openapi checkout not found at $(OPENAPI_DIR) — set OPENAPI_DIR=<path> or clone hanzoai/openapi"; exit 1; }
# skills.py rewrites the whole catalog dir; the .gitignore keeps only the tiny
# `ai` fallback tracked, so the full set is embedded at build but never committed.
python3 "$(OPENAPI_DIR)/skills.py" --no-services --out clients/agentskills/catalog
@echo ">> embedded FULL agent-skills catalog ($$(jq -r .skill_count clients/agentskills/catalog/hanzo/index.json) skills/brand)"
build: ## Build the unified cloud binary into ./bin/cloud (embeds whatever webui/dist holds — run `webui` first for the real console).
@mkdir -p bin
CGO_ENABLED=$(CGO_ENABLED) $(GO) build -ldflags="$(LDFLAGS)" -o bin/$(BIN) $(PKG)
build-standalone: webui build ## Build the REAL 1-binary console: console2 build:embed → webui/dist → go build.
build-standalone: webui build ## Build the REAL 1-binary console: console build:embed → webui/dist → go build.
hanzo: ## Build the hanzo control-plane CLI into ./bin/hanzo (pure Go, same mode as cmd/cloud — registers the ONE "sqlite" driver exactly once; a plain CGO_ENABLED=1 `go build ./cmd/hanzo` links the fork's mattn backend alongside the embedded modernc importers and panics, see header).
@mkdir -p bin
CGO_ENABLED=$(CGO_ENABLED) $(GO) build -ldflags="$(LDFLAGS)" -o bin/hanzo ./cmd/hanzo
run: build ## Run with iam,base,kms,gateway,o11y enabled (matches README quickstart).
./bin/$(BIN) --enable=iam,base,kms,gateway,o11y --brand=hanzo --domain=api.hanzo.ai
@@ -71,3 +84,6 @@ docker-push: docker ## Push the Docker image to ghcr.io. Requires docker login.
clean: ## Remove built artifacts.
rm -rf bin
native: ## Build the native flags evaluator staticlib (required for CGO=1 builds/tests).
cargo build --release --manifest-path native/flags/Cargo.toml
+16 -14
View File
@@ -15,7 +15,7 @@ docker run -p 8080:8080 ghcr.io/hanzoai/cloud:latest
## What this is
`hanzoai/cloud` is one Go binary that mounts every Hanzo subsystem (iam, kms, base, gateway, ai, commerce, vfs, mq, dns, amqp, mcp, o11y, ...) into a single multi-tenant process. Same artifact serves `api.hanzo.ai`, `api.osage.cloud`, `api.lux.cloud`, `api.zoo.cloud`, and every white-label reseller. Brand, enabled subsystems, and tenant scope are deployment configuration.
`hanzoai/cloud` is one Go binary that mounts every Hanzo subsystem (iam, kms, base, gateway, ai, commerce, vfs, mq, dns, amqp, mcp, o11y, ...) into a single multi-org process. Same artifact serves `api.hanzo.ai`, `api.osage.cloud`, `api.lux.cloud`, `api.zoo.cloud`, and every white-label reseller. Brand, enabled subsystems, and org scope are deployment configuration.
## `hanzo` — cloud control CLI
@@ -61,7 +61,7 @@ Implements:
## Architecture
```
api.{tenant}.{brand}
api.{org}.{brand}
|
hanzoai/cloud (one Go binary)
|
@@ -69,7 +69,7 @@ Implements:
| iam | base | kms | ai | gateway | ...
| Mount() | Mount() | Mount() | Mount() | Mount() |
+----------+----------+----------+----------+----------+
per-tenant SQLite (HIP-0302) | Hanzo IAM JWKS (HIP-0026)
per-org SQLite (HIP-0302) | Hanzo IAM JWKS (HIP-0026)
replicate -> S3 (HIP-0107) | ZAP inter-subsystem RPC
```
@@ -88,7 +88,7 @@ Per [HIP-0106](https://github.com/hanzoai/HIPs/blob/main/HIPs/hip-0106-unified-h
## Subsystems mounted
- `iam` — identity & access
- `base` — per-tenant SQLite + extension runtimes (per HIP-0105)
- `base` — per-org SQLite + extension runtimes (per HIP-0105)
- `kms` — secrets
- `commerce` — checkout, billing, pricing, invoicing (light router; NOT in PCI-DSS scope)
- `ai` — LLM control plane / RAG / model hub / MCP management (was hanzoai/cloud pre-rename)
@@ -122,7 +122,7 @@ built on Fiber v3. The ONE Go web framework. No `.Fast` escape hatch.
## Console UI — embedded in the ONE binary
The same `hanzoai/cloud` binary serves the [console](https://github.com/hanzoai/console2)
The same `hanzoai/cloud` binary serves the [console](https://github.com/hanzoai/console)
(`@hanzo/gui`) UI at the web root AND the `/v1` API from one process — one
artifact, one origin, no separate console Service. The UI is compiled in via
`//go:embed` (see `webui.go`).
@@ -130,7 +130,7 @@ artifact, one origin, no separate console Service. The UI is compiled in via
Pipeline (in the `Dockerfile`, before `go build`):
```
console stage → build console2 static bundle → /out
console stage → build console static bundle → /out
COPY --from=console /out/ → src/webui/dist/ (overlays the fallback shell)
build stage → go build → //go:embed all:webui/dist bakes it into /cloud
```
@@ -153,14 +153,16 @@ even without the Node toolchain. The image build overwrites `webui/dist` with th
real console bundle. See `webui_test.go` for the boot-and-assert tests
(`/` → shell, deep link → shell 200, `/v1/*` → API, unmatched `/v1` → 404).
> Honest current state: console2 ships 15 Next server route handlers
> (`app/**/route.ts`) that hold KMS-sourced service tokens and mint short-lived
> user tokens, so it emits a Node server bundle, not a static export
> (`output: export` would fail). Until console2 exposes a `build:embed` static
> target — or those handlers land here as native `/v1` endpoints — the image
> embeds the fallback shell, and the separate console2 Service stays up. The Go
> embed/serve plumbing is complete and needs no further change to light up the
> full console the moment the static bundle exists.
Current state: `hanzoai/console` exposes `build:embed` (`scripts/build-embed.mjs`),
which stashes its Next server route handlers (BFF proxies that collapse to the
cloud `/v1/*` the SPA calls same-origin), wraps the client catch-all pages for
`output: 'export'`, neutralizes the root layout's request-time `headers()` read,
and emits a real static export at `out/` (a ~360 KB `index.html` + `_next/`
chunks). The image build (and `make webui`) run it and overlay `webui/dist`, so
`//go:embed` bakes the FULL `@hanzo/gui` console into the ONE binary. The
Dockerfile console stage FAILS HARD if that bundle is missing or degenerate —
the placeholder shell can never silently ship to prod (escape hatch:
`--build-arg ALLOW_PLACEHOLDER=1` for a pure-Go dev image).
## Status
+431
View File
@@ -0,0 +1,431 @@
// Package apps is the composition root: the single, explicit list of which
// Hanzo cloud subsystems are linked into the binary AND the order they mount in.
//
// Wire() returns []cloud.MountSpec in mount order (slice position == order). There
// is no init()-registry and no order-int: adding, removing, or reordering a
// subsystem is a one-line edit to Wire(), read top-to-bottom. cmd/cloud and
// cmd/hanzo both call Wire() and thread the slice into cloud.Serve — the set is
// defined ONCE, here.
//
// (This package must NOT live in package cloud: the subsystems import cloud for
// Deps + Typed, so a root-package bundle would form an import cycle. As a sibling
// subpackage it composes them without one.)
//
// HIP-0106: the unified cloud binary is the APPLICATION layer plus the embedded KMS
// secrets plane and the embedded IAM identity plane ("one Go binary embeds IAM +
// KMS + o11y"). The edge/infra tier (mcp, gateway, ingress-edge) runs as its own
// deployments for blast-radius isolation; several application folds (iam, base,
// commerce, captable, dataroom, sign, ingress) are STAGED — linked here but mounted
// only when the operator names them in CLOUD_ENABLE.
//
// Ordering provenance: order-int ascending; ties in the exact order the
// pre-refactor init()-registry mounted them, captured empirically from origin/main
// @c504d2b (68 self-registering specs) and frozen by TestWireOrderMatchesFrozen
// (wire_test.go). ai (@150) and the hanzoai/o11y module wildcard (@70) are NOT in
// that dump: on their wave-2 tags (ai v1.805.2, o11y v1.5.12) they no longer
// self-register, so origin/main currently DROPS them (a latent regression this
// composition root fixes). They are wired back at their order-int slots — o11y-ext
// kept adjacent to the in-repo o11y read-plane (@69); ai as the last /v1/* catch-all
// before plugins (@900). Do not re-sort; edit positions deliberately.
//
//go:generate go run ../cmd/gen-app-cmds
package apps
import (
"context"
"fmt"
"os"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
// External subsystem modules. As of the atomic wave-2 bump they NO LONGER
// self-register (no cloud.Register in their init) — the composition root wires
// each one explicitly below, so removing an entry here is the ONLY way to drop it.
"github.com/hanzoai/ai"
"github.com/hanzoai/authz"
"github.com/hanzoai/licensing"
"github.com/hanzoai/metrics"
// In-repo subsystem packages (clients/*). Each exports a Mount (and, where it
// owns process-lifetime resources, a Shutdown); Wire references them directly.
"github.com/hanzoai/cloud/clients/account"
"github.com/hanzoai/cloud/clients/admin"
"github.com/hanzoai/cloud/clients/ads"
"github.com/hanzoai/cloud/clients/affiliates"
"github.com/hanzoai/cloud/clients/agent"
"github.com/hanzoai/cloud/clients/agents"
"github.com/hanzoai/cloud/clients/agentskills"
"github.com/hanzoai/cloud/clients/analytics"
"github.com/hanzoai/cloud/clients/auditlog"
"github.com/hanzoai/cloud/clients/authors"
"github.com/hanzoai/cloud/clients/automations"
"github.com/hanzoai/cloud/clients/base"
"github.com/hanzoai/cloud/clients/billing"
"github.com/hanzoai/cloud/clients/bots"
"github.com/hanzoai/cloud/clients/captable"
"github.com/hanzoai/cloud/clients/catalogsync"
"github.com/hanzoai/cloud/clients/code"
"github.com/hanzoai/cloud/clients/company"
"github.com/hanzoai/cloud/clients/connectorruntime"
"github.com/hanzoai/cloud/clients/content"
"github.com/hanzoai/cloud/clients/crm"
"github.com/hanzoai/cloud/clients/cron"
"github.com/hanzoai/cloud/clients/dataroom"
"github.com/hanzoai/cloud/clients/deploy"
"github.com/hanzoai/cloud/clients/do"
"github.com/hanzoai/cloud/clients/entitlements"
"github.com/hanzoai/cloud/clients/eval"
"github.com/hanzoai/cloud/clients/exec"
"github.com/hanzoai/cloud/clients/flags"
"github.com/hanzoai/cloud/clients/framework"
"github.com/hanzoai/cloud/clients/functions"
"github.com/hanzoai/cloud/clients/gateway"
"github.com/hanzoai/cloud/clients/git"
"github.com/hanzoai/cloud/clients/graph"
"github.com/hanzoai/cloud/clients/guide"
"github.com/hanzoai/cloud/clients/iam"
"github.com/hanzoai/cloud/clients/iam2"
"github.com/hanzoai/cloud/clients/ingress"
"github.com/hanzoai/cloud/clients/integrations"
"github.com/hanzoai/cloud/clients/kafka"
"github.com/hanzoai/cloud/clients/kms"
"github.com/hanzoai/cloud/clients/knowledge"
"github.com/hanzoai/cloud/clients/link"
"github.com/hanzoai/cloud/clients/marketing"
"github.com/hanzoai/cloud/clients/marketplace"
"github.com/hanzoai/cloud/clients/ml"
"github.com/hanzoai/cloud/clients/notify"
"github.com/hanzoai/cloud/clients/o11y"
"github.com/hanzoai/cloud/clients/paas"
"github.com/hanzoai/cloud/clients/plan"
"github.com/hanzoai/cloud/clients/platform"
"github.com/hanzoai/cloud/clients/plugin"
"github.com/hanzoai/cloud/clients/pricing"
"github.com/hanzoai/cloud/clients/product"
"github.com/hanzoai/cloud/clients/projects"
"github.com/hanzoai/cloud/clients/prompts"
"github.com/hanzoai/cloud/clients/provisioning"
"github.com/hanzoai/cloud/clients/pubsub"
"github.com/hanzoai/cloud/clients/referrals"
"github.com/hanzoai/cloud/clients/runtime"
"github.com/hanzoai/cloud/clients/sbom"
"github.com/hanzoai/cloud/clients/security"
"github.com/hanzoai/cloud/clients/settings"
"github.com/hanzoai/cloud/clients/sign"
"github.com/hanzoai/cloud/clients/social"
"github.com/hanzoai/cloud/clients/storage"
"github.com/hanzoai/cloud/clients/sync"
"github.com/hanzoai/cloud/clients/tasks"
"github.com/hanzoai/cloud/clients/team"
"github.com/hanzoai/cloud/clients/templates"
"github.com/hanzoai/cloud/clients/tools"
"github.com/hanzoai/cloud/clients/tracker"
"github.com/hanzoai/cloud/clients/treasury"
"github.com/hanzoai/cloud/clients/usage"
"github.com/hanzoai/cloud/clients/visor"
"github.com/hanzoai/cloud/clients/wallets"
"github.com/hanzoai/cloud/clients/websearch"
"github.com/hanzoai/cloud/clients/world"
"github.com/hanzoai/cloud/clients/x402"
"github.com/hanzoai/cloud/clients/zt"
// Framework CONTENT modules — NOT mount subsystems (they carry no HTTP surface
// and are absent from Wire()). Each registers its DocType fixtures and, for erp,
// its ledger-posting lifecycle hooks into the clients/framework DocType engine
// from a package init() (framework.RegisterModule) — the idiomatic
// register-into-a-registry pattern (cf. database/sql drivers). The framework
// engine is mounted (always-on, /v1/framework/*) but its module registry is
// populated ONLY by these blank imports. Dropping one silently strips that
// lane's DocTypes and hooks — for erp, the immutable ledger postings — from the
// binary with NO mount change and NO failing mount test. #248 dropped them;
// TestFrameworkContentModulesLinked now guards against a recurrence. Keep.
_ "github.com/hanzoai/cloud/clients/cms"
_ "github.com/hanzoai/cloud/clients/erp"
_ "github.com/hanzoai/cloud/clients/help"
)
// init wires the cross-subsystem func seams — the composition root is the one place
// that may import two leaf subsystems at once, so a connection neither can express
// alone lives here. git's push→index reactor calls the code index without git
// importing code: the adapter converts git's IndexedFile to code's File and drops the
// result (the reactor only needs success/failure). Stored once at load; invoked on
// push, long after mount, so there is no ordering dependency. Same
// register-into-a-registry idiom the framework content modules use above.
func init() {
git.SetIndexer(func(ctx context.Context, org, billingOrg, project, repo string, files []git.IndexedFile) error {
in := make([]code.File, len(files))
for i, f := range files {
in[i] = code.File{Path: f.Path, Content: f.Content}
}
_, err := code.IndexFiles(ctx, org, billingOrg, project, repo, in)
return err
})
}
// identitySpec selects the ONE identity backend that owns /v1/iam/* (+ /login/oauth/*)
// for this boot. CLOUD_IAM_IMPL=iam2 picks the clean-room iam2 (zip+orm, beego-free);
// anything else — including unset, the production default — keeps the legacy beego
// Casdoor embed, byte-for-byte today's behavior. The two impls register the SAME
// absolute prefixes and therefore cannot co-mount, so selection (this func) stays
// separate from activation (cfg.Enabled): exactly one spec occupies the identity slot
// in Wire, preserving mount order either way. os.Getenv (not the unexported
// cloud.getenv, which is unreachable from package apps) is the read — CLOUD_IAM_IMPL is
// the deliberate, off-by-default opt-in that keeps iam2 inert until a canary flips it.
func identitySpec() cloud.MountSpec {
if os.Getenv("CLOUD_IAM_IMPL") == "iam2" {
return cloud.MountSpec{Name: "iam2", Mount: iam2.Mount}
}
return cloud.MountSpec{Name: "iam", Mount: iam.Mount}
}
// Wire returns every linked subsystem as a cloud.MountSpec, in mount order. The
// slice position IS the order: cloud.MountAll iterates it as-given, registering each
// subsystem's teardown as a zip shutdown hook so teardown runs in reverse (LIFO).
// Enablement is a separate axis: cloud.Serve mounts only the specs cfg.Enabled(name)
// admits, so a STAGED subsystem is linked but inert until named.
func Wire() []cloud.MountSpec {
return []cloud.MountSpec{
// embedded NATS :4222 + JetStream.
{Name: "pubsub", Mount: pubsub.Mount, Shutdown: pubsub.Shutdown},
// embedded Kafka adaptor :9092.
{Name: "kafka", Mount: kafka.Mount, Shutdown: kafka.Shutdown},
// /.well-known/agent-skills/* — before IAM's /.well-known/* wildcard (50).
{Name: "agentskills", Mount: agentskills.Mount},
// Insights feature-flag evaluation seam (no routes; a hot value plane).
{Name: "flags", Mount: flags.Mount, Shutdown: flags.Shutdown, OwnsHealth: true},
// Embedded KMS secrets plane /v1/kms/*. OwnsHealth: serves its own fail-closed
// /v1/kms/health (the generic always-ok route must not shadow it). Fails closed
// until the operator injects CLOUD_KMS_MASTER_KEY_REF. (Its in-process client
// factory is registered separately via cloud.RegisterKMSClientFactory.)
{Name: "kms", Mount: kms.Mount, OwnsHealth: true},
// hanzoai/metrics — native o11y. It declares its OWN narrow metrics.Deps (no
// hanzoai/cloud import), so Typed cannot adapt it; mountMetrics builds that Deps
// from cloud.Deps and calls metrics.Mount explicitly.
{Name: "metrics", Mount: mountMetrics},
// Embedded runtime edge (/v1/ingress/*). STAGED — edge listeners stay off unless
// the operator names "ingress" in CLOUD_ENABLE.
{Name: "ingress", Mount: ingress.Mount, Shutdown: ingress.Shutdown},
// SPECIFIC self-service routes (/v1/iam/{keys,onboard}, /v1/csrf, /v1/embed-status,
// /v1/commerce/topup/wallet). MUST mount before the IAM /v1/iam/* wildcard (50) so
// they win Fiber's first-match scan (framework-guaranteed since zip v1.3.0).
{Name: "account", Mount: account.MountAccount},
// Embedded IAM identity plane (/v1/iam/*, /.well-known/*, /login/oauth/*, /_/iam/*,
// /cas/*, /scim/*) — the identity authority, mounts before its dependents. STAGED:
// the operator adds "iam" to --enable only after IAM config + the fold are verified.
// Which IMPLEMENTATION owns these prefixes is selected by CLOUD_IAM_IMPL
// (identitySpec): the clean-room iam2 (zip+orm, beego-free) when =="iam2", else the
// legacy beego Casdoor embed — the default (unset = today's behavior, byte-for-byte).
// Both register the SAME absolute paths and cannot co-mount, so this is an either/or
// switch at this ONE slot, never a shadow prefix.
identitySpec(),
// Embedded Base app engine + viral waitlist (/v1/waitlist/*). STAGED behind
// CLOUD_BASE_EMBED. OwnsHealth: native /v1/base/health.
{Name: "base", Mount: base.Mount, Shutdown: base.Shutdown, OwnsHealth: true},
// The ONE observability subsystem: the in-repo o11y READ plane + runtime-handler
// install (o11y.SetHandler), with the hanzoai/o11y module wildcard /v1/o11y/*
// folded in as the TERMINAL sub-mount INSIDE o11y.MountO11y. Every specific
// /v1/o11y/* route registers before that wildcard, so Fiber's in-order match gives
// them precedence. NOT OwnsHealth: /v1/o11y/health stays the generic always-ok
// route (registered before MountAll), exactly as when the former module co-entry —
// which also set OwnsHealth=false — triggered it.
{Name: "o11y", Mount: o11y.MountO11y, Shutdown: o11y.ShutdownO11y},
{Name: "authz", Mount: authz.Mount},
// Embedded commerce plane /v1/commerce/*, /_/commerce/* — the hanzoai/commerce
// MODULE via the adapter in commerce.go (un-forked; the in-process
// CommerceClient is wired directly in pickCommerceClient).
{Name: "commerce", Mount: mountCommerce},
{Name: "licensing", Mount: licensing.Mount},
{Name: "plans", Mount: plan.Mount, OwnsHealth: true},
{Name: "pricing", Mount: pricing.Mount, OwnsHealth: true},
// /v1/s3/buckets/* + /v1/s3/health. Mounts BEFORE provisioning (120) so its static
// routes win over provisioning's /v1/s3/:name. OwnsHealth (real fail-closed probe).
{Name: "storage", Mount: storage.Mount, OwnsHealth: true},
// Provisioning control plane: /v1/sql,/v1/vector,/v1/datastore,/v1/kv,/v1/search,/v1/s3,/v1/docdb.
{Name: "provisioning", Mount: provisioning.Mount},
{Name: "billing", Mount: billing.Mount},
// CATCH-ALL /v1/billing/* + /v1/commerce/* data bridges — AFTER clients/billing
// (121) + the commerce embed (100). Same clients/account package as "account" (48).
{Name: "account-bridge", Mount: account.MountBridge},
{Name: "do", Mount: do.Mount},
{Name: "platform", Mount: platform.Mount, OwnsHealth: true},
{Name: "projects", Mount: projects.Mount},
{Name: "prompts", Mount: prompts.Mount},
{Name: "agents", Mount: agents.Mount, Shutdown: agents.Shutdown},
// The unified AI login manager registry (/v1/links). Mounts AFTER agents so
// a link revoke can stop the affected agent sessions in-process.
{Name: "link", Mount: link.Mount, Shutdown: link.Shutdown},
{Name: "wallets", Mount: wallets.Mount, Shutdown: ctxShutdown(wallets.Shutdown)},
// x402 pay-per-use: settles a signed ERC-3009 authorization to a recipient
// wallet through the metering spine. Mounts AFTER wallets (it resolves the
// recipient via wallets.ResolvePaymentTarget) and provides the Enforce
// middleware a marketplace applies to its priced routes.
{Name: "x402", Mount: x402.Mount, Shutdown: ctxShutdown(x402.Shutdown)},
{Name: "paas", Mount: paas.Mount, OwnsHealth: true},
// GitOps deploy dashboard /v1/deploy/* (the ArgoCD-grade fleet view over the
// operator App CRs). After paas so the release seam paas installs is registered
// before a gitops rollback delegates to it; owns its own /v1/deploy/health.
{Name: "deploy", Mount: deploy.Mount, OwnsHealth: true},
{Name: "functions", Mount: functions.Mount},
{Name: "tracker", Mount: tracker.Mount},
{Name: "templates", Mount: templates.Mount},
{Name: "framework", Mount: framework.Mount, Shutdown: ctxShutdown(framework.Shutdown)},
{Name: "knowledge", Mount: knowledge.Mount},
// Marketing content loop /v1/content/* (generate → CMS → transition → publish).
// After framework (its DocType store the ops read/write) + knowledge (the sibling
// framework lane); before the AI /v1/* catch-all so /v1/content/* resolves here.
// CRUD/tenancy/install are framework's; this adds the board, lifecycle transition,
// and the generate/publish orchestration over the zen5 + studio + social edges.
{Name: "content", Mount: content.Mount, Shutdown: ctxShutdown(content.Shutdown)},
// Reverse storefront loop: consume the commerce COMMERCE stream (product.created)
// → content.EnsureCatalogAsset (render the new product's ecom asset, design==slug).
// After content (whose EnsureCatalogAsset it drives). Inert until CLOUD_COMMERCE_NATS_URL
// names the NATS carrying commerce catalog events — the reverse of the forward edge.
{Name: "catalogsync", Mount: catalogsync.Mount, Shutdown: catalogsync.Shutdown},
{Name: "ml", Mount: ml.Mount, OwnsHealth: true},
{Name: "usage", Mount: usage.Mount},
{Name: "crm", Mount: crm.Mount},
// Native /v1/marketing/* — the in-process fold of github.com/hanzoai/marketing
// (per-org campaign store on Base/SQLite), twin of crm. Owns a DB handle, so
// its Shutdown closes it cleanly on SIGTERM (ctxShutdown adapts func() error).
{Name: "marketing", Mount: marketing.Mount, Shutdown: ctxShutdown(marketing.Shutdown)},
// Native /v1/ads/* — the net-new per-org ad-campaign store on Base/SQLite,
// twin of crm/marketing. Owns a DB handle, so its Shutdown closes it cleanly
// on SIGTERM (ctxShutdown adapts func() error).
{Name: "ads", Mount: ads.Mount, Shutdown: ctxShutdown(ads.Shutdown)},
// Native /v1/social/* — the in-process fold of the live social stack
// (github.com/hanzoai/social: social-backend/frontend/orchestrator, a Postiz-style
// scheduler), a per-org accounts+posts store on Base/SQLite, twin of crm. Owns a DB
// handle, so its Shutdown closes it cleanly on SIGTERM (ctxShutdown adapts func() error).
{Name: "social", Mount: social.Mount, Shutdown: ctxShutdown(social.Shutdown)},
{Name: "analytics", Mount: analytics.Mount, OwnsHealth: true},
{Name: "git", Mount: git.Mount},
// Universal sync (/v1/sync/links + engine). Registers the cloud.SyncEngine the
// GitHub/Gitea webhooks enqueue to; git is its first provider. Owns per-org
// DB handles, so its Shutdown closes them on SIGTERM.
{Name: "sync", Mount: sync.Mount, Shutdown: ctxShutdown(sync.Shutdown)},
{Name: "visor", Mount: visor.Mount},
// Cap table on Base via goja. STAGED behind CLOUD_ENABLE.
{Name: "captable", Mount: captable.Mount, Shutdown: captable.Shutdown},
{Name: "code", Mount: code.Mount, Shutdown: code.Shutdown},
{Name: "zero-trust", Mount: zt.Mount},
// Data rooms via goja + per-tenant Base. STAGED behind CLOUD_ENABLE. OwnsHealth.
{Name: "dataroom", Mount: dataroom.Mount, Shutdown: dataroom.Shutdown, OwnsHealth: true},
{Name: "graph", Mount: graph.Mount},
{Name: "security", Mount: security.Mount, Shutdown: ctxShutdown(security.Shutdown), OwnsHealth: true},
{Name: "integrations", Mount: integrations.Mount, Shutdown: integrations.Shutdown},
{Name: "sbom", Mount: sbom.Mount, OwnsHealth: true},
{Name: "team", Mount: team.Mount, Shutdown: ctxShutdown(team.Shutdown)},
{Name: "settings", Mount: settings.Mount, Shutdown: settings.Shutdown},
{Name: "notify", Mount: notify.Mount, OwnsHealth: true},
{Name: "gateway", Mount: gateway.Mount},
{Name: "entitlements", Mount: entitlements.Mount, Shutdown: entitlements.Shutdown},
{Name: "exec", Mount: exec.Mount},
{Name: "websearch", Mount: websearch.Mount},
{Name: "world", Mount: world.Mount, Shutdown: ctxShutdown(world.Shutdown)},
// The bot runtime's ops face (/v1/bot/*). The transport itself is domain-free;
// the run control plane is "bots" below.
{Name: "runtime", Mount: runtime.Mount},
{Name: "authors", Mount: authors.Mount, Shutdown: ctxShutdown(authors.Shutdown)},
{Name: "bots", Mount: bots.Mount},
{Name: "audit", Mount: auditlog.Mount},
{Name: "affiliates", Mount: affiliates.Mount},
// Hanzo Sign (e-signature) via goja + per-tenant Base. STAGED behind CLOUD_ENABLE. OwnsHealth.
{Name: "sign", Mount: sign.Mount, Shutdown: sign.Shutdown, OwnsHealth: true},
{Name: "product", Mount: product.Mount},
{Name: "evals", Mount: eval.Mount},
{Name: "treasury", Mount: treasury.Mount, Shutdown: ctxShutdown(treasury.Shutdown)},
{Name: "admin", Mount: admin.Mount},
// Launch-control (per-service waitlist mode) folded into the flags engine: the
// mode IS the switch waitlist.<svc>, the board is the /v1/admin/services lens,
// and /v1/featuregate/mode is served by flags. featuregate is no longer a mounted
// subsystem — it exposes only the native Enforce middleware (wired in serve.go),
// a consumer of flags.WaitlistModeForHost.
{Name: "tasks", Mount: tasks.Mount},
// Platform cron: durable schedules on the shared tasks engine replacing
// every k8s CronJob — entries are cron.hanzo.ai ConfigMaps (universe git),
// runs visible in the Tasks console. Mounts no routes; starts after the
// engine is wired.
{Name: "cron", Mount: cron.Mount},
{Name: "automations", Mount: automations.Mount, Shutdown: automations.Shutdown},
// Native single-connector execution (HIP-0126): runs an ActivePieces JS
// connector action in-process via goja (clients/connectorruntime), retiring
// the standalone auto Node engine. Mounts POST /v1/automations/connectors/:id/run,
// paired with the automations catalogue above; STAGED like the rest.
{Name: "connectorruntime", Mount: connectorruntime.Mount},
// Unified tool plane: /v1/tools/* — the ONE registry (connectors, functions,
// agents, skills, external MCP servers, full-cloud-control /v1 routes), per-org
// activation, and the unified MCP endpoint. Sources register into it from their
// own Mounts, so mount position is not load-bearing (List/Dispatch run at request
// time); placed after automations, before the zen/ai catch-all so /v1/tools wins.
{Name: "tools", Mount: tools.Mount, Shutdown: tools.Shutdown},
// Marketplace: /v1/marketplace/* — listing/discovery/install over the tool plane,
// with x402-priced monetized listings. Mounts after tools (it fills the price seam).
{Name: "marketplace", Mount: marketplace.Mount, Shutdown: marketplace.Shutdown},
{Name: "referrals", Mount: referrals.Mount},
// Business AI Guide /v1/guide/* — the interactive launch checklist engine +
// the agent that executes a step through the per-principal MCP plane. After
// automations (whose InvokeTool it drives) and referrals; before the ai
// catch-all. Owns per-org SQLite, so its Shutdown closes the stores.
{Name: "guide", Mount: guide.Mount, Shutdown: ctxShutdown(guide.Shutdown)},
// Hanzo Company — the incorporation + fundraising state machine
// (/v1/company/*). Mounts after the seams it composes (integrations for the
// google token custody; captable/dataroom facades) and before the /v1/* AI
// catch-all so its routes resolve here.
{Name: "company", Mount: company.Mount, Shutdown: company.Shutdown},
// Chat orchestrator — POST /v1/chat: ONE LLM tool-calling round over the tool
// plane. It COMPOSES the ai completion path (in-process, so per-org billing
// runs) + the unified tool registry, and splits the model's tool calls into
// server-executed actions and client-applied ops. Mounts BEFORE the zen/ai
// catch-all so /v1/chat resolves here (Fiber first-match); the ai module's
// beego /v1/chat alias behind its /v1/* glob is thereby shadowed, while ai
// keeps /v1/chat/completions + /v1/completions.
{Name: "agent", Mount: agent.Mount},
// The bare /v1/* AI catch-all — the LAST route position. Every owning subsystem above
// wins its own namespace (Fiber first-match); AI is the fallback for the rest of /v1/*.
// zen mounts as a /v1-scoped Claim middleware BEFORE ai: it routes zen* models
// to zen's serving layer in-process (identity, tools, 1M ladder, codec) and
// c.Next()s everything else to ai. zen owns the zen family; ai owns every
// other model and the /v1/models list. Order is load-bearing — Claim must
// run before ai's catch-all. (See hip-00NN.)
{Name: "zen", Mount: mountZen},
{Name: "ai", Mount: ai.Mount},
// Runtime wasm/proxy plugins — mounts dead last.
{Name: "plugins", Mount: plugin.Mount},
}
}
// ServeSingle is the ONE way to run a single app standalone: validate `name`
// against Wire(), then serve exactly it (cloud.Serve with a one-name enable
// list — MountAll mounts only it). It is the path `hanzo <name>` already uses;
// promoting it here lets each cmd/<app>/main.go stub reuse it instead of
// re-implementing the dispatch, so adding an app in Wire() is still the one edit
// and its standalone binary comes for free (generated). Returns an error for an
// unknown name rather than booting a no-op.
func ServeSingle(name string) error {
if name == "" {
return fmt.Errorf("ServeSingle: empty app name")
}
for _, spec := range Wire() {
if spec.Name == name {
return cloud.Serve(Wire(), []string{name})
}
}
return fmt.Errorf("ServeSingle: unknown app %q — run `hanzo code ls`/`hanzo` for the list", name)
}
// mountMetrics adapts hanzoai/metrics into a cloud.MountFunc. Unlike the other
// externals, metrics declares its OWN narrow Deps (Logger, DataDir, Brand) and does
// not import hanzoai/cloud, so cloud.Typed cannot bridge it: the composition root
// builds metrics.Deps from cloud.Deps and calls metrics.Mount explicitly here.
func mountMetrics(a *zip.App, deps cloud.Deps) error {
return metrics.Mount(a, metrics.Deps{Logger: deps.Logger, DataDir: deps.DataDir, Brand: deps.Brand})
}
// ctxShutdown adapts a subsystem's zero-arg Shutdown() error to the
// cloud.ShutdownFunc(ctx) signature. Several subsystems expose the simpler form
// (their teardown ignores the deadline); this bridges the impedance mismatch in ONE
// place so the Wire entries stay declarative — no inline closures.
func ctxShutdown(f func() error) cloud.ShutdownFunc {
return func(context.Context) error { return f() }
}
+217
View File
@@ -0,0 +1,217 @@
// Copyright © 2026 Hanzo AI. MIT License.
// commerce.go mounts the hanzoai/commerce MODULE into the unified cloud binary
// (HIP-0106) via the NATIVE co-residence contract: commerce registers its routes
// directly on the HOST's zip app (EmbedConfig.App) — one router, one specificity
// space, zero handler adaptation. This adapter narrows cloud.Deps, boots the
// embed, and wires the in-process seams. Direction is one-way: cloud → commerce.
//
// PCI SCOPE. Commerce is a LIGHT ROUTER, NOT in PCI-DSS scope: tokens + intent IDs
// only, NEVER a PAN. PAN-touching paths call the out-of-process Payments / Vault
// (ZAP-RPC); when those clients are absent the payment handlers fail closed while
// tenant config + admin stay served — mountCommerce warns loudly at startup.
//
// FAIL-SOFT. A broken Embed does NOT crash the binary: commerce degrades to a 503
// on its own prefixes while every co-resident subsystem stays up.
package apps
import (
"context"
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients/commerceclient"
"github.com/hanzoai/cloud/clients/commerceinproc"
"github.com/hanzoai/commerce"
commercebilling "github.com/hanzoai/commerce/api/billing"
commercestore "github.com/hanzoai/commerce/api/store"
commercemid "github.com/hanzoai/commerce/middleware"
"github.com/hanzoai/commerce/middleware/iammiddleware"
log "github.com/luxfi/log"
"github.com/zap-proto/zip"
)
func init() {
// In-process CommerceClient factory — pickCommerceClient calls it when the
// commerce subsystem is enabled. Registered HERE (not called directly from
// package cloud) because commerceclient's entitlement client imports
// clients/plan, which imports cloud: the hook keeps the package graph acyclic.
cloud.RegisterCommerceClientFactory(func(cfg *cloud.Config, _ log.Logger) cloud.CommerceClient {
return commerceclient.InProcessClient(cfg.Brand)
})
}
// commercePrefixes is every root path the commerce surface owns on the shared
// app. Under the native SharedApp contract most of these are registered by
// commerce's own setupRoutes; the list is the fail-closed 503 set AND the wire
// contract commerce_prefix_test pins — the route families a session gate or the
// AI /v1/* catch-all must never swallow:
var commercePrefixes = []string{
"/v1/commerce", // public checkout + tenant + catalog + deposits
"/_/commerce", // tenant-admin surface
// The BARE store surface: GET /v1/store/current (the org-scoped default
// store the admin dashboard AND the content storefront edge resolve), the
// per-listing upsert /v1/store/:id/listing/:slug the publish edge writes,
// and the public storefront reads karma.style serves at runtime. Without
// this owner, /v1/store/* fell through to the bare /v1/* AI catch-all —
// whose prepaid BALANCE gate 402'd every store read (a store-metadata read
// must never require an LLM balance).
"/v1/store",
// Payment-provider webhook receiver (POST /v1/billing/webhooks/:provider —
// Square et al). The provider's HMAC over the registered notification URL +
// body IS the auth; a bearer gate is impossible for provider callbacks.
"/v1/billing/webhooks",
// The platform auto-recharge sweep (PlatformOnly, POST .../run-all). The
// durable cron's poke carries the COMMERCE_SERVICE_TOKEN bearer; without
// this owner it lands on the account-bridge /v1/billing/* catch-all, whose
// session gate 403s a service token. (Landed 5x before the unfork — #274 —
// and the pin test lives beside THIS list so it can't silently regress.)
"/v1/billing/auto-recharge",
}
// mountCommerce boots commerce ON the shared zip app (native co-residence).
// commerce's own setupRoutes registers /v1/commerce/* and /_/commerce/*
// directly; the standalone-only surfaces (bare /healthz, legacy /admin SPA,
// checkout SPA root catch-all, Listen) are skipped by the SharedApp contract.
// This adapter registers the remaining wire-contract families with commerce's
// own gate chains (see commercePrefixes).
func mountCommerce(app *zip.App, deps cloud.Deps) error {
if app == nil {
return fmt.Errorf("commerce: nil zip.App")
}
if deps.Logger == nil {
return fmt.Errorf("commerce: nil deps.Logger")
}
lg := deps.Logger.New("subsystem", "commerce")
if deps.Payments == nil {
lg.Warn("commerce: deps.Payments is nil — payment intent paths will fail; tenant config + admin still served")
}
if deps.Vault == nil {
lg.Warn("commerce: deps.Vault is nil — vault charge paths unavailable; tenant config + admin still served")
}
// Native zip health endpoint — registered FIRST so probes answer even when
// the embed fails below.
app.Get("/_/commerce/healthz", func(c *zip.Ctx) error {
return c.JSON(http.StatusOK, map[string]string{"status": "ok", "service": "commerce"})
})
// commerce persists its per-org SQLite + `base` tree under <DataDir>/commerce,
// NEVER at DataDir directly: cloud already owns DataDir/orgs and DataDir/base,
// and commerce also writes orgs/ + base/ — sharing the root would collide two
// apps on the same SQLite files and corrupt them.
dataDir := "/var/lib/cloud/commerce"
if deps.DataDir != "" {
dataDir = filepath.Join(deps.DataDir, "commerce")
}
embedded, err := commerce.Embed(context.Background(), commerce.EmbedConfig{
DataDir: dataDir,
// RequireIdentity stays gateway-owned: the gateway in front of the cloud
// binary is the trust boundary per HIP-0026.
RequireIdentity: false,
// THE native co-residence contract: commerce registers its routes on
// cloud's own app — no second engine, no net/http adaptation.
App: app,
// ONE LEDGER: commerce's POST /v1/billing/credit mints into cloud's native
// finance ledger (the SAME per-org account the AI spend-gate reads), so a
// granted credit is immediately spendable. commerce.Embed calls
// creditledger.Set(this) before routes register; nil would leave commerce on
// its own datastore (standalone), but in this unified binary finance is
// co-resident, so we inject the finance-backed ledger adapter.
Ledger: ledger{},
})
if err != nil {
lg.Error("commerce embed failed — serving fail-closed 503 (cloud stays up)", "err", err)
mountCommerceFailClosed(app)
return nil
}
// The BARE /v1/store surface (see commercePrefixes). Group-scoped chain
// mirrors the standalone /v1 bundle: gated request context, host, IAM
// resolution; store.Route's own tokenRequired arg gates the CRUD.
storeV1 := app.Group("/v1")
storeV1.Use(commercemid.AddHost(), commercemid.RequestContext(), commerceErrorScope())
// Unconditional, exactly like the standalone bundle: IAMTokenRequired
// no-ops gracefully when IAM is not initialized.
storeV1.Use(iammiddleware.IAMTokenRequired())
commercestore.Route(storeV1, commercemid.TokenRequired())
// Provider webhook intake at the LIVE registered path. Chain mirrors the
// commerce-standalone posture: gated request context, then the sessionless
// HMAC-verified handler.
app.Post("/v1/billing/webhooks/:provider", commercemid.RequestContext(), commercebilling.HandleProviderWebhook)
// Durable-cron auto-recharge poke (COMMERCE_SERVICE_TOKEN bearer) at its
// live path — the bridge's session gate would 403 the poke. Same gate
// chain the commerce route table uses: TokenRequired authenticates the
// service token, PlatformOnly authorizes the mint.
app.Post("/v1/billing/auto-recharge/run-all",
commercemid.RequestContext(),
commercemid.TokenRequired(),
commercemid.PlatformOnly(),
commercebilling.RunAutoRechargeAllOrgs,
)
// In-process seams:
// - commerceinproc routes the S2S billing byte-stream into the co-resident
// app (the metering debit path) instead of a socket to a standalone pod.
// - commerceclient reads the Embedded's datastore DIRECTLY (entitlements +
// BalanceCents) — no HTTP shape at all.
commerceinproc.SetApp(app)
commerceclient.PublishEmbedded(embedded)
lg.Info("commerce embedded natively (hanzoai/commerce module on the shared zip app)",
"data_dir", dataDir,
"brand", deps.Brand,
"env", deps.Env,
)
return nil
}
// mountCommerceFailClosed serves an honest JSON 503 on every commerce prefix when
// the embed cannot boot, so /v1/commerce/* answers "commerce unavailable" instead
// commerceErrorScope confines commerce's JSON error envelope to commerce's OWN
// routes. commercemid.ErrorHandlerJSON is a `/v1` GROUP middleware, and fiber
// matches group middleware by PREFIX, not by the handle a route registered on —
// so on the shared `/v1` it wraps every subsystem mounted AFTER commerce and
// flattens their typed zip.HTTPError (403/400/…) into a blanket 500 (the store
// envelope always renders 500). Guarded by commercePrefixes, the envelope stays on
// commerce and every other subsystem renders its own status via zip's default
// handler — the pre-commerce subsystems (kms, o11y, …) already do; this makes the
// post-commerce ones (projects, agents, wallets, …) match.
func commerceErrorScope() zip.Handler {
envelope := commercemid.ErrorHandlerJSON()
return func(c *zip.Ctx) error {
if hasCommercePrefix(c.Path()) {
return envelope(c)
}
return c.Next()
}
}
// hasCommercePrefix reports whether path is a commerce-owned root (an exact prefix
// or a child of one), the SAME ownership commercePrefixes encodes for the
// fail-closed mount.
func hasCommercePrefix(path string) bool {
for _, p := range commercePrefixes {
if path == p || strings.HasPrefix(path, p+"/") {
return true
}
}
return false
}
// of falling through to another subsystem's catch-all.
func mountCommerceFailClosed(app *zip.App) {
failed := func(c *zip.Ctx) error {
c.SetHeader("Content-Type", "application/json")
return c.Bytes(http.StatusServiceUnavailable, []byte(`{"error":"commerce unavailable","code":503}`))
}
for _, p := range commercePrefixes {
app.All(p+"/*", failed)
}
}
+82
View File
@@ -0,0 +1,82 @@
package apps
import (
"io"
"net/http/httptest"
"strings"
"testing"
commercemid "github.com/hanzoai/commerce/middleware"
"github.com/zap-proto/zip"
)
// TestCommerceErrorScope proves commerceErrorScope() confines commerce's always-500
// JSON envelope to commerce-owned prefixes: a post-commerce subsystem route
// (/v1/projects) that returns a typed 403 renders 403 (zip default), while a
// commerce route (/v1/store/...) still gets commerce's envelope. Mirrors the frozen
// order: kms (before commerce) → commerce /v1 group chain → projects + store (after).
// Regression for the release-smoke failure where 14 post-commerce endpoints 500'd.
func TestCommerceErrorScope(t *testing.T) {
app := zip.New(zip.Config{})
// kms (before commerce) — a clean 403 baseline (never wrapped by commerce).
app.Get("/v1/kms/health", func(c *zip.Ctx) error { return zip.ErrForbidden("kms says no") })
// commerce (position 39): the REAL group chain, now with the scoped envelope.
sv1 := app.Group("/v1")
sv1.Use(commercemid.AddHost(), commercemid.RequestContext(), commerceErrorScope())
// projects (after commerce) — typed 403; must NOT be clobbered to 500.
app.Get("/v1/projects", func(c *zip.Ctx) error { return zip.ErrForbidden("X-Org-Id required") })
// a commerce store route (after commerce) — typed 403; commerce envelope applies.
app.Get("/v1/store/current", func(c *zip.Ctx) error { return zip.ErrForbidden("store needs org") })
probe := func(path string) (int, string) {
req := httptest.NewRequest("GET", path, nil)
resp, err := app.Fiber().Test(req)
if err != nil {
t.Fatalf("%s: %v", path, err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
// The invariant the scope guards: a typed zip.HTTPError (403) a subsystem returns
// is NEVER flattened to a 500 — not before commerce, not after it. (commerce
// >=1.48.10 honors the status itself; the scope keeps commerce's error handler off
// other subsystems' routes regardless, so a future commerce regression can't
// re-clobber them.)
for _, tc := range []struct {
path string
wantCode int
}{
{"/v1/kms/health", 403}, // before commerce
{"/v1/projects", 403}, // after commerce — must NOT be clobbered to 500
{"/v1/store/current", 403}, // commerce's own route — its handler still honors 403
} {
code, body := probe(tc.path)
t.Logf("%-20s -> %d %s", tc.path, code, body)
if code != tc.wantCode {
t.Errorf("%s: got %d, want %d (%s)", tc.path, code, tc.wantCode, body)
}
if strings.Contains(body, "\"status\":5") || code >= 500 {
t.Errorf("%s: a typed 403 was flattened to a 5xx (%s)", tc.path, body)
}
}
for _, p := range []struct {
path string
own bool
}{
{"/v1/store/current", true},
{"/v1/commerce/checkout", true},
{"/v1/projects", false},
{"/v1/agent/presets", false},
{"/v1/agents", false},
} {
if got := hasCommercePrefix(p.path); got != p.own {
t.Errorf("hasCommercePrefix(%q) = %v, want %v", p.path, got, p.own)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
// Copyright © 2026 Hanzo AI. MIT License.
package apps
import (
"io"
"net/http"
"net/http/httptest"
"testing"
luxlog "github.com/luxfi/log"
"github.com/zap-proto/zip"
)
// TestCommercePrefixesPinned pins the wire paths that MUST reach the commerce gin
// handler — the ones a missing prefix silently regresses because they otherwise
// fall through to another owner (the account-bridge /v1/billing/* catch-all, or
// the bare /v1/* AI catch-all) that answers with the wrong contract:
//
// - /v1/billing/webhooks provider HMAC is the auth (Square et al); the
// session-gated bridge would 403 it.
// - /v1/billing/auto-recharge the durable cron's billing-autorecharge poke
// (COMMERCE_SERVICE_TOKEN bearer); without the prefix the poke 403s at the
// bridge ("sign in to view billing") — exactly how the first live fires
// failed, and how the commerce unfork regressed it once already.
// - /v1/store the bare storefront surface (GET /v1/store/current +
// the listing upsert/reads). Dropped by the unfork, it matched no owner and fell
// to the /v1/* AI balance gate, which 402'd every store read for a commerce-funded
// org (the karma /v1/store/current outage). It is metadata, never LLM inference.
func TestCommercePrefixesPinned(t *testing.T) {
want := map[string]bool{
"/v1/billing/auto-recharge": false,
"/v1/billing/webhooks": false,
"/v1/store": false,
}
for _, p := range commercePrefixes {
if _, ok := want[p]; ok {
want[p] = true
}
}
for p, ok := range want {
if !ok {
t.Errorf("commercePrefixes missing %q — the route falls through to the wrong owner", p)
}
}
}
// TestStoreSurfaceRoutedToCommerceNotAIGate is the regression guard for the karma
// GET /v1/store/current → 402 outage. Because "/v1/store" is a commercePrefix, a
// store read is mounted on the commerce handler AHEAD of the bare /v1/* AI catch-all
// (Wire order: commerce@191 < ai@321; Fiber matches first-registered), so it resolves
// on commerce and NEVER reaches the LLM prepaid-balance gate that denied every store
// read for an org funded in commerce but $0 in the ai ledger.
func TestStoreSurfaceRoutedToCommerceNotAIGate(t *testing.T) {
app := zip.New(zip.Config{Logger: luxlog.New("test")})
// Mirror mountCommerce EXACTLY: app.All(prefix+"/*", handler) for each commerce
// prefix. The stub stands in for the embedded commerce gin handler that serves
// getCurrent (200 with the org's store).
commerce := zip.AdaptNetHTTP(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"store":{"id":"karma-store"}}`)
}))
for _, p := range commercePrefixes {
app.All(p+"/*", commerce)
}
// The bare /v1/* AI catch-all, mounted LAST like the real Wire, gates every
// non-exempt /v1/* path on the caller's LLM prepaid balance → 402 for a
// commerce-funded-but-ai-$0 org. This is the exact gate that produced the outage.
app.Get("/v1/*", func(c *zip.Ctx) error {
return c.JSON(http.StatusPaymentRequired, map[string]any{
"error": map[string]string{"code": "insufficient_balance"},
})
})
// The store read must resolve on the commerce handler (200), never 402 at the AI gate.
code, body := doReq(t, app, http.MethodGet, "/v1/store/current")
if code != http.StatusOK {
t.Fatalf("GET /v1/store/current hit the AI balance gate (got %d, body %s) — /v1/store must be a commercePrefix so it reaches commerce, not the /v1/* catch-all", code, body)
}
// And a sibling store path (the listing upsert the publish edge writes) is owned too.
if code, _ := doReq(t, app, http.MethodPut, "/v1/store/karma-store/listing/valentina"); code == http.StatusPaymentRequired {
t.Fatalf("PUT /v1/store/:id/listing/:slug fell through to the AI balance gate (402) — the whole store surface must be commerce-owned")
}
}
// doReq drives one request through the mounted app and returns (status, body).
func doReq(t *testing.T, app *zip.App, method, path string) (int, []byte) {
t.Helper()
resp, err := app.Fiber().Test(httptest.NewRequest(method, path, nil))
if err != nil {
t.Fatalf("Test %s %s: %v", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
+33
View File
@@ -0,0 +1,33 @@
package apps
import (
"testing"
"github.com/hanzoai/cloud/clients/framework"
)
// TestFrameworkContentModulesLinked guards the framework CONTENT modules
// (cms/erp/help) against silent removal. They are not mount subsystems, so they
// never appear in Wire(); they register their DocTypes and — for erp — the
// ledger-posting lifecycle hooks into the framework engine from a package
// init(), reached ONLY via the blank imports in apps.go. #248 dropped
// those imports, which stripped the erp ledger hooks from the binary with no
// mount change and no failing mount test. This asserts the engine's module
// registry carries each lane, so that money-adjacent regression cannot recur.
func TestFrameworkContentModulesLinked(t *testing.T) {
got := make(map[string]bool)
for _, m := range framework.RegisteredModules() {
got[m] = true
}
for _, want := range []string{"cms", "erp", "help"} {
if !got[want] {
t.Errorf("framework content module %q not registered — a blank import in apps.go is missing (erp drop = ledger hooks gone from the binary)", want)
}
}
// The module registry proves DocTypes are linked, but erp's ledger-posting
// HOOKS register in a separate init() step; assert them directly so the guard
// survives a future split of registerHooks() out of erp's module init().
if framework.RegisteredHookCount() == 0 {
t.Error("no framework lifecycle hooks registered — erp's ledger-posting hooks (computeJournalTotals, journalEntry/paymentEntry submit+cancel, …) are not linked into the binary")
}
}
+81
View File
@@ -0,0 +1,81 @@
// Copyright © 2026 Hanzo AI. MIT License.
package apps
import (
"context"
"fmt"
"github.com/hanzoai/cloud/clients/finance"
"github.com/hanzoai/cloud/clients/money"
"github.com/hanzoai/cloud/types"
"github.com/hanzoai/commerce/billing/creditledger"
)
// ledger implements commerce's creditledger.CreditLedger over cloud's native
// finance ledger — the SAME per-org account (finance.Current()) the AI spend-gate
// reads and the edge meter debits. Injected at mountCommerce (EmbedConfig.Ledger),
// it makes commerce's POST /v1/billing/credit mint into the ONE ledger: a granted
// credit is immediately visible to the gate (one ledger, no split). This is the
// cloud half of the one-ledger seam — commerce defines the interface, cloud
// implements it once here, the compiler enforces the match.
//
// Fails closed when no finance ledger is co-resident; in the unified cloud binary
// finance is always published, so Get() != nil ⇒ credit routes here.
type ledger struct{}
// compile-time proof the adapter satisfies commerce's exported seam.
var _ creditledger.CreditLedger = ledger{}
// Credit posts a balanced deposit (funding:platform → wallet) to the org's POOL
// account (Subject == Org, the wallet the gate reads) and returns the ledger entry
// id + the org's new available balance in cents. Idempotent on IdempotencyKey:
// finance dedups on Ref, so the same key credits AT MOST once.
func (ledger) Credit(ctx context.Context, in creditledger.CreditInput) (string, int64, error) {
fin := finance.Current()
if fin == nil {
return "", 0, fmt.Errorf("commerce credit: no finance ledger co-resident")
}
cur := in.Currency
if cur == "" {
cur = "usd"
}
tag := in.Tag
if tag == "" {
tag = "grant:admin" // non-cash grant bucket (finance is a single wallet; Tags is a memo)
}
id, err := fin.Deposit(ctx, types.DepositInput{
Org: in.Org,
Subject: in.Org, // org-pool wallet == the account the AI gate reads
Amount: money.FromCents(in.AmountCents),
Currency: cur,
Notes: in.Reason,
Tags: tag,
Ref: in.IdempotencyKey,
})
if err != nil {
return "", 0, err
}
bal, berr := fin.Balance(ctx, in.Org, in.Org, cur, false)
if berr != nil {
return id, 0, berr
}
return id, bal.Cents(), nil
}
// Balance returns the org pool's available balance in cents for currency — the
// same read the AI gate performs, so GET /v1/billing/balance and the gate agree.
func (ledger) Balance(ctx context.Context, org, currency string) (int64, error) {
fin := finance.Current()
if fin == nil {
return 0, fmt.Errorf("commerce balance: no finance ledger co-resident")
}
if currency == "" {
currency = "usd"
}
bal, err := fin.Balance(ctx, org, org, currency, false)
if err != nil {
return 0, err
}
return bal.Cents(), nil
}
+23
View File
@@ -0,0 +1,23 @@
package apps
import (
"github.com/hanzoai/cloud/clients/coding"
"github.com/hanzoai/cloud/clients/git"
"github.com/hanzoai/cloud/clients/integrations"
)
// wire_seams.go wires cross-subsystem in-process seams that cannot be a MountSpec
// because they compose functions ACROSS packages that must not import each other.
//
// The coding orchestrator (clients/coding) needs git's CloneURL + VerifyRef, but
// clients/git imports clients/integrations (Slack-notify), and integrations calls
// coding — so coding -> git would cycle (integrations -> coding -> git ->
// integrations). The composition root is the ONE place that imports all three, so
// it assembles the coding Dispatcher here (git seams + agents/tracker/bot adapters)
// and injects it into the Slack trigger surface. init() runs once at load, before
// cloud.Serve; the git functions are plain reads that resolve their state at call
// time, so no mount ordering is required. The mirror-failure logger is nil (those
// failures are non-fatal and dropped).
func init() {
integrations.SetCodingDispatcher(coding.NewDispatcher(git.CloneURL, git.VerifyRef, nil))
}
+152
View File
@@ -0,0 +1,152 @@
package apps
import "testing"
// frozen is the EXACT subsystem mount sequence of the PRE-refactor binary —
// name, OwnsHealth, and whether it has a Shutdown — one row per mounted spec, in
// mount order. It was captured empirically from the pre-refactor cloud binary by
// cmd/dumpregistry (a throwaway tool that blank-imported the old init()-registry
// and replayed the legacy MountAll bubble-sort: ascending order-int, ties broken by
// the non-stable sort over init-registration order). The "was order N" trailing
// comment records each spec's deleted order-int for provenance.
//
// This is the SOLE guardian of mount order now that the order-ints are gone:
// Wire() must reproduce this sequence byte-for-byte (the func pointers aside), so a
// reorder, drop, add, or flag change in the composition root fails HERE. Captured on
// origin/main @c504d2b: 68 specs from the live init()-registry, PLUS the two the
// wave-2 external bumps (ai v1.805.2, o11y v1.5.12) stopped self-registering — ai
// (@150 catch-all) and the hanzoai/o11y module wildcard (@70), which main currently
// DROPS and this PR restores. The module wildcard (order 70) is now folded in as the
// terminal sub-mount of the in-repo o11y read plane (order 69), so "o11y" is ONE spec.
var frozen = []struct {
name string
ownsHealth bool
hasShutdown bool
}{
{"pubsub", false, true}, // was order 5
{"kafka", false, true}, // was order 6
{"agentskills", false, false}, // was order 8
{"flags", true, true}, // was order 9; native engine: /v1/flags health + store shutdown
{"kms", true, false}, // was order 10
{"metrics", false, false}, // was order 40
{"ingress", false, true}, // was order 42
{"account", false, false}, // was order 48
{"iam", false, false}, // was order 50
{"base", true, true}, // was order 60; per-org embed added Shutdown (#298)
{"o11y", false, true}, // ONE observability subsystem (was co-owned orders 69+70): read plane + the hanzoai/o11y module wildcard folded in as MountO11y's terminal sub-mount. OwnsHealth=false keeps /v1/o11y/health the generic always-ok route the module co-entry used to trigger.
{"authz", false, false}, // was order 70
{"commerce", false, false}, // was order 100
{"licensing", false, false}, // was order 110
{"plans", true, false}, // was order 111
{"pricing", true, false}, // was order 112
{"storage", true, false}, // was order 118
{"provisioning", false, false}, // was order 120
{"billing", false, false}, // was order 121
{"account-bridge", false, false}, // was order 122
{"do", false, false}, // was order 123
{"platform", true, false}, // was order 124
{"projects", false, false}, // was order 125
{"prompts", false, false}, // was order 126
{"agents", false, true}, // was order 127
{"link", false, true}, // new: unified AI login manager (/v1/links), after agents
{"wallets", false, true}, // was order 127
{"x402", false, true}, // new: x402 pay-per-use settlement (after wallets)
{"paas", true, false}, // was order 128
{"deploy", true, false}, // after paas (release seam), before functions
{"functions", false, false}, // was order 128
{"tracker", false, false}, // was order 129
{"templates", false, false}, // was order 129
{"framework", false, true}, // was order 129
{"knowledge", false, false}, // was order 130
{"content", false, true}, // new: marketing content loop (after knowledge)
{"catalogsync", false, true}, // new: reverse loop (product.created → render) after content
{"ml", true, false}, // was order 130
{"usage", false, false}, // was order 131
{"crm", false, false}, // was order 131
{"marketing", false, true}, // new: marketing domain fold (after crm)
{"ads", false, true}, // new: ads domain fold (after crm)
{"social", false, true}, // new: /v1/social fold (after crm)
{"analytics", true, false}, // was order 132
{"git", false, false}, // was order 132
{"sync", false, true}, // /v1/sync engine (owns per-org DB handles → Shutdown)
{"visor", false, false}, // was order 133
{"captable", false, true}, // was order 133
{"code", false, true}, // was order 134
{"zero-trust", false, false}, // was order 134
{"dataroom", true, true}, // was order 134
{"graph", false, false}, // was order 135
{"security", true, true}, // was order 136
{"integrations", false, true}, // was order 137
{"sbom", true, false}, // was order 137
{"team", false, true}, // was order 138
{"settings", false, true}, // was order 138
{"notify", true, false}, // was order 139
{"gateway", false, false}, // was order 139
{"entitlements", false, true}, // was order 139
{"exec", false, false}, // was order 140
{"websearch", false, false}, // was order 141
{"world", false, true}, // was order 142
{"runtime", false, false}, // was order 143; was "bot" until the transport was named for what it is
{"authors", false, true}, // was order 143
{"bots", false, false}, // was order 143
{"audit", false, false}, // was order 144
{"affiliates", false, false}, // was order 144
{"sign", true, true}, // was order 145
{"product", false, false}, // was order 145
{"evals", false, false}, // was order 145
{"treasury", false, true}, // was order 146
{"admin", false, false}, // was order 146
{"tasks", false, false}, // was order 147
{"cron", false, false}, // durable platform cron on the shared engine (post-freeze add)
{"automations", false, true}, // was order 148
{"connectorruntime", false, false}, // new: native single-connector exec via goja (after automations, HIP-0126)
{"tools", false, true}, // new: unified tool plane (after automations)
{"marketplace", false, true}, // new: marketplace over the tool plane (after tools)
{"referrals", false, false}, // was order 149
{"guide", false, true}, // new: Business AI Guide (after referrals, before ai)
{"company", false, true}, // new: Hanzo Company formation state machine (after guide)
{"agent", false, false}, // new: /v1/agent tool-calling round (before zen/ai catch-all)
{"zen", false, false}, // zen* claim middleware before ai's catch-all (hip-00NN)
{"ai", false, false}, // was order 150
{"plugins", false, false}, // was order 900
}
// TestWireOrderMatchesFrozen proves the composition root's mount order is
// byte-identical to the legacy init()-registry's, position by position.
func TestWireOrderMatchesFrozen(t *testing.T) {
wire := Wire()
if len(wire) != len(frozen) {
t.Fatalf("Wire() has %d specs, frozen sequence has %d", len(wire), len(frozen))
}
for i, s := range wire {
w := frozen[i]
if s.Name != w.name {
t.Errorf("position %d: Wire() = %q, frozen = %q (mount ORDER changed)", i, s.Name, w.name)
}
if s.OwnsHealth != w.ownsHealth {
t.Errorf("position %d (%s): OwnsHealth = %v, frozen = %v", i, s.Name, s.OwnsHealth, w.ownsHealth)
}
if (s.Shutdown != nil) != w.hasShutdown {
t.Errorf("position %d (%s): hasShutdown = %v, frozen = %v", i, s.Name, s.Shutdown != nil, w.hasShutdown)
}
if s.Mount == nil {
t.Errorf("position %d (%s): Mount is nil", i, s.Name)
}
}
}
// TestWireNoDuplicateEnablement guards that every subsystem name is unique: a name
// maps 1:1 to an enable id, so a duplicate would mount two specs under one id. (The
// former o11y co-ownership was collapsed — the module wildcard is now a sub-mount of
// the in-repo o11y read plane — so there is no longer any exempt duplicate.)
func TestWireNoDuplicateEnablement(t *testing.T) {
seen := map[string]int{}
for _, s := range Wire() {
seen[s.Name]++
}
for name, n := range seen {
if n > 1 {
t.Errorf("subsystem %q wired %d times (each enable id must be unique)", name, n)
}
}
}
+304
View File
@@ -0,0 +1,304 @@
// Copyright 2026 Hanzo AI Inc. All Rights Reserved.
package apps
import (
"context"
"fmt"
"math/big"
"os"
"strings"
aicontrollers "github.com/hanzoai/ai/controllers"
aiobject "github.com/hanzoai/ai/object"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients/metering"
cloudmoney "github.com/hanzoai/cloud/clients/money"
"github.com/hanzoai/cloud/clients/principal"
hmoney "github.com/hanzoai/money"
"github.com/hanzoai/zen"
"github.com/zap-proto/zip"
)
// mountZen mounts zen co-resident in the unified cloud binary. zen is the ONE
// serving layer for the zen model family; it owns identity, routing, the 1M
// context ladder, vision, tools, and the Anthropic↔OpenAI codec. ai stays the
// auth+billing+discovery seam and the /v1/models authority; it no longer carries
// a parallel zen table or identity prompts. (See hip-00NN.)
//
// zen mounts as a MIDDLEWARE, not a route owner: Claim is scoped to /v1/* and
// routes every request whose model is a zen SKU to zen's pipeline in-process,
// calling c.Next() for everything else so ai's /v1/* catch-all serves non-zen
// models. ONE mount mechanism; the host owns the routes, zen owns the family.
//
// Billing. cloud's edge middleware (serve.go) runs IdentityMiddleware,
// AuditTrail, ScopeRateLimit, and BillingGate app-wide BEFORE MountAll, so a
// zen-claimed request is already authenticated, audited, and rate-limited at the
// edge. But the edge BillingGate prices bare /v1/messages, /v1/chat/completions,
// and /v1/embeddings at 0 (they are not under /v1/ai/ in selfMeteredPrefixes), and
// ai's OWN in-handler metering — which used to bill zen* — is SKIPPED because
// zen's Claim runs before ai's beego catch-all. zen therefore bills zen* itself,
// through the same commerce metering client the edge gate uses, so there is ONE
// billing source for zen* (never double-billed, never free): zen's Gate
// authorizes the estimate before the upstream call, zen's Meter records the
// exact served cost after. zen's Meter/Gate are wired here; ai's edge gate stays
// 0 for these paths.
//
// Billing granularity is org / project / user, mirroring the edge gate's
// identityFromCtx exactly:
// - the HOME org (principal.BillingOrg) is the balance key — who PAYS. An admin
// acting in another org bills the admin's home org, never the org acted on.
// - the project (principal.ValidatedProject) scopes spend caps; a project may
// carry its own billing account, resolved server-side by commerce from the
// org's project binding (the X-Billing-Account-Id header only attributes,
// never redirects spend). Empty is the org-wide default.
// - the user (c.User) is the actor for the audit trail.
//
// It is wired BEFORE ai in Wire() so Claim's c.Next() falls through to ai's
// catch-all. zen's catalog reads its upstream keys from KMS via the Key resolver.
func mountZen(a *zip.App, deps cloud.Deps) error {
z, err := zen.New(zen.Config{
Logger: deps.Logger,
Key: zenKeyResolver(deps.KMS),
Tenant: cloudTenantResolver,
Gate: commerceGate(deps.Metering),
Meter: commerceMeter(deps.Metering),
})
if err != nil {
return fmt.Errorf("zen: %w", err)
}
// The one mount: Claim scoped to /v1, ahead of ai's catch-all.
a.Group("/v1", z.Claim())
return nil
}
// cloudTenantResolver is the multi-tenant billing-identity resolver: it keys
// the balance on the validated HOME org (who pays), resolves the project scope
// from a validated claim, and attributes the user. It mirrors the edge gate's
// identityFromCtx so a zen* debit lands on the SAME ledger axes the edge gate
// would have used — home-org balance, project+service scope, user actor — and a
// masquerading admin bills their own home org, never the org acted on. A request
// with no validated principal resolves to an empty Tenant, which zen's Valid()
// gate refuses (no free, anonymous usage).
func cloudTenantResolver(c *zip.Ctx) zen.Tenant {
home, _ := principal.BillingOrg(c)
project, _ := principal.ValidatedProject(c)
return zen.Tenant{
Org: c.Org(),
User: c.User(),
BillingOrg: home,
Project: project,
}
}
// commerceGate is zen's pre-serve authorization backed by cloud commerce. It
// asks the metering client whether the home org can cover the request's
// estimated cost (priced at the tier that WILL serve, so an overflow is gated
// against its real cost). The balance key is the home org (User); the project
// scopes the spend cap. The estimate is exact 18-dp atto-USD from zen, folded to
// whole cents for the balance check (a sub-cent estimate gates as "any positive
// balance", the same contract as the edge gate's AmountCents). An unconfigured
// metering client (nil) admits everything — zen's own tenant gate still refuses
// anonymous traffic, and the edge BillingGate + ScopeRateLimit already ran. A
// denied verdict returns the metering reason so zen surfaces it as its 402.
func commerceGate(m *metering.Client) zen.Gate {
if m == nil || !m.Enabled() {
return nil
}
return func(ctx context.Context, t zen.Tenant, model string, est hmoney.Amount) error {
if t.BillingOrg == "" {
return fmt.Errorf("a billable tenant is required (no anonymous usage)")
}
// zen's estimate is an exact 18-dp USD value. Fold it to whole cents for
// the balance check via cloud's typed money.Amount.Cents() — a sub-cent
// estimate gates as 0 (any-positive-balance), matching the edge gate's
// AmountCents contract. The post-serve Meter debits the exact 18-dp.
//
// The fold is Cents() on the CREDIT amount, never Minor() on the zen one:
// Minor() renders money.USD's 2 decimals, so it returned cents that FromInt
// then read as atto — every estimate came back 0, and AuthorizeVerdict skips
// its `available >= AmountCents` check when AmountCents is 0, admitting a
// request of ANY size against any positive balance.
cents := credit(est).Cents()
v, err := m.AuthorizeVerdict(ctx, metering.AuthInput{
User: t.BillingOrg,
Org: t.BillingOrg,
AmountCents: cents,
Project: t.Project,
Service: zenService,
})
if err != nil {
// Balance unknown -> fail-closed (mirrors the edge gate's 503).
return fmt.Errorf("billing unavailable")
}
if !v.Allow {
if v.Reason == "spend_cap" {
return fmt.Errorf("spend cap reached for this scope")
}
return fmt.Errorf("insufficient balance")
}
return nil
}
}
// commerceMeter is zen's post-serve usage recorder backed by cloud commerce.
// It debits the home org for the EXACT served cost as a typed money.Amount
// (native 18-dp USD — the same precision the co-resident finance ledger holds),
// so an exact per-token cost is never floored to cents or micros. Attributed to
// the requested zen SKU with real token counts. The debit is detached (background
// context) so a client disconnect cannot cancel it and recording never blocks the
// reply — the same contract as the edge gate's post-request record. An
// unconfigured client is a no-op (zen's logMeter still ran as the default, so the
// audit trail is never empty).
func commerceMeter(m *metering.Client) zen.Meter {
if m == nil || !m.Enabled() {
return nil
}
return commerceMeterImpl{m}
}
type commerceMeterImpl struct{ m *metering.Client }
func (g commerceMeterImpl) Record(ctx context.Context, u zen.Usage) {
if u.Tenant.BillingOrg == "" {
return // never debit an unattributable request
}
// Beside the commerce debit, land the SAME warehouse row + gen_ai span every
// native ai path writes (TraceServedUsage = recordTrace WITHOUT recordUsage —
// the debit below is the one billing source, never doubled). zen knows its
// EXACT per-tier retail (Charge) and upstream COGS (Cost), so the row carries
// true margin (credit → nano). Without this, zen* traffic is
// warehouse/o11y-blind exactly where prod runs (the unified binary).
aicontrollers.TraceServedUsage(context.Background(), aicontrollers.ServedUsage{
Owner: u.Tenant.BillingOrg,
User: u.Tenant.User,
Model: u.Model,
Provider: zenProvider,
RequestID: u.RequestID,
Status: "success",
PromptTokens: u.PromptTokens,
CompletionTokens: u.CompletionTokens,
BilledNano: nano(credit(u.Charge)),
CostNano: nano(credit(u.Cost)),
})
// Detached: the request context is recycled once the handler returns, so a
// background context carries the debit to commerce without racing the reply.
usage := meterUsage(u)
go func() { _, _ = g.m.Record(context.Background(), usage) }()
// Enso learning ledger: the embedded zen mount serves the zen catalog in-process
// and never reaches ai's pipeToFamily, so ai's family-event writer never runs for
// zen traffic. Write the SAME RoutingEvent here (source="family") through the ONE
// shared writer, keyed on the client-visible response id (zen.Usage.ResponseID), so
// zen* calls land in the same ledger — stats, world, spark retrain, and /v1/feedback
// all read these rows. No prompt text; no shadow (zen.Usage carries no request
// text — that stays the auto/enso-proxy path's job). Fire-and-forget.
owner := u.Tenant.Org
if owner == "" {
owner = u.Tenant.BillingOrg
}
go aiobject.RecordFamilyRouting(aiobject.FamilyRoutingInput{
Owner: owner,
User: u.Tenant.User,
RequestedModel: u.Model,
RoutedModel: u.Upstream,
ResponseId: u.ResponseID,
PromptTokens: u.PromptTokens,
CompletionTokens: u.CompletionTokens,
CostCents: credit(u.Charge).Cents(),
RouterEndpoint: os.Getenv("ROUTER_ENDPOINT"),
})
}
// meterUsage projects a served zen.Usage onto the commerce debit. It is the ONE
// place the debit's amount is chosen, and it is pure — no ledger, no warehouse —
// so the money property is a unit test rather than an integration.
//
// The amount is the RETAIL Charge: what the caller pays. Cost is the upstream
// COGS we pay to serve the call; it is never the debit. It rides only the
// warehouse row (CostNano), where margin = Charge Cost stays exact. Debiting
// Cost would collect our own COGS and book zero margin on every zen call — and
// because the affiliate and OSS payout bases read this debit, it would fund
// their shares out of principal. This mirrors ai, whose debit is likewise the
// customer price (usageBilledCents), never its CostIn/CostOut COGS.
func meterUsage(u zen.Usage) metering.Usage {
return metering.Usage{
User: u.Tenant.BillingOrg,
Org: u.Tenant.BillingOrg,
Actor: u.Tenant.User,
Model: u.Model,
Provider: zenProvider,
Service: zenService,
Project: u.Tenant.Project,
PromptTokens: u.PromptTokens,
CompletionTokens: u.CompletionTokens,
TotalTokens: u.PromptTokens + u.CompletionTokens,
Amount: credit(u.Charge), // exact 18-dp USD, no floor
RequestID: u.RequestID,
Currency: "usd",
Status: "success",
}
}
// credit re-denominates a zen price into cloud's credit unit. It is the ONE
// conversion at this seam — every site below goes through it, so the unit is
// decided once rather than re-derived per call site.
//
// zen prices every SKU as an exact 18-dp value tagged money.USD (meter.go:
// money.New(<18-dp decimal>, money.USD)), and cloud's credit unit is the SAME USD
// value at 18-dp storage scale. So the conversion carries the exact decimal across
// and changes only the minor-unit convention: no rescale, no rounding, no factor.
// It is right by construction because the decimal is the value — the currency's
// Decimals is a rendering convention, not part of it.
//
// It must NEVER go through Amount.Minor(). money.USD declares 2 decimals, so
// Minor() rescales zen's 18-dp value to CENTS; feeding cents to the 18-dp
// FromInt understates the debit by 10^16 (a $17.376 charge debits $0.0000000000000017),
// and folds every sub-cent charge to a zero the ledger drops entirely.
func credit(a hmoney.Amount) cloudmoney.Amount { return cloudmoney.FromDecimal(a.Decimal()) }
// nano folds an exact credit Amount to nano-USD (1e-9) for the warehouse margin
// columns. It takes the typed Amount rather than a bare *big.Int so the unit is
// carried by the type: a cents integer is not a cloudmoney.Amount and can no
// longer be passed here. A single request's cost always fits int64 at nano.
func nano(a cloudmoney.Amount) int64 {
return new(big.Int).Div(a.Atto(), big.NewInt(1_000_000_000)).Int64()
}
// zenService is the commerce service axis zen* spend attributes to. zen serves
// the same LLM product ai does, so it shares ai's service label — a per-scope
// spend cap on "ai" binds both surfaces, and Observe reconciles them together.
const zenService = "ai"
// zenProvider is the metering provider label that marks a debit as zen-served
// (the LLM family zen owns) for internal cost reconciliation vs the raw upstream.
const zenProvider = "zen"
// zenKeyResolver is zen's upstream-credential resolver. zen's catalog names each
// provider's key by an env-var convention (DO_AI_API_KEY, ANTHROPIC_API_KEY, …);
// the resolver turns that name into a concrete secret. It reads the ENVIRONMENT
// FIRST, then falls back to KMS — the SAME order ai uses (object/kms.go: "the prod
// hot path resolves DO_AI_API_KEY from the env before any live KMS"). The operator
// injects these provider keys as env from the KMS-synced K8s secret
// (cloud-api-llm-keys), so the env is the live value; the embedded KMS store is a
// fallback that is not always seeded with the provider keys. Reading KMS-only made
// zen send an EMPTY key whenever the store lacked it, and the upstream (DO GenAI)
// answered 401 "Unable to authenticate you" — surfacing to the caller as a failed
// chat while ai (which reads env) worked. Env-first fixes that with one source of
// truth shared across both zen and ai. An empty result on both still returns "" so
// the upstream call fails fast (never silent free usage).
func zenKeyResolver(kms cloud.KMSClient) func(context.Context, string) string {
return func(ctx context.Context, envName string) string {
if v := strings.TrimSpace(os.Getenv(envName)); v != "" {
return v
}
if kms == nil {
return ""
}
b, err := kms.GetSecret(ctx, envName)
if err != nil || len(b) == 0 {
return ""
}
return string(b)
}
}
+305
View File
@@ -0,0 +1,305 @@
// Copyright 2026 Hanzo AI Inc. All Rights Reserved.
package apps
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"sync/atomic"
"testing"
"github.com/hanzoai/cloud/clients/metering"
cloudmoney "github.com/hanzoai/cloud/clients/money"
"github.com/hanzoai/decimal"
hmoney "github.com/hanzoai/money"
"github.com/hanzoai/zen"
)
// usd builds an exact USD amount from a decimal string, the way zen prices a
// call (18-dp native, never through float).
//
// The decimal here must be hanzoai/decimal, the one hmoney.New takes and the one
// zen prices with — not shopspring's identically-named type. Money has exactly one
// decimal; a second one that merely LOOKS like it is how a price silently becomes
// a different number.
func usd(t *testing.T, s string) hmoney.Amount {
t.Helper()
d, err := decimal.Parse(s)
if err != nil {
t.Fatalf("parse %q: %v", s, err)
}
return hmoney.New(d, hmoney.USD)
}
// zen5Usage is one served call at zen5's live rates: 1M in + 1M out, priced at
// the family's 3× margin (retail = cost × margin).
//
// in : cost 1.392 → retail 4.176
// out: cost 4.40 → retail 13.20
func zen5Usage(t *testing.T) zen.Usage {
t.Helper()
return zen.Usage{
Tenant: zen.Tenant{BillingOrg: "acme", User: "acme/alice", Project: "p1"},
Model: "zen5",
PromptTokens: 1_000_000,
CompletionTokens: 1_000_000,
Charge: usd(t, "17.376"), // 4.176 + 13.20 — what the caller pays
Cost: usd(t, "5.792"), // 1.392 + 4.40 — what we pay upstream
RequestID: "req-1",
}
}
// dollars is the EXPECTED money, built from a plain dollar literal through cloud's
// OWN ParseUSD — deliberately a DIFFERENT constructor than the code under test uses.
//
// That is what pins the UNIT. These tests once asserted meterUsage(u).Amount.Int()
// against u.Charge.Minor(): both sides re-derived the number through the same
// conversion, so the assertion only proved an integer round-tripped and was blind
// to what the integer MEANT. It passed while every zen debit was 10^16 too small.
// Comparing money to a known dollar amount cannot be blind that way: if the debit
// is off by any factor, it is not $17.376 and the test fails.
func dollars(t *testing.T, s string) cloudmoney.Amount {
t.Helper()
a, err := cloudmoney.ParseUSD(s)
if err != nil {
t.Fatalf("parse %q: %v", s, err)
}
return a
}
// The debit is the RETAIL Charge — what the caller pays — never the upstream
// COGS. This is the money property: it fails if the Amount is built from
// u.Cost. The tier is margin-bearing (retail != cost), so the two values are
// distinguishable and the assertion cannot pass by coincidence.
func TestMeterUsageDebitsRetailNotCost(t *testing.T) {
u := zen5Usage(t)
if u.Charge.Cmp(u.Cost) == 0 {
t.Fatal("fixture is not margin-bearing: retail == cost, so the test could not tell them apart")
}
got := meterUsage(u).Amount
// The known dollar value the fixture charges — a $17.376 call debits $17.376.
if want := dollars(t, "17.376"); got.Cmp(want) != 0 {
t.Errorf("debit = $%s, want the retail Charge $%s", got, want)
}
if cogs := dollars(t, "5.792"); got.Cmp(cogs) == 0 {
t.Errorf("debit = $%s, which is the upstream COGS — the caller must be billed retail, not our cost", got)
}
}
// At the family's 3× margin the debit is exactly 3× the COGS: we collect the
// full retail price, not the wholesale one. Debiting Cost would collect 1/3 —
// our own COGS — and book zero margin.
func TestMeterUsageCollectsTheFullMargin(t *testing.T) {
u := zen5Usage(t)
debit := meterUsage(u).Amount
// 3x the COGS in the SAME unit as the debit — $5.792 + $5.792 + $5.792.
// Summing the credit Amount keeps the comparison in exact dollars; the old
// version multiplied Cost.Minor() (cents, 579 after rounding away 5.792's
// third decimal) and compared it to a debit that was not cents at all.
cogs := dollars(t, "5.792")
thriceCOGS := cogs.Add(cogs).Add(cogs)
if debit.Cmp(thriceCOGS) != 0 {
t.Errorf("debit = $%s, want 3x COGS = $%s (retail = cost x margin, margin 3.0)", debit, thriceCOGS)
}
if want := dollars(t, "17.376"); debit.Cmp(want) != 0 {
t.Errorf("debit = $%s, want $%s", debit, want)
}
}
// The debit carries zen's exact 18-dp value with no floor: a sub-cent call must
// not round to zero on the way to the ledger.
func TestMeterUsageKeepsExactSubCentCharge(t *testing.T) {
u := zen5Usage(t)
u.Charge = usd(t, "0.004176") // 1k input tokens at 4.176/MTok — well under a cent
u.Cost = usd(t, "0.001392")
got := meterUsage(u).Amount
if want := dollars(t, "0.004176"); got.Cmp(want) != 0 {
t.Errorf("debit = $%s, want the exact sub-cent charge $%s", got, want)
}
// metering.Record drops a zero Amount before it ever reaches the ledger
// (`if !c.Enabled() || amt.IsZero() ... return nil`), so a floored sub-cent
// charge is not a small debit — it is NO DEBIT ROW, and the call is free.
if got.IsZero() {
t.Error("sub-cent charge floored to zero — Record drops a zero Amount, so the call is served free with no debit row")
}
}
// The unit trap this seam shipped with, pinned so it cannot come back. zen prices
// an exact 18-dp value but tags it money.USD, whose Currency declares 2 decimals —
// so Charge.Minor() renders CENTS, while cloudmoney.FromInt reads its argument as
// 18-dp. Composing them silently divides every debit by 10^16.
//
// The tests above already fail if credit() regresses to that composition; this one
// names WHY, and proves the two conversions are still distinguishable — an
// assertion that cannot tell right from wrong is worse than no assertion.
func TestCreditIsNotTheMinorUnit(t *testing.T) {
charge := usd(t, "17.376")
if got, want := credit(charge), dollars(t, "17.376"); got.Cmp(want) != 0 {
t.Fatalf("credit($17.376) = $%s, want $%s", got, want)
}
// The conversion that shipped, spelled out.
old := cloudmoney.FromAtto(charge.Minor())
if old.Cmp(credit(charge)) == 0 {
t.Fatal("FromInt(Minor()) agrees with credit() — the fixture can no longer tell the units apart, so these tests prove nothing")
}
if old.Cents() != 0 {
t.Errorf("FromInt(Minor()).Cents() = %d, want 0 — that this was ALWAYS 0 is what made the spend gate admit every request", old.Cents())
}
}
// The identity fields ride with the debit unchanged: the debit lands on the org
// that PAYS (BillingOrg), scoped to its project, with the actor for the audit
// trail.
func TestMeterUsageAttribution(t *testing.T) {
u := zen5Usage(t)
m := meterUsage(u)
for _, c := range []struct{ name, got, want string }{
{"User", m.User, "acme"},
{"Org", m.Org, "acme"},
{"Actor", m.Actor, "acme/alice"},
{"Project", m.Project, "p1"},
{"Model", m.Model, "zen5"},
{"Provider", m.Provider, zenProvider},
{"Service", m.Service, zenService},
{"Currency", m.Currency, "usd"},
} {
if c.got != c.want {
t.Errorf("%s = %q, want %q", c.name, c.got, c.want)
}
}
if m.TotalTokens != 2_000_000 {
t.Errorf("TotalTokens = %d, want 2000000", m.TotalTokens)
}
}
// The spend gate must REFUSE a request whose estimate exceeds the balance.
//
// This is the sharpest edge of the unit bug and the reason it is a security
// finding, not only a revenue one. AuthorizeVerdict gates size like this:
//
// funded := available > 0
// if in.AmountCents > 0 { funded = available >= in.AmountCents }
//
// The estimate reached it as FromInt(est.Minor()).Cents(), which is ALWAYS 0 —
// so the size branch was DEAD and every request rode `available > 0`. Any org
// with a single cent of balance could draw an unbounded call. The debits were
// dust too, so the balance never fell and the cap could never trip.
func TestCommerceGateRefusesAnOverCapRequest(t *testing.T) {
const availableCents = 500 // the org holds $5.00
var authorized atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/billing/balance":
_, _ = io.WriteString(w, `{"available":`+strconv.Itoa(availableCents)+`}`)
case "/v1/billing/spend-alerts/authorize":
authorized.Store(true)
_, _ = io.WriteString(w, `{"allow":true}`)
default:
_, _ = io.WriteString(w, `[]`)
}
}))
defer srv.Close()
m, err := metering.New(metering.Config{BaseURL: srv.URL, Token: "t", Org: "acme"})
if err != nil {
t.Fatal(err)
}
gate := commerceGate(m)
if gate == nil {
t.Fatal("gate is nil — the client must be enabled for this proof to mean anything")
}
tenant := zen.Tenant{BillingOrg: "acme", User: "acme/alice", Project: "p1"}
// $17.376 against a $5.00 balance: over cap, must be refused.
if err := gate(context.Background(), tenant, "zen5", usd(t, "17.376")); err == nil {
t.Error("gate ADMITTED a $17.376 request against a $5.00 balance — the estimate is reaching AuthorizeVerdict as 0 cents, so the size check never runs")
}
// The same balance must still admit a request it can actually cover, or the
// test would pass by refusing everything.
if err := gate(context.Background(), tenant, "zen5", usd(t, "1.00")); err != nil {
t.Errorf("gate refused an affordable $1.00 request against a $5.00 balance: %v", err)
}
if !authorized.Load() {
t.Error("the affordable request never reached the spend-cap authorize step")
}
}
// The estimate must reach the balance check as the RIGHT number of cents. The
// refusal test above proves the gate says no; this proves it says no for the
// right reason — that $17.376 is folded to 1738 cents, not to 0.
func TestCommerceGateFoldsTheEstimateToRealCents(t *testing.T) {
for _, c := range []struct {
charge string
want int64
}{
{"17.376", 1738}, // rounds half-away-from-zero at the cent
{"1000.00", 100000},
{"1.00", 100},
{"0.004176", 0}, // sub-cent gates as "any positive balance"
} {
if got := credit(usd(t, c.charge)).Cents(); got != c.want {
t.Errorf("$%s folds to %d cents, want %d", c.charge, got, c.want)
}
}
}
// A zero-value zen price must convert and fold without panicking. zen leaves
// Charge/Cost as the zero Amount for a free SKU, and that value carries the
// EMPTY currency code, not "USD" — so this also pins that credit() reads the
// decimal rather than dispatching on the currency. The old attoToNano guarded a
// nil *big.Int here; nano() needs no guard because decimal.Coef() returns a real
// zero big.Int, never nil, but the property is worth holding.
func TestCreditAndNanoHandleTheZeroPrice(t *testing.T) {
var free hmoney.Amount // zero value: no currency, no coefficient
got := credit(free)
if !got.IsZero() {
t.Errorf("credit(zero) = $%s, want $0", got)
}
if n := nano(got); n != 0 {
t.Errorf("nano(credit(zero)) = %d, want 0", n)
}
if c := got.Cents(); c != 0 {
t.Errorf("credit(zero).Cents() = %d, want 0", c)
}
// And a free call books no debit row, which is correct — nothing is owed.
u := zen5Usage(t)
u.Charge, u.Cost = free, free
if amt := meterUsage(u).Amount; !amt.IsZero() {
t.Errorf("free call debits $%s, want $0", amt)
}
}
// nano carries real money to the warehouse margin columns. It is the last place
// the unit could silently collapse: attoToNano(cents) divided a cents integer by
// 1e9 and produced 0 for every charge under $10,000,000.
func TestNanoFoldsCreditToRealNano(t *testing.T) {
for _, c := range []struct {
charge string
want int64
}{
{"17.376", 17_376_000_000},
{"5.792", 5_792_000_000},
{"0.004176", 4_176_000},
{"1000.00", 1_000_000_000_000},
} {
if got := nano(credit(usd(t, c.charge))); got != c.want {
t.Errorf("nano($%s) = %d, want %d", c.charge, got, c.want)
}
}
}
+50
View File
@@ -0,0 +1,50 @@
// Copyright 2026 The Hanzo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloud
import (
"os"
"testing"
)
// TestJWTAudiences_AcceptsAdminGuard is the operator-cockpit keystone. The
// admin.hanzo.ai forward-auth guard is the confidential client `hanzo-admin-guard`,
// so IAM mints its access tokens with aud=hanzo-admin-guard (each app's aud is its
// client_id). The guard forwards that bearer to cloud-api /v1/admin/*; the identity
// sanitizer only grants SuperAdmin (owner==adminOrg) to a VALIDATED principal, and
// validation enforces this audience allowlist. If hanzo-admin-guard is not accepted
// the token resolves anonymous and the SuperAdmin gate reads false -> 403, even
// though the token's owner IS admin. Pin the client_id into the baked default so the
// forwarded bearer validates.
func TestJWTAudiences_AcceptsAdminGuard(t *testing.T) {
os.Unsetenv("CLOUD_JWT_AUDIENCES")
os.Unsetenv("GATEWAY_ALLOWED_AUDIENCES")
has := func(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
if !has(defaultJWTAudiences, "hanzo-admin-guard") {
t.Fatalf("defaultJWTAudiences must include hanzo-admin-guard (the admin-cockpit guard client_id); got %v", defaultJWTAudiences)
}
if !has(jwtAudiencesFromEnv(), "hanzo-admin-guard") {
t.Fatalf("resolved JWT audiences must include hanzo-admin-guard; got %v", jwtAudiencesFromEnv())
}
}
+47
View File
@@ -0,0 +1,47 @@
// Copyright 2026 The Hanzo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloud
import (
"os"
"testing"
)
// TestJWTAudiences_AcceptsHanzoWorld pins the world.hanzo.ai OIDC client. IAM
// mints world's access tokens with aud=hanzo-world (each app's aud is its
// client_id). Those bearers hit cloud-api; the identity sanitizer only trusts a
// principal whose aud is in this allowlist. If hanzo-world is not accepted the
// token resolves anonymous and the analyst's api.hanzo.ai calls 401. Pin the
// client_id into the baked default so the forwarded bearer validates.
func TestJWTAudiences_AcceptsHanzoWorld(t *testing.T) {
os.Unsetenv("CLOUD_JWT_AUDIENCES")
os.Unsetenv("GATEWAY_ALLOWED_AUDIENCES")
has := func(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
if !has(defaultJWTAudiences, "hanzo-world") {
t.Fatalf("defaultJWTAudiences must include hanzo-world (the world.hanzo.ai client_id); got %v", defaultJWTAudiences)
}
if !has(jwtAudiencesFromEnv(), "hanzo-world") {
t.Fatalf("resolved JWT audiences must include hanzo-world; got %v", jwtAudiencesFromEnv())
}
}
+2 -2
View File
@@ -31,7 +31,7 @@ func openTemp(t *testing.T) (*Recorder, string) {
return rec, path
}
// sampleRecord is a representative security event (a global-admin org deletion).
// sampleRecord is a representative security event (a SuperAdmin org deletion).
func sampleRecord(action string) Record {
return Record{
Time: time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC),
@@ -41,7 +41,7 @@ func sampleRecord(action string) Record {
Auth: AuthContext{Method: "jwt", IsAdmin: true},
Outcome: Outcome{Result: "success", Status: 200},
SourceIP: "203.0.113.7",
UserAgent: "console2",
UserAgent: "console",
RequestID: "req-123",
Method: "DELETE",
Path: "/v1/admin/orgs/acme",
+13 -9
View File
@@ -18,15 +18,16 @@ import (
// and compared against the RFC3339Nano ts column lexicographically (RFC3339 is
// order-preserving as text, so a string range is a correct time range).
type Filter struct {
Org string // actor_org exact match (tenant scope)
Sub string // actor_sub exact match (a specific user)
Action string // action exact match
Resource string // res_type exact match
Result string // outcome result: success|deny|error
Since time.Time // ts >= Since (UTC)
Until time.Time // ts <= Until (UTC)
Limit int // max rows (default 100, cap 1000)
Offset int // pagination offset
Org string // actor_org exact match (tenant scope)
Sub string // actor_sub exact match (a specific user)
Action string // action exact match
Resource string // res_type exact match
ResourceID string // res_id exact match (a specific resource instance)
Result string // outcome result: success|deny|error
Since time.Time // ts >= Since (UTC)
Until time.Time // ts <= Until (UTC)
Limit int // max rows (default 100, cap 1000)
Offset int // pagination offset
}
// Query returns records matching f, newest first, and the total count matching
@@ -93,6 +94,9 @@ func (f Filter) build() (string, []any) {
if f.Resource != "" {
add("res_type = ?", f.Resource)
}
if f.ResourceID != "" {
add("res_id = ?", f.ResourceID)
}
if f.Result != "" {
add("result = ?", f.Result)
}
+3 -3
View File
@@ -54,9 +54,9 @@ type Resource struct {
}
// AuthContext records HOW the actor authenticated and what authority they held
// at decision time — the AC-* evidence (was this a global admin? by what
// at decision time — the AC-* evidence (was this a SuperAdmin? by what
// credential?). Method is "jwt" | "api-key" | "none". IsAdmin is the VALIDATED
// global-admin bit (owner == AdminOrg), never a raw X-User-IsAdmin.
// SuperAdmin bit (owner == AdminOrg), never a raw X-User-IsAdmin.
type AuthContext struct {
Method string `json:"method"`
IsAdmin bool `json:"isAdmin"`
@@ -65,7 +65,7 @@ type AuthContext struct {
// Outcome is the result of the action: whether it was allowed and what
// happened. Result is "success" | "deny" | "error". Status is the HTTP status.
// Reason is a short, non-sensitive explanation for a deny/error (e.g.
// "global admin required", "insufficient_balance") — never a secret, never a
// "SuperAdmin required", "insufficient_balance") — never a secret, never a
// raw upstream error body.
type Outcome struct {
Result string `json:"result"`
+107
View File
@@ -0,0 +1,107 @@
package audit
// Shareability probe (HA carve evidence, NOT a shipped feature).
//
// Proves the audit SQLite store is SHAREABLE by a read-only second opener while
// the single writer is live-appending — the exact reader/writer split the HA
// carve needs. A reader opened with ?mode=ro:
// - never takes the write lock, so it cannot contend with or corrupt the
// writer's serialized appends (no chain-head fork: the reader never appends),
// - sees the writer's committed records via the shared WAL (concurrent reads),
// - and on "promotion" a fresh RW open recovers the head from disk == the
// writer's last synchronously-persisted record (no gap, no fork).
//
// This is the audit-store analog of clients/kms TestReaderReadOnlyRoundTrip
// (which proves the same for the KMS ZapDB store). Run:
// CGO_ENABLED=0 GOWORK=off GOFLAGS=-mod=mod go test ./audit/ -run Shareability -v
import (
"context"
"database/sql"
"sync"
"testing"
"time"
_ "github.com/hanzoai/sqlite"
)
func TestShareability_ReaderSharesLiveWriterStore(t *testing.T) {
dir := t.TempDir()
path := dir + "/audit.db"
// Writer: the real serialized Recorder (WAL, MaxOpenConns(1)).
w, err := Open(path, nil)
if err != nil {
t.Fatalf("writer Open: %v", err)
}
defer w.Close()
const total = 200
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < total; i++ {
if _, err := w.Append(context.Background(), Record{Action: "POST /v1/probe"}); err != nil {
t.Errorf("append %d: %v", i, err)
return
}
time.Sleep(200 * time.Microsecond)
}
}()
// Reader: a SECOND, independent connection opened READ-ONLY against the SAME
// files while the writer appends. This is what a reader-role pod does.
ro, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
if err != nil {
t.Fatalf("reader Open(ro): %v", err)
}
defer ro.Close()
// Poll the reader's view of the head while the writer runs. It must (a) never
// error, (b) be monotonic, and (c) eventually observe the writer's records —
// concurrent cross-connection RO reads over a live WAL writer.
var lastSeen int64 = -1
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
var maxSeq sql.NullInt64
if err := ro.QueryRow(`SELECT MAX(seq) FROM audit_log`).Scan(&maxSeq); err != nil {
t.Fatalf("reader concurrent read failed (store NOT shareable): %v", err)
}
if maxSeq.Valid {
if maxSeq.Int64 < lastSeen {
t.Fatalf("reader head regressed %d -> %d (not monotonic)", lastSeen, maxSeq.Int64)
}
lastSeen = maxSeq.Int64
}
if lastSeen >= total-1 {
break
}
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
if lastSeen < total-1 {
t.Fatalf("reader never caught up: saw head %d, writer wrote %d", lastSeen, total-1)
}
// Writer chain is intact and complete AFTER concurrent reader activity.
gotCount, _ := w.Head()
if gotCount != total {
t.Fatalf("writer head count = %d, want %d", gotCount, total)
}
// "Promotion": a fresh RW opener (the reader taking over) recovers the head
// from disk == the writer's last synchronously-persisted record. No fork.
promoted, err := Open(path, nil)
if err != nil {
t.Fatalf("promotion RW re-open: %v", err)
}
defer promoted.Close()
pc, _ := promoted.Head()
if pc != total {
t.Fatalf("promoted writer recovered head %d, want %d (chain gap/fork)", pc, total)
}
t.Logf("SHAREABLE: reader observed %d records concurrently; writer chain=%d; promotion recovered head=%d",
lastSeen+1, gotCount, pc)
}
+7 -6
View File
@@ -2,7 +2,7 @@ package audit
// The append-only sink + the serialized Recorder that owns the hash-chain head.
//
// WHY SQLITE IS THE PRIMARY, DURABLE STORE (not ClickHouse). The chain is only
// WHY SQLITE IS THE PRIMARY, DURABLE STORE (not datastore). The chain is only
// tamper-EVIDENT if records are appended in a strict, gapless total order and
// each record's PrevHash is the immediately-preceding record's Hash. That demands
// a single serializing writer with a synchronous, read-your-write head. cloud's
@@ -14,8 +14,8 @@ package audit
// app issues no UPDATE/DELETE, and the hash-chain detects any out-of-band edit to
// the file. That is the compliance-grade primary control.
//
// THE CLICKHOUSE MIRROR IS A PROJECTION, NOT THE SOURCE OF TRUTH. The datastore
// (ClickHouse MergeTree — insert-only, mutation-rejected at parse time) is the
// THE DATASTORE MIRROR IS A PROJECTION, NOT THE SOURCE OF TRUTH. The datastore
// (datastore MergeTree — insert-only, mutation-rejected at parse time) is the
// fleet-wide OLAP mirror for long-retention, cross-deployment query. It is
// best-effort and asynchronous: a mirror outage must never block or fail an
// audited request, and the local chain remains the authority the verifier walks.
@@ -39,12 +39,13 @@ import (
// mattn+SQLCipher, encrypted at rest; !cgo → pure-Go modernc). Importing
// modernc directly instead would double-register "sqlite" under CGO and
// panic at init. Blank import registers the driver.
"github.com/hanzoai/cloud/cek"
_ "github.com/hanzoai/sqlite"
)
// Mirror is the optional OLAP projection sink (the datastore/ClickHouse). It is
// Mirror is the optional OLAP projection sink (the datastore/datastore). It is
// deliberately a tiny interface, not a concrete client, so the Recorder has no
// compile-time dependency on ClickHouse and tests can supply a fake. Append is
// compile-time dependency on datastore and tests can supply a fake. Append is
// called best-effort, asynchronously, off the request path.
type Mirror interface {
// Append writes one sealed record to the projection. A returned error is
@@ -111,7 +112,7 @@ type CheckpointFunc func(cp Checkpoint)
// the file lock — the same single-writer discipline pricing/provisioning use,
// here doubling as the chain's serialization guarantee.
func Open(path string, mirror Mirror) (*Recorder, error) {
db, err := sql.Open("sqlite", path)
db, err := cek.Open(path)
if err != nil {
return nil, fmt.Errorf("audit: open sqlite %q: %w", path, err)
}
+60
View File
@@ -0,0 +1,60 @@
package audit
import "time"
// Wire is the JSON shape of one audit record on the operator/console contract. It
// is cloud's OWN record projection — richer than the IAM record it supersedes: it
// carries the outcome, the validated auth context, and the hash-chain linkage
// (Hash/PrevHash) so a console can show tamper-evidence per row. The JSON tags ARE
// the contract; both the admin god-view (/v1/admin/audit) and the org-scoped trail
// (/v1/audit) serialize this ONE shape so a single console adapter reads either.
type Wire struct {
Seq uint64 `json:"seq"`
Time string `json:"time"`
Org string `json:"org"`
Sub string `json:"sub"`
Email string `json:"email,omitempty"`
Action string `json:"action"`
Resource string `json:"resource"`
ResourceID string `json:"resourceId,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Result string `json:"result"`
Status int `json:"status"`
Reason string `json:"reason,omitempty"`
SourceIP string `json:"sourceIp,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
RequestID string `json:"requestId,omitempty"`
IsAdmin bool `json:"isAdmin"`
Auth string `json:"authMethod,omitempty"`
Hash string `json:"hash"`
PrevHash string `json:"prevHash"`
}
// ToWire projects a stored Record onto the console wire shape. Time is emitted as
// RFC3339Nano (UTC) — the same nanosecond-precise, order-preserving format the ts
// column stores — so a client can sort/range on it verbatim.
func (r Record) ToWire() Wire {
return Wire{
Seq: r.Seq,
Time: r.Time.UTC().Format(time.RFC3339Nano),
Org: r.Actor.Org,
Sub: r.Actor.Sub,
Email: r.Actor.Email,
Action: r.Action,
Resource: r.Resource.Type,
ResourceID: r.Resource.ID,
Method: r.Method,
Path: r.Path,
Result: r.Outcome.Result,
Status: r.Outcome.Status,
Reason: r.Outcome.Reason,
SourceIP: r.SourceIP,
UserAgent: r.UserAgent,
RequestID: r.RequestID,
IsAdmin: r.Auth.IsAdmin,
Auth: r.Auth.Method,
Hash: r.Hash,
PrevHash: r.PrevHash,
}
}
+73
View File
@@ -0,0 +1,73 @@
package audit
import (
"context"
"testing"
"time"
)
func TestToWire_MapsEveryField(t *testing.T) {
r := Record{
Seq: 7,
Time: time.Date(2026, 7, 4, 12, 30, 0, 0, time.UTC),
Actor: Actor{Org: "maxpower", Sub: "dave", Email: "dave@maxpower.ai"},
Action: "machine.create",
Resource: Resource{Type: "machine", ID: "m-1"},
Auth: AuthContext{Method: "jwt", IsAdmin: true},
Outcome: Outcome{Result: "success", Status: 201, Reason: "ok"},
SourceIP: "1.2.3.4", UserAgent: "test-agent", RequestID: "req-1",
Method: "POST", Path: "/v1/machines",
PrevHash: "aa", Hash: "bb",
}
w := r.ToWire()
if w.Seq != 7 || w.Time != "2026-07-04T12:30:00Z" {
t.Fatalf("seq/time: %+v", w)
}
if w.Org != "maxpower" || w.Sub != "dave" || w.Email != "dave@maxpower.ai" {
t.Fatalf("actor: %+v", w)
}
if w.Action != "machine.create" || w.Resource != "machine" || w.ResourceID != "m-1" {
t.Fatalf("action/resource: %+v", w)
}
if w.Auth != "jwt" || !w.IsAdmin {
t.Fatalf("auth: %+v", w)
}
if w.Result != "success" || w.Status != 201 || w.Reason != "ok" {
t.Fatalf("outcome: %+v", w)
}
if w.Method != "POST" || w.Path != "/v1/machines" || w.SourceIP != "1.2.3.4" {
t.Fatalf("request: %+v", w)
}
if w.Hash != "bb" || w.PrevHash != "aa" {
t.Fatalf("chain: %+v", w)
}
}
func TestQuery_ResourceIDFilter(t *testing.T) {
rec, err := Open(":memory:", nil)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer func() { _ = rec.Close() }()
ctx := context.Background()
for _, id := range []string{"m-1", "m-1", "m-2"} {
if _, err := rec.Append(ctx, Record{
Actor: Actor{Org: "o"}, Action: "machine.op",
Resource: Resource{Type: "machine", ID: id}, Outcome: Outcome{Result: "success"},
}); err != nil {
t.Fatalf("append: %v", err)
}
}
rows, total, err := rec.Query(ctx, Filter{ResourceID: "m-1"})
if err != nil {
t.Fatalf("Query: %v", err)
}
if total != 2 || len(rows) != 2 {
t.Fatalf("resourceId filter: want 2 rows on m-1, got %d rows total %d", len(rows), total)
}
for _, r := range rows {
if r.Resource.ID != "m-1" {
t.Fatalf("filter leaked %q", r.Resource.ID)
}
}
}
+1 -1
View File
@@ -208,7 +208,7 @@ func actorFromCtx(c *zip.Ctx) audit.Actor {
// authFromCtx records HOW the caller authenticated and the VALIDATED admin bit.
// IsAdmin comes from c.IsAdmin() (the sanitized X-User-IsAdmin, true only for a
// verified global admin), never a raw header. Method is inferred from the
// verified SuperAdmin), never a raw header. Method is inferred from the
// presence/shape of a credential: an Authorization/X-Authorization bearer or a
// session cookie ⇒ "jwt" (or "api-key" for an opaque hk-/sk- token); none ⇒
// "none".
+3 -3
View File
@@ -52,7 +52,7 @@ func newAuditApp(t *testing.T) (*zip.App, *audit.Recorder) {
// security event and MUST be audited even though it is a GET.
app.Get("/v1/admin/orgs", func(c *zip.Ctx) error {
if !c.IsAdmin() {
return zip.ErrForbidden("global admin required")
return zip.ErrForbidden("SuperAdmin required")
}
return c.JSON(http.StatusOK, map[string]string{"ok": "true"})
})
@@ -65,7 +65,7 @@ func newAuditApp(t *testing.T) (*zip.App, *audit.Recorder) {
return app, rec
}
// asAdmin sets the sanitized identity headers a VALIDATED global admin would
// asAdmin sets the sanitized identity headers a VALIDATED SuperAdmin would
// carry after SanitizeIdentity (X-User-IsAdmin=true, org=admin).
func asAdmin(req *http.Request) {
req.Header.Set("X-User-Id", "z@hanzo.ai")
@@ -435,7 +435,7 @@ func TestScrubToken_RedReviewBypassClasses(t *testing.T) {
}
// Normal UAs must be byte-identical (no false scrub).
for _, ua := range []string{
"console2", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
"console", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
"curl/8.1.2", "Go-http-client/2.0",
} {
if got := scrubFreeText(ua); got != ua {
+37 -24
View File
@@ -1,15 +1,15 @@
package cloud
// The datastore (ClickHouse) OLAP mirror — a best-effort projection of the audit
// The datastore OLAP mirror — a best-effort projection of the audit
// trail for fleet-wide, long-retention, cross-deployment query. It implements
// audit.Mirror.
//
// The datastore is the natural OLAP audit sink: the table is a MergeTree, which
// is INSERT-ONLY by engine — ClickHouse rejects UPDATE/DELETE against it at parse
// is INSERT-ONLY by engine — datastore rejects UPDATE/DELETE against it at parse
// time ("MergeTree does not support mutations"), so the mirror is append-only at
// the storage layer, matching the local chain's discipline. We create the table
// idempotently on first connect (CREATE TABLE IF NOT EXISTS) and insert via the
// canonical clickhouse-go PrepareBatch → Append → Send idiom (the same the
// canonical datastore-go PrepareBatch → Append → Send idiom (the same the
// provisioning subsystem uses; the driver is already in cloud's module graph, so
// this adds no dependency).
//
@@ -26,14 +26,14 @@ import (
"strings"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go/v2"
datastore "github.com/hanzo-ds/go"
"github.com/hanzoai/cloud/audit"
luxlog "github.com/luxfi/log"
)
// clickhouseMirror writes audit records to a ClickHouse MergeTree table.
type clickhouseMirror struct {
conn clickhouse.Conn
// datastoreMirror writes audit records to a datastore MergeTree table.
type datastoreMirror struct {
conn datastore.Conn
table string
log luxlog.Logger
}
@@ -44,25 +44,38 @@ type clickhouseMirror struct {
//
// Config (all from env / KMS-injected secrets, never hard-coded):
//
// CLOUD_AUDIT_CLICKHOUSE_ADDR host:9000 of the datastore native port
// CLOUD_AUDIT_CLICKHOUSE_DB database (default "hanzo")
// CLOUD_AUDIT_CLICKHOUSE_TABLE table (default "audit_log")
// CLOUD_AUDIT_CLICKHOUSE_USER user
// CLOUD_AUDIT_CLICKHOUSE_PASSWORD password (KMS-backed secret)
// CLOUD_AUDIT_DATASTORE_ADDR host:9000 of the datastore native port
// CLOUD_AUDIT_DATASTORE_DB database (default "hanzo")
// CLOUD_AUDIT_DATASTORE_TABLE table (default "audit_log")
// CLOUD_AUDIT_DATASTORE_USER user
// CLOUD_AUDIT_DATASTORE_PASSWORD password (KMS-backed secret)
//
// auditEnv reads CLOUD_AUDIT_DATASTORE_<suffix>; auditEnvOr adds a default when unset.
func auditEnv(suffix string) string {
return os.Getenv("CLOUD_AUDIT_DATASTORE_" + suffix)
}
func auditEnvOr(suffix, def string) string {
if v := auditEnv(suffix); v != "" {
return v
}
return def
}
func newAuditMirror(log luxlog.Logger) (audit.Mirror, error) {
addr := strings.TrimSpace(os.Getenv("CLOUD_AUDIT_CLICKHOUSE_ADDR"))
addr := strings.TrimSpace(auditEnv("ADDR"))
if addr == "" {
return nil, nil // no datastore configured — local chain only.
}
db := getenv("CLOUD_AUDIT_CLICKHOUSE_DB", "hanzo")
table := getenv("CLOUD_AUDIT_CLICKHOUSE_TABLE", "audit_log")
db := auditEnvOr("DB", "hanzo")
table := auditEnvOr("TABLE", "audit_log")
conn, err := clickhouse.Open(&clickhouse.Options{
conn, err := datastore.Open(&datastore.Options{
Addr: []string{addr},
Auth: clickhouse.Auth{
Auth: datastore.Auth{
Database: db,
Username: os.Getenv("CLOUD_AUDIT_CLICKHOUSE_USER"),
Password: os.Getenv("CLOUD_AUDIT_CLICKHOUSE_PASSWORD"),
Username: auditEnv("USER"),
Password: auditEnv("PASSWORD"),
},
DialTimeout: 5 * time.Second,
})
@@ -77,7 +90,7 @@ func newAuditMirror(log luxlog.Logger) (audit.Mirror, error) {
}
qualified := db + "." + table
m := &clickhouseMirror{conn: conn, table: qualified, log: log}
m := &datastoreMirror{conn: conn, table: qualified, log: log}
if err := m.ensureTable(ctx); err != nil {
_ = conn.Close()
return nil, err
@@ -92,7 +105,7 @@ func newAuditMirror(log luxlog.Logger) (audit.Mirror, error) {
// = insert-only (mutations rejected at parse time). Partitioned by month and
// ordered for the (org, time) query pattern; seq + hash are carried so the OLAP
// copy is cross-checkable against the local chain.
func (m *clickhouseMirror) ensureTable(ctx context.Context) error {
func (m *datastoreMirror) ensureTable(ctx context.Context) error {
ddl := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
seq UInt64,
@@ -130,7 +143,7 @@ ORDER BY (actor_org, ts, seq)`, m.table)
// still payload-bearing) diffs out of the fleet warehouse minimizes the blast
// radius of a warehouse compromise. The full record (with diffs) lives only in
// the local, access-controlled chain.
func (m *clickhouseMirror) Append(ctx context.Context, r audit.Record) error {
func (m *datastoreMirror) Append(ctx context.Context, r audit.Record) error {
batch, err := m.conn.PrepareBatch(ctx, "INSERT INTO "+m.table+` (
seq, ts, actor_org, actor_sub, actor_email, action, res_type, res_id,
auth_method, is_admin, result, status, reason, source_ip, user_agent,
@@ -159,7 +172,7 @@ func (m *clickhouseMirror) Append(ctx context.Context, r audit.Record) error {
// series and alerts on any regression. Best-effort; a failure is dropped by the
// Recorder (the structured log carries the same digest). Implements
// audit.CheckpointSink.
func (m *clickhouseMirror) Checkpoint(ctx context.Context, cp audit.Checkpoint) error {
func (m *datastoreMirror) Checkpoint(ctx context.Context, cp audit.Checkpoint) error {
if err := m.ensureCheckpointTable(ctx); err != nil {
return err
}
@@ -177,7 +190,7 @@ func (m *clickhouseMirror) Checkpoint(ctx context.Context, cp audit.Checkpoint)
// ensureCheckpointTable creates the append-only checkpoint digest table. A plain
// MergeTree ordered by time — the monitor reads the latest rows and checks that
// count never decreases.
func (m *clickhouseMirror) ensureCheckpointTable(ctx context.Context) error {
func (m *datastoreMirror) ensureCheckpointTable(ctx context.Context) error {
ddl := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s_checkpoints (
ts DateTime64(3, 'UTC'),
+16 -3
View File
@@ -15,6 +15,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/hanzoai/cloud/audit"
@@ -22,7 +23,7 @@ import (
)
// buildAuditRecorder constructs the audit Recorder from cfg: the append-only
// SQLite chain at {DataDir}/audit.db plus a best-effort ClickHouse OLAP mirror
// SQLite chain at {DataDir}/audit.db plus a best-effort datastore OLAP mirror
// when a datastore is configured. Returns (nil, nil) only when the trail is
// explicitly disabled — the caller then wires a no-op middleware.
func buildAuditRecorder(cfg *Config, logger luxlog.Logger) (*audit.Recorder, error) {
@@ -57,6 +58,18 @@ func buildAuditRecorder(cfg *Config, logger luxlog.Logger) (*audit.Recorder, err
return nil, fmt.Errorf("open audit store: %w", err)
}
// PER-SHARD audit under horizontal scale. The trail lives at {DataDir}/audit.db on
// THIS pod's own RWO PVC, so under shard routing each pod's chain covers ONLY the
// tenants routed to it (its shard) — and org-scoped audit queries route to the
// owning shard where those records live. Soundness: the chain is a per-FILE hash
// chain whose head is recovered at open; because no two pods share the file, there
// is no cross-pod head to fork (the very failure that pinned cloud to replicas:1 was
// two pods on ONE audit file). Integrity is preserved WITHIN each partition; a
// deployment-wide view is the union of the N per-shard chains. The shard id is
// stamped on the AU-9 checkpoint stream below so the external tail-truncation monitor
// tracks N heads (one per shard) rather than expecting a single global head.
shard := strings.TrimSpace(cfg.ShardSelf) // "" when single-pod — a harmless empty tag
// AU-9 tail-truncation anchor: emit a periodic head-digest checkpoint to the
// append-only observability log (and, when a mirror supports it, an
// independent digest store). An external o11y monitor compares consecutive
@@ -67,7 +80,7 @@ func buildAuditRecorder(cfg *Config, logger luxlog.Logger) (*audit.Recorder, err
if logger != nil {
rec.StartCheckpoints(interval, func(cp audit.Checkpoint) {
logger.Info("audit_head_checkpoint",
"count", cp.Count, "head", cp.Head, "ts", cp.Time.Format(time.RFC3339Nano))
"shard", shard, "count", cp.Count, "head", cp.Head, "ts", cp.Time.Format(time.RFC3339Nano))
})
} else {
rec.StartCheckpoints(interval, nil)
@@ -76,7 +89,7 @@ func buildAuditRecorder(cfg *Config, logger luxlog.Logger) (*audit.Recorder, err
if logger != nil {
count, head := rec.Head()
logger.Info("audit trail ready (tamper-evident, append-only)",
"store", dbPath, "records", count, "head", head,
"store", dbPath, "shard", shard, "records", count, "head", head,
"mirror", mirror != nil, "checkpoint_interval", interval.String())
}
return rec, nil
+173
View File
@@ -0,0 +1,173 @@
// Copyright 2026 Hanzo AI Inc. All Rights Reserved.
package cloud
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
)
// The identity boundary (SanitizeIdentity) validates a JWT and mints the identity
// headers every subsystem trusts. An opaque API key (hk-/sk-/pk-/fw_/hz_) is not a
// JWT, so it yielded no principal — and a subsystem that gates on the minted
// identity (zen's billing gate) refused an API-key request as anonymous, though the
// key is a first-class credential. keyResolver closes that gap: it turns a key into
// the SAME idClaims a JWT yields, so ONE minting path serves both credentials and
// key auth and session auth can never disagree on who a request is.
// keyResolver turns an opaque API key into the principal it authenticates, or nil
// for an unknown key or an unconfigured resolver (the request stays anonymous — a
// bad key never grants trust).
type keyResolver interface {
resolve(ctx context.Context, key string) *idClaims
}
// iamKeys resolves an `hk-` key against IAM's get-user?accessKey endpoint,
// authenticating as the confidential `hanzo-console` client (the credential
// clients/account already uses). The resolved user is exactly what a JWT for that
// user carries, so SanitizeIdentity mints identical headers for a key and a session.
// A brief cache keeps the hot auth path off the network; it caches misses too, so a
// bad key cannot hammer IAM.
type iamKeys struct {
base string
auth string // client_secret_basic, or "" when unconfigured
http *http.Client
cache cache[string, *idClaims]
}
// newIAMKeys reads the same IAM env clients/account does. With no confidential
// credential it returns a resolver that resolves nothing (keys stay anonymous —
// never a fabricated principal), so a deployment lacking the credential is safe.
func newIAMKeys() *iamKeys {
return &iamKeys{
base: iamHost(),
auth: iamCred(),
http: &http.Client{Timeout: 5 * time.Second},
cache: newCache[string, *idClaims](60 * time.Second),
}
}
// iamHost is the standalone IAM origin cloud talks to; iamCred is the service
// credential (client_secret_basic) it presents — the ONE IAM identity, shared by
// the API-key resolver here and the /v1/iam edge (iam_edge.go), so both
// authenticate to IAM the same way. Empty cred → a deployment lacking the
// credential stays safe (the caller treats "" as unconfigured).
func iamHost() string { return strings.TrimRight(env("IAM_URL", "IAM_INTERNAL_URL"), "/") }
func iamCred() string {
id := strings.TrimSpace(os.Getenv("IAM_MINT_CLIENT_ID"))
secret := strings.TrimSpace(os.Getenv("IAM_MINT_CLIENT_SECRET"))
if id == "" || secret == "" {
return ""
}
return "Basic " + base64.StdEncoding.EncodeToString([]byte(id+":"+secret))
}
func env(names ...string) string {
for _, n := range names {
if v := strings.TrimSpace(os.Getenv(n)); v != "" {
return v
}
}
return ""
}
func (k *iamKeys) resolve(ctx context.Context, key string) *idClaims {
if k.auth == "" || k.base == "" || key == "" {
return nil
}
if c, ok := k.cache.get(key); ok {
return c // may be a cached nil — a valid "anonymous" answer
}
c := k.lookup(ctx, key)
k.cache.put(key, c)
return c
}
// lookup performs the authenticated get-user?accessKey call and maps the user row
// to idClaims. Any failure (unreachable, denied, unknown key) yields nil. Name is
// both the username IAM's owner/name lookups parse and the id fallback: a key has
// no UUID subject, so userID() falls through to name — the gateway's historical
// X-User-Id==name behavior the owner/name path expects.
func (k *iamKeys) lookup(ctx context.Context, key string) *idClaims {
u := k.base + "/v1/iam/get-user?" + url.Values{"accessKey": {key}}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil
}
req.Header.Set("Authorization", k.auth)
req.Header.Set("Accept", "application/json")
resp, err := k.http.Do(req)
if err != nil {
return nil
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return nil
}
var env struct {
Status string `json:"status"`
Data *struct {
Owner string `json:"owner"`
Name string `json:"name"`
Email string `json:"email"`
IsAdmin bool `json:"isAdmin"`
} `json:"data"`
}
if json.Unmarshal(raw, &env) != nil || env.Status != "ok" || env.Data == nil {
return nil
}
if strings.TrimSpace(env.Data.Owner) == "" {
return nil
}
return &idClaims{
Owner: strings.TrimSpace(env.Data.Owner),
Name: strings.TrimSpace(env.Data.Name),
PreferredUsername: strings.TrimSpace(env.Data.Name),
Email: strings.TrimSpace(env.Data.Email),
IsAdmin: env.Data.IsAdmin,
}
}
// cache is a tiny concurrency-safe TTL map — one generic type for every
// resolve-once-reuse-briefly lookup, so no bespoke cache is hand-rolled per caller.
type cache[K comparable, V any] struct {
ttl time.Duration
mu sync.Mutex
m map[K]entry[V]
}
type entry[V any] struct {
v V
exp time.Time
}
func newCache[K comparable, V any](ttl time.Duration) cache[K, V] {
return cache[K, V]{ttl: ttl, m: make(map[K]entry[V])}
}
func (c *cache[K, V]) get(k K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.m[k]
if !ok || time.Now().After(e.exp) {
var zero V
return zero, false
}
return e.v, true
}
func (c *cache[K, V]) put(k K, v V) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[k] = entry[V]{v: v, exp: time.Now().Add(c.ttl)}
}
+86
View File
@@ -0,0 +1,86 @@
// Copyright 2026 Hanzo AI Inc. All Rights Reserved.
package cloud
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// iamKeys.lookup maps an IAM get-user?accessKey row to the SAME idClaims a JWT
// yields, so the one minting path serves a key and a session identically.
func TestIAMKeysLookup(t *testing.T) {
var gotKey, gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotKey = r.URL.Query().Get("accessKey")
gotAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"ok","data":{"owner":"hanzo","name":"z","email":"z@hanzo.ai","isAdmin":true}}`))
}))
defer srv.Close()
k := &iamKeys{base: srv.URL, auth: "Basic test", http: srv.Client(), cache: newCache[string, *idClaims](time.Minute)}
c := k.resolve(context.Background(), "hk-abc123")
if c == nil {
t.Fatal("resolve returned nil for a valid key")
}
if c.Owner != "hanzo" || c.Name != "z" || c.Email != "z@hanzo.ai" || !c.IsAdmin {
t.Fatalf("claims = %+v, want owner=hanzo name=z email=z@hanzo.ai isAdmin=true", c)
}
// The key is passed as accessKey and the confidential credential is sent.
if gotKey != "hk-abc123" {
t.Errorf("IAM got accessKey=%q, want hk-abc123", gotKey)
}
if gotAuth != "Basic test" {
t.Errorf("IAM got auth=%q, want the confidential Basic credential", gotAuth)
}
// userID falls through to name (a key has no UUID subject) — the owner/name
// path IAM's privileged lookups expect.
if c.userID() != "z" || c.username() != "z" {
t.Errorf("userID=%q username=%q, want both z", c.userID(), c.username())
}
}
// An unconfigured resolver (no confidential credential) resolves nothing, so an
// API key stays anonymous rather than mis-resolved.
func TestIAMKeysUnconfigured(t *testing.T) {
k := &iamKeys{base: "http://iam", auth: "", cache: newCache[string, *idClaims](time.Minute)}
if c := k.resolve(context.Background(), "hk-abc"); c != nil {
t.Fatalf("unconfigured resolver returned %+v, want nil", c)
}
}
// An unknown key (IAM status != ok) resolves to nil — a bad key never grants trust.
func TestIAMKeysUnknown(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"status":"error","msg":"Unauthorized operation"}`))
}))
defer srv.Close()
k := &iamKeys{base: srv.URL, auth: "Basic test", http: srv.Client(), cache: newCache[string, *idClaims](time.Minute)}
if c := k.resolve(context.Background(), "hk-bad"); c != nil {
t.Fatalf("unknown key resolved to %+v, want nil", c)
}
}
// The cache serves a resolved key without a second IAM call (and caches a miss too,
// so a bad key cannot hammer IAM).
func TestIAMKeysCache(t *testing.T) {
var calls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
_, _ = w.Write([]byte(`{"status":"ok","data":{"owner":"hanzo","name":"z"}}`))
}))
defer srv.Close()
k := &iamKeys{base: srv.URL, auth: "Basic test", http: srv.Client(), cache: newCache[string, *idClaims](time.Minute)}
for i := 0; i < 3; i++ {
if k.resolve(context.Background(), "hk-x") == nil {
t.Fatal("resolve nil")
}
}
if calls != 1 {
t.Fatalf("IAM called %d times, want 1 (cached)", calls)
}
}
+50 -15
View File
@@ -31,6 +31,8 @@ import (
gojose "github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/hanzoai/cloud/clients/principal"
)
// idClaims is the subset of Hanzo IAM JWT claims the identity sanitizer needs.
@@ -38,15 +40,31 @@ import (
type idClaims struct {
jwt.Claims
Owner string `json:"owner"` // org slug (the tenant)
Owner string `json:"owner"` // org slug (the org)
Project string `json:"project"` // org SUB-SCOPE within owner (empty ⟹ default project)
Name string `json:"name"` // display name (id fallback)
PreferredUsername string `json:"preferred_username"` // id fallback
Email string `json:"email"`
IsAdmin bool `json:"isAdmin"`
}
// mintedProject returns the project id to stamp into X-Project-Id, or "" when the
// header must be OMITTED. The project rides in the validated JWT `project` claim,
// scoped to the caller's org exactly like `owner` — trusted, not forgeable. The
// default project (absent claim, or the literal principal.DefaultProject) mints
// nothing, so X-Project-Id is present iff a non-default project is in scope. This
// mirrors the edge (iamauth.Claims.MintedProject) byte-for-byte, so the in-binary
// path binds the same header the gateway would.
func (c *idClaims) mintedProject() string {
if principal.IsDefaultProject(c.Project) {
return ""
}
return strings.TrimSpace(c.Project)
}
// userID resolves the canonical user id: sub, then preferred_username, then
// name. IAM may leave sub empty.
// name. IAM may leave sub empty. This is the STABLE identifier (a UUID when IAM
// sets sub) stamped as X-User-Id and consumed as the attribution key everywhere.
func (c *idClaims) userID() string {
if c.Subject != "" {
return c.Subject
@@ -57,6 +75,21 @@ func (c *idClaims) userID() string {
return c.Name
}
// username resolves the IAM USERNAME — the `name` half of the `<owner>/<name>`
// key IAM's privileged ops (mint-user-keys, get-user) parse. Prefers the `name`
// claim (IAM's canonical username, e.g. "z"), then preferred_username. It NEVER
// returns the subject: sub is a UUID, and `<owner>/<uuid>` fails IAM's
// GetOwnerAndNameFromId user lookup ("password or code is incorrect"). This is
// the distinct-from-userID() value stamped as X-User-Name so the direct-Bearer
// path builds owner/name correctly — the gateway historically minted
// X-User-Id==name, which userID() (sub-first) breaks on the in-binary path.
func (c *idClaims) username() string {
if c.Name != "" {
return c.Name
}
return c.PreferredUsername
}
// jwtSigAlgs is the accepted signature-algorithm allowlist passed to
// jwt.ParseSigned (go-jose v4 requires it explicitly). RSA + ECDSA + PSS, the
// set IAM may sign with — never "none".
@@ -78,6 +111,7 @@ type identityValidator struct {
issuers []string
audiences []string
cache *jwksCache
keys keyResolver // resolves an opaque API key to a principal; nil ⟹ keys stay anonymous
}
// newIdentityValidator builds a validator whose trusted-issuer set is the primary
@@ -89,11 +123,12 @@ func newIdentityValidator(issuer, jwksURL string, audiences []string, ttl time.D
issuers: trustedIssuers(issuer),
audiences: audiences,
cache: newJWKSCache(jwksURL, ttl),
keys: newIAMKeys(),
}
}
// kmsMachineAudSuffix is the fixed suffix of a per-tenant PaaS-KMS sync machine
// identity's audience. Each tenant's KMS sync authenticates as a dedicated,
// kmsMachineAudSuffix is the fixed suffix of a per-org PaaS-KMS sync machine
// identity's audience. Each org's KMS sync authenticates as a dedicated,
// NON-shared IAM application named "<org>-platform-kms" (Organization=<org>,
// client_credentials grant), so IAM stamps the token's aud == the app's own
// clientId == "<org>-platform-kms" (a non-shared app's audience is its clientId,
@@ -101,18 +136,18 @@ func newIdentityValidator(issuer, jwksURL string, audiences []string, ttl time.D
// (object/token_oauth.go GetClientCredentialsToken sets owner = app.Organization).
//
// That audience is, by construction, absent from CLOUD_JWT_AUDIENCES — it is
// per-tenant, not a fixed app — which is EXACTLY why the sync stayed pending: the
// per-org, not a fixed app — which is EXACTLY why the sync stayed pending: the
// machine token failed the audience check below, SanitizeIdentity treated it as
// anonymous, and the /v1/kms org-scope guard 403'd it before the store. The fix is
// to accept this one audience, but ONLY when it equals the token's OWN owner claim
// plus this suffix, so it certifies "the KMS sync identity for its own org" and
// grants nothing wider. Tenancy is still enforced downstream by owner at the guard
// grants nothing wider. Org-scoping is still enforced downstream by owner at the guard
// (owner == :org); this only lets a legitimately-minted, owner-scoped machine token
// clear validation. A per-tenant application means a per-tenant clientSecret — never
// a shared platform-wide reader, which would be a cross-tenant hole.
// clear validation. A per-org application means a per-org clientSecret — never
// a shared platform-wide reader, which would be a cross-org hole.
const kmsMachineAudSuffix = "-platform-kms"
// kmsMachineAudience returns the audience a tenant org's PaaS-KMS sync identity
// kmsMachineAudience returns the audience an org org's PaaS-KMS sync identity
// carries: "<owner>-platform-kms". An empty owner yields empty — no machine
// audience is ever granted to an org-less token (fail closed).
func kmsMachineAudience(owner string) string {
@@ -122,13 +157,13 @@ func kmsMachineAudience(owner string) string {
return owner + kmsMachineAudSuffix
}
// isKMSMachinePrincipal reports whether a validated token is a per-tenant KMS-sync
// isKMSMachinePrincipal reports whether a validated token is a per-org KMS-sync
// machine identity: its audience set contains the owner-bound machine audience
// (<owner>-platform-kms). Such a principal is a client_credentials machine identity
// scoped to exactly one org. SanitizeIdentity uses this to DENY it global-admin
// scoped to exactly one org. SanitizeIdentity uses this to DENY it SuperAdmin
// authority even if it somehow carries isAdmin=true and owner==adminOrg, so V6's
// audience widening can never be leveraged (via an admin-org machine token) into a
// cross-tenant read. Its org-scoped data access is unaffected — this gates ONLY the
// cross-org read. Its org-scoped data access is unaffected — this gates ONLY the
// admin grant, keeping the machine path decoupled from admin inside cloud (rather
// than resting on the external invariant "IAM never stamps isAdmin=true on a
// machine-aud token", which cloud cannot see or enforce).
@@ -179,12 +214,12 @@ func (v *identityValidator) validate(raw string) (*idClaims, error) {
return nil, fmt.Errorf("untrusted issuer %q", claims.Issuer)
}
// Audience: the static allowlist (CLOUD_JWT_AUDIENCES / brand app client_ids)
// PLUS the per-tenant PaaS-KMS sync machine audience bound to THIS token's own
// PLUS the per-org PaaS-KMS sync machine audience bound to THIS token's own
// owner (<owner>-platform-kms). The machine audience is added only when the
// allowlist is active (non-empty — always so in production) and only for the
// token's own org, so accepting it never widens tenancy: the /v1/kms guard still
// token's own org, so accepting it never widens org-scoping: the /v1/kms guard still
// gates on owner == :org. Without this, a real client_credentials machine token
// (aud == its per-tenant clientId, never in the allowlist) fails here and the
// (aud == its per-org clientId, never in the allowlist) fails here and the
// sync silently stays pending — the activation blocker.
expected := jwt.Expected{}
if len(v.audiences) > 0 {
+4 -4
View File
@@ -1,14 +1,14 @@
package cloud
// V6 (the activation blocker) — the identity validator must accept a per-tenant
// PaaS-KMS sync machine token: a client_credentials JWT whose aud is the tenant's
// own IAM application clientId "<owner>-platform-kms" (a per-tenant value, NEVER in
// V6 (the activation blocker) — the identity validator must accept a per-org
// PaaS-KMS sync machine token: a client_credentials JWT whose aud is the org's
// own IAM application clientId "<owner>-platform-kms" (a per-org value, NEVER in
// CLOUD_JWT_AUDIENCES) — but ONLY when that audience is bound to the token's OWN
// owner claim. Before the fix the machine token failed the audience check,
// SanitizeIdentity resolved anonymous, and the /v1/kms guard 403'd it, so the sync
// silently stayed pending. These are white-box unit tests of validate() itself;
// the end-to-end proof through SanitizeIdentity + the real guard lives in
// clients/kmssvc (v6_aud_e2e_test.go). Reuses the jwksServer/signWith/tokenClaims
// clients/kms (v6_aud_e2e_test.go). Reuses the jwksServer/signWith/tokenClaims
// helpers from middleware_identity_test.go (same package).
import (
+102
View File
@@ -0,0 +1,102 @@
// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloud
// Auto-routing billing binding at the cloud edge.
//
// The ai subsystem serves a virtual `auto`/`zen-router` model: it resolves the
// request to a concrete model id BEFORE pricing/billing, meters its own LLM
// token cost to commerce keyed on the SERVED model, and reports that id via the
// `X-Routed-Model` response header (and the response body `model` field).
//
// The cloud edge must therefore do two things for an `auto` request, both
// verified here end-to-end through the real BillingGate + DefaultPrice:
// 1. NOT re-price it by the (virtual) request model — /v1/ai/* is self-metered,
// so the edge gate delegates all LLM billing to the ai subsystem. That
// subsystem bills the resolved model, so `auto` bills as what served it.
// 2. Pass the `X-Routed-Model` header through untouched, so the model the
// client sees reported is exactly the model that was billed.
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/zap-proto/zip"
)
// TestAutoRoutingBillsAsResolvedModel drives an `auto` chat request through the
// real edge gate (BillingGate + DefaultPrice) in front of a handler that
// simulates the ai subsystem after it resolved auto→zen4-coder.
func TestAutoRoutingBillsAsResolvedModel(t *testing.T) {
fc := &fakeCommerce{balanceBody: `{"available":5000}`}
srv := fc.server(t)
m := mustClient(t, srv.URL, false /* fail-closed */)
app := zip.New(zip.Config{})
// The genuine edge gate with the genuine price function.
app.Use(BillingGate(m, DefaultPrice))
// Stand-in for the mounted ai subsystem: auto already resolved to zen4-coder,
// which it reports on the header + body (and meters itself — not modeled here).
app.Post("/v1/ai/chat/completions", func(c *zip.Ctx) error {
c.SetHeader("X-Routed-Model", "zen4-coder")
return c.JSON(http.StatusOK, map[string]string{"model": "zen4-coder"})
})
req := httptest.NewRequest(http.MethodPost, "/v1/ai/chat/completions",
strings.NewReader(`{"model":"auto","messages":[{"role":"user","content":"refactor this"}]}`))
req.Header.Set("X-Org-Id", "hanzo")
req.Header.Set("X-User-Id", "alice")
req.Header.Set("Content-Type", "application/json")
resp, err := app.Fiber().Test(req)
if err != nil {
t.Fatalf("Test request: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200", resp.StatusCode)
}
// (1) The edge did NOT bill: /v1/ai/* is self-metered (DefaultPrice 0), so the
// gate short-circuits before Authorize/Record. Billing is delegated to the ai
// subsystem, which meters the RESOLVED model — never the virtual `auto`.
// (Give any erroneous async Record a moment to land before asserting zero.)
if fc.usages() != 0 {
t.Fatalf("edge recorded %d usage(s) for /v1/ai/*, want 0 (self-metered by ai)", fc.usages())
}
if waitFor(func() bool { return fc.usages() > 0 }, 50*time.Millisecond) {
t.Fatalf("edge double-billed an ai request (usages=%d): auto must be billed by the ai meter, not the edge", fc.usages())
}
// (2) Header pass-through: the resolved model the ai meter billed reaches the
// client, so what's reported == what's billed.
if got := resp.Header.Get("X-Routed-Model"); got != "zen4-coder" {
t.Errorf("X-Routed-Model = %q, want zen4-coder (must pass through the edge)", got)
}
}
// TestDefaultPriceAiPathModelAgnostic documents the binding at the pricing layer:
// the edge price for the ai chat path is 0 regardless of the request model, so
// `auto` and a concrete model are treated identically — the ai subsystem's own
// per-token meter (keyed on the resolved model) is the single source of the
// charge. Path-based, never request-model-based, pricing is what makes `auto`
// bill as the model that served it.
func TestDefaultPriceAiPathModelAgnostic(t *testing.T) {
if got := priceForPath(t, "/v1/ai/chat/completions"); got != 0 {
t.Errorf("DefaultPrice(/v1/ai/chat/completions) = %d, want 0 — ai self-meters the resolved model", got)
}
}
+62
View File
@@ -0,0 +1,62 @@
package cloud
import "testing"
// The context window is a BODY-SIZE fact, not just a model fact.
//
// A chat request carries its whole prompt in the request body, so the edge's
// BodyLimit is a hard ceiling on the context window no matter what the model
// catalog advertises. The zip/fiber framework default is 4 MiB; a 1M-token
// prompt serializes to roughly 4.3 MB of JSON (measured on prod: 2 MB of body
// carried 466,148 prompt tokens, ~4.5 bytes/token). Left at the default, every
// 1M-context route — deepseek-v4-pro, and anything glm-5.2 overflows into once
// a prompt passes its 262,144 cap — was unreachable: fasthttp rejected the body
// before any handler ran and answered the opaque 400 "Error when parsing
// request", which reads like a malformed payload rather than a size cap.
//
// This pins the ceiling above a real 1M-token prompt so the regression cannot
// come back silently.
// oneMillionTokenBody is a conservative byte estimate for a 1M-token prompt.
// Measured ~4.5 bytes/token; 4.3 keeps the floor conservative.
const oneMillionTokenBody = 1_000_000 * 43 / 10 // ~4.3 MB
// zipFrameworkDefault is the zip/fiber BodyLimit applied when Config.BodyLimit
// is left at 0 (zip.go: `if cfg.BodyLimit == 0 { cfg.BodyLimit = 4 << 20 }`) —
// the exact cap that made 1M context unreachable.
const zipFrameworkDefault = 4 << 20
// LoadConfig registers process flags, so it may only be called ONCE per test
// binary (a second call panics with "flag redefined"). Both invariants are
// therefore asserted against a single load, and the env-override path is
// exercised through the getenvInt helper that LoadConfig itself uses.
func TestBodyLimit_FitsAMillionTokenPrompt(t *testing.T) {
cfg := LoadConfig()
if cfg.BodyLimit == 0 || cfg.BodyLimit == zipFrameworkDefault {
t.Fatalf("BodyLimit = %d — this is the zip/fiber 4 MiB default, the exact cap "+
"that made 1M context unreachable", cfg.BodyLimit)
}
if cfg.BodyLimit <= oneMillionTokenBody {
t.Fatalf("BodyLimit = %d bytes, which cannot hold a 1M-token prompt (~%d bytes); "+
"the 1M-context models would 400 with fasthttp's opaque "+
"%q", cfg.BodyLimit, oneMillionTokenBody, "Error when parsing request")
}
}
func TestBodyLimit_EnvOverride(t *testing.T) {
t.Setenv("GATEWAY_BODY_LIMIT", "33554432") // 32 MiB
if got := getenvInt("GATEWAY_BODY_LIMIT", 16<<20); got != 32<<20 {
t.Fatalf("getenvInt(GATEWAY_BODY_LIMIT) = %d, want %d — the limit must stay tunable", got, 32<<20)
}
}
func TestBodyLimit_DefaultsWhenEnvUnset(t *testing.T) {
t.Setenv("GATEWAY_BODY_LIMIT", "")
if got := getenvInt("GATEWAY_BODY_LIMIT", 16<<20); got != 16<<20 {
t.Fatalf("getenvInt fallback = %d, want the 16 MiB default", got)
}
}
+65 -6
View File
@@ -24,8 +24,16 @@ type BrandInfo struct {
// IAMIssuer is the OIDC issuer (JWKS source) for this brand — the value the
// JWT `iss` claim must equal and whose /v1/iam/.well-known/jwks signs tokens.
IAMIssuer string
// Domain is the brand's primary marketing/site domain (for response scoping).
// Domain is the brand's primary marketing/site domain (for response scoping
// and base-URL derivation, e.g. api.<Domain>).
Domain string
// AltDomains are additional registrable domains that ALSO belong to this
// brand, used ONLY for hostname→brand white-label detection (BrandForHostOK).
// A brand's real serving surfaces span more than its marketing domain — the
// cloud console runs on <brand>.cloud hosts (console.lux.cloud,
// console.zoo.cloud), and a request Host there must brand as Lux/Zoo, never
// fall through to Hanzo. Base-URL/issuer scoping still uses the primary Domain.
AltDomains []string
}
// brands is the brand→IAM registry. Keys are the canonical brand IDs accepted
@@ -38,13 +46,13 @@ type BrandInfo struct {
// https://hanzo.id/v1/iam/.well-known/jwks (iam.hanzo.ai is a routing alias, not
// the issuer), and the cloud CLI already defaults to hanzo.id. Pinning
// iam.hanzo.ai here would fail the issuer check on every real token, anonymizing
// every principal — global admin would 403 platform-wide (fail-secure, but
// every principal — SuperAdmin would 403 platform-wide (fail-secure, but
// broken). lux/zoo/pars already correctly point at their own .id issuers.
var brands = map[string]BrandInfo{
"hanzo": {ID: "hanzo", IAMIssuer: "https://hanzo.id", Domain: "hanzo.ai"},
"lux": {ID: "lux", IAMIssuer: "https://lux.id", Domain: "lux.network"},
"zoo": {ID: "zoo", IAMIssuer: "https://zoo.id", Domain: "zoo.ngo"},
"pars": {ID: "pars", IAMIssuer: "https://pars.id", Domain: "pars.network"},
"hanzo": {ID: "hanzo", IAMIssuer: "https://hanzo.id", Domain: "hanzo.ai", AltDomains: []string{"hanzo.cloud", "hanzo.app"}},
"lux": {ID: "lux", IAMIssuer: "https://lux.id", Domain: "lux.network", AltDomains: []string{"lux.cloud"}},
"zoo": {ID: "zoo", IAMIssuer: "https://zoo.id", Domain: "zoo.ngo", AltDomains: []string{"zoo.network", "zoo.cloud"}},
"pars": {ID: "pars", IAMIssuer: "https://pars.id", Domain: "pars.network", AltDomains: []string{"pars.ai"}},
"bootnode": {ID: "bootnode", IAMIssuer: "https://id.bootno.de", Domain: "bootno.de"},
}
@@ -65,6 +73,57 @@ func IssuerForBrand(id string) string {
return BrandFor(id).IAMIssuer
}
// BrandForHostOK resolves a request Host to a brand id from the same `brands`
// registry, mirroring the hostname→brand semantics of platform.ts's
// getWhiteLabelBrand: a Host at or under a brand's Domain (api.lux.network,
// lux.network) is that brand. The port is stripped and the compare is
// case-insensitive; the longest matching Domain wins so a nested brand domain is
// never shadowed by a shorter one. ok is false when NO brand domain matches, so
// the caller can choose its own fallback (the deployment brand) rather than
// silently emitting Hanzo branding on, say, a Zoo pod hit with an odd Host.
func BrandForHostOK(host string) (string, bool) {
host = strings.ToLower(strings.TrimSpace(host))
if i := strings.IndexByte(host, ':'); i >= 0 {
host = host[:i]
}
// A fully-qualified Host may carry a trailing root dot ("api.lux.network.");
// strip it so the suffix match still resolves the brand instead of failing to
// neutral.
host = strings.TrimSuffix(host, ".")
best, bestLen := "", -1
for id, b := range brands {
for _, d := range append([]string{b.Domain}, b.AltDomains...) {
d = strings.ToLower(d)
if d == "" {
continue
}
if (host == d || strings.HasSuffix(host, "."+d)) && len(d) > bestLen {
best, bestLen = id, len(d)
}
}
}
return best, best != ""
}
// BrandForHost is BrandForHostOK with the Hanzo default for an unmatched Host.
func BrandForHost(host string) string {
if b, ok := BrandForHostOK(host); ok {
return b
}
return DefaultBrand
}
// brandDisplay is a brand id's human display name: the id with an upper-cased
// first letter (lux → "Lux", hanzo → "Hanzo"). Derived from the id — one source
// of truth with the brands registry, no hand-maintained display list. Used to
// build the white-label console <title> (webui.go).
func brandDisplay(id string) string {
if id == "" {
id = DefaultBrand
}
return strings.ToUpper(id[:1]) + id[1:]
}
// BrandIssuers returns the OIDC issuer of every configured white-label brand. The
// in-binary identity validator (auth_identity.go) trusts a token whose `iss` is
// any of these, so ONE cloud binary validates hanzo AND lux/zoo/pars tokens. One
+40
View File
@@ -29,6 +29,46 @@ func TestBrandFor(t *testing.T) {
}
}
func TestBrandForHost(t *testing.T) {
match := map[string]string{
"api.hanzo.ai": "hanzo",
"hanzo.ai": "hanzo",
"api.lux.network": "lux",
"lux.network": "lux",
"API.LUX.NETWORK": "lux", // case-insensitive
"api.lux.network:443": "lux", // port stripped
"api.zoo.ngo": "zoo",
"chat.zoo.ngo": "zoo",
"api.pars.network": "pars",
// AltDomains: the real cloud console surfaces run on <brand>.cloud /
// <brand>.network — a Host there must brand as Lux/Zoo, never Hanzo.
"console.lux.cloud": "lux",
"console.zoo.cloud": "zoo",
"foo.zoo.network": "zoo",
"console.hanzo.cloud": "hanzo",
"app.hanzo.app": "hanzo",
}
for host, want := range match {
if got, ok := BrandForHostOK(host); !ok || got != want {
t.Errorf("BrandForHostOK(%q) = %q,%v; want %q,true", host, got, ok, want)
}
if got := BrandForHost(host); got != want {
t.Errorf("BrandForHost(%q) = %q; want %q", host, got, want)
}
}
// No brand domain matches → not ok, and BrandForHost defaults to hanzo. The
// caller (agentskills) uses the not-ok signal to fall back to the DEPLOYMENT
// brand instead of blindly emitting Hanzo on a non-hanzo pod.
for _, host := range []string{"example.com", "localhost", "", "10.0.0.1"} {
if _, ok := BrandForHostOK(host); ok {
t.Errorf("BrandForHostOK(%q) matched a brand, want no match", host)
}
if got := BrandForHost(host); got != DefaultBrand {
t.Errorf("BrandForHost(%q) = %q, want %q", host, got, DefaultBrand)
}
}
}
// TestLoadConfig_IssuerDerivedFromBrand asserts that when CLOUD_IAM_ISSUER is
// unset, the issuer is derived from CLOUD_BRAND — so a non-hanzo brand does not
// silently validate against iam.hanzo.ai.
+515 -147
View File
@@ -3,13 +3,21 @@ package cloud
import (
"context"
"fmt"
"os"
"strings"
"github.com/hanzoai/commerce/metering"
aiobject "github.com/hanzoai/ai/object"
"github.com/hanzoai/cloud/clients/commerceinproc"
"github.com/hanzoai/cloud/clients/metering"
luxlog "github.com/luxfi/log"
"github.com/zap-proto/zip"
"github.com/hanzoai/cloud/clients"
"github.com/hanzoai/cloud/clients/kms"
"github.com/hanzoai/cloud/clients/finance"
"github.com/hanzoai/cloud/clients/gatewaypolicy"
"github.com/hanzoai/cloud/clients/money"
"github.com/hanzoai/cloud/clients/s3admin"
"github.com/hanzoai/cloud/types"
)
// BuildDeps constructs the Deps used by every subsystem's Mount(app, deps).
@@ -45,7 +53,8 @@ import (
// when no endpoint is configured.
func BuildDeps(cfg *Config) Deps {
logger := luxlog.New("cloud")
logger.Info("building deps",
logger.Info(
"building deps",
"brand", cfg.Brand,
"domain", cfg.Domain,
"iam_issuer", cfg.IAMIssuer,
@@ -54,50 +63,105 @@ func BuildDeps(cfg *Config) Deps {
)
deps := Deps{
Logger: logger,
Brand: cfg.Brand,
Env: cfg.Env,
Domain: cfg.Domain,
IAMIssuer: cfg.IAMIssuer,
DataDir: cfg.DataDir,
Logger: logger,
Brand: cfg.Brand,
Version: cfg.Version,
Env: cfg.Env,
Domain: cfg.Domain,
IAMIssuer: cfg.IAMIssuer,
DataDir: cfg.DataDir,
AIDefaultModel: cfg.AIDefaultModel,
}
// For each subsystem: enabled → leave nil (Mount fills it); not
// enabled + endpoint → RPC client; not enabled + no endpoint →
// disabled stub.
deps.IAM = pickIAMClient(cfg, logger)
// disabled stub. The plain co-resident-or-RPC-or-disabled clients share
// ONE resolver (pick); KMS/AI/VFS keep bespoke pickers because their
// construction genuinely differs (embedded store / gateway preference /
// S3-admin backend). O11y's disabled stub is a no-op (telemetry going
// nowhere is normal), not fail-closed.
deps.IAM = pick(cfg, logger, "iam", "IAM", cfg.IAMZAPAddr, clients.IAMRPCAt, clients.DisabledIAM)
deps.KMS = pickKMSClient(cfg, logger)
deps.Base = pickBaseClient(cfg, logger)
deps.Base = pick(cfg, logger, "base", "Base", cfg.BaseZAPAddr, clients.BaseRPCAt, clients.DisabledBase)
deps.Commerce = pickCommerceClient(cfg, logger)
deps.AI = pickAIClient(cfg, logger)
deps.O11y = pickO11yClient(cfg, logger)
// Metering client BEFORE the AI client: deps.AI is wrapped in the metering
// decorator (the ONE inference gate+meter — no exempt path, no bypass, no
// side-channel key), which needs deps.Metering. nil-safe — an unconfigured
// commerce URL yields a !Enabled() client, so the wrap is a transparent
// pass-through and a dev deployment is never blocked.
deps.Metering = buildMeteringClient(cfg, logger)
deps.AI = meteredAIClient(pickAIClient(cfg, logger), deps)
wireFinance(cfg, logger)
deps.O11y = pick(cfg, logger, "o11y", "O11y", cfg.O11yZAPAddr, clients.O11yRPCAt, clients.DisabledO11y)
deps.VFS = pickVFSClient(cfg, logger)
deps.MQ = pickMQClient(cfg, logger)
deps.MQ = pick(cfg, logger, "mq", "MQ", cfg.MQZAPAddr, clients.MQRPCAt, clients.DisabledMQ)
// Payments and Vault never co-resident. Disabled stub when no
// endpoint, otherwise RPC.
deps.Payments = pickPaymentsClient(cfg, logger)
deps.Vault = pickVaultClient(cfg, logger)
// Billing metering client for the request-edge gate. nil-safe: when no
// commerce URL is configured the resulting client is !Enabled() and the
// gate is a no-op.
deps.Metering = buildMeteringClient(cfg, logger)
// Runtime-mutable edge-policy store (/v1/gateway config plane), layered over
// the static env/flag defaults so an un-provisioned deployment behaves exactly
// as the static config until an operator PUTs an override. New always returns a
// working *Store (static-only if the SQLite file can't open), so the edge
// middleware is never left without a policy source — a store-open error is
// logged, not fatal.
gp, err := gatewaypolicy.New(cfg.DataDir, cfg.AdminOrg, staticEdgePolicy(cfg))
if err != nil {
logger.Warn("gateway policy store degraded to static-only", "err", err)
}
deps.GatewayPolicy = gp
return deps
}
// buildMeteringClient constructs the commerce metering client for BillingGate.
// An empty CommerceHTTPURL yields a not-Enabled() client (allow + no-op),
// matching the metering package's "not configured" mode, so an unconfigured
// deployment is never blocked. The token is a KMS-sourced secret supplied via
// config; it is never logged.
// staticEdgePolicy projects the static env/flag edge config into the boot-default
// policy the gatewaypolicy.Store layers runtime overrides on top of. A disabled
// per-IP limiter (CLOUD_EDGE_RATELIMIT=false) maps to PerIPRPM 0 (a live no-op).
func staticEdgePolicy(cfg *Config) gatewaypolicy.Policy {
p := gatewaypolicy.Policy{
CORSOrigins: cfg.CORSOrigins,
WindowSec: cfg.EdgeRateWindowSec,
}
if cfg.EdgeRateEnabled {
p.PerIPRPM = cfg.EdgeRatePerIP
}
return p
}
// buildMeteringClient constructs the commerce metering client for BillingGate —
// the request-edge debit on every paid AI call.
//
// CO-RESIDENT (task #111): when commerce is folded in-process (Enabled("commerce")),
// the gate DEBITS the in-process commerce handler over commerceinproc's self-routing
// transport — a direct Go call, no socket to commerce.hanzo.svc:8001. The base is
// pinned NON-EMPTY (real CLOUD_COMMERCE_HTTP_URL, else the in-process placeholder) so
// the gate stays ENABLED even after the standalone + its env are retired — a metering
// gate that silently no-ops is a free-money hole, so it must never drop to
// "not configured" while commerce is co-resident. The transport resolves the handler
// lazily (published by commerce.Mount before any request), so building the client
// here (pre-MountAll) is fine.
//
// SPLIT-DEPLOY (unchanged): without co-residency an empty CommerceHTTPURL yields a
// not-Enabled() client (allow + no-op) and a set one speaks plain HTTP to the
// standalone, exactly as before. The token is KMS-sourced; never logged.
func buildMeteringClient(cfg *Config, log luxlog.Logger) *metering.Client {
base := cfg.CommerceHTTPURL
var httpClient metering.HTTPDoer
inProcess := cfg.Enabled("commerce")
if inProcess {
if base == "" {
base = commerceinproc.PlaceholderBase
}
httpClient = commerceinproc.Client(0) // in-process dispatch; no network timeout
}
m, err := metering.New(metering.Config{
BaseURL: cfg.CommerceHTTPURL,
Token: cfg.CommerceServiceToken,
Org: cfg.Brand, // X-Org-Id default for S2S; per-request org overrides.
FailOpen: cfg.BillingFailOpen,
BaseURL: base,
Token: cfg.CommerceServiceToken,
Org: cfg.Brand, // X-Org-Id default for S2S; per-request org overrides.
FailOpen: cfg.BillingFailOpen,
HTTPClient: httpClient, // nil off the co-resident path → metering builds its own
})
if err != nil {
// Only an unparseable URL reaches here. Fall back to a not-configured
@@ -106,51 +170,122 @@ func buildMeteringClient(cfg *Config, log luxlog.Logger) *metering.Client {
m, _ = metering.New(metering.Config{})
}
if m.Enabled() {
log.Info("billing gate enabled", "commerce_url", cfg.CommerceHTTPURL, "fail_open", cfg.BillingFailOpen)
log.Info("billing gate enabled", "commerce", boolStr(inProcess, "in-process", "http:"+base), "fail_open", cfg.BillingFailOpen)
} else {
log.Info("billing gate disabled (no commerce URL)")
}
return m
}
// pickIAMClient returns the canonical IAMClient for this process.
// nil = enabled here, Mount will fill it. RPC = remote endpoint
// configured. Disabled = not enabled, no endpoint.
func pickIAMClient(cfg *Config, log luxlog.Logger) IAMClient {
if cfg.Enabled("iam") {
return nil
func boolStr(b bool, t, f string) string {
if b {
return t
}
if cfg.IAMZAPAddr != "" {
log.Info("deps.IAM → ZAP RPC", "addr", cfg.IAMZAPAddr)
return clients.IAMRPCAt(cfg.IAMZAPAddr)
return f
}
// wireFinance constructs the ONE in-process finance ledger (per-org SQLite
// double-entry prepaid wallet), publishes it for every money consumer to resolve by
// the narrow finance.Client, and installs the embedded ai router's balance-read +
// usage-debit hooks so the PREPAID gate dispatches DIRECTLY to it — a typed in-proc
// call, no HTTP, no socket. There is NO exempt path (hanzoai/ai >= v1.805.8): every
// principal is gated on a positive prepaid balance, fail-closed. MUST run before
// ai.Mount (the ai gate reads the hook per request; the hook must be installed first)
// — which BuildDeps guarantees (deps are built before MountAll).
func wireFinance(cfg *Config, log luxlog.Logger) {
if !cfg.Enabled("commerce") {
return // money layer not co-resident (split-deploy); ai falls back to HTTP.
}
return clients.DisabledIAM()
fin := finance.New(cfg.DataDir)
finance.Publish(fin)
// Money is billed to the SUBJECT's wallet, inside the org's ledger.
//
// org = which ledger (the tenant's books)
// subject = which wallet in it (ai resolves it: a person => "org/name", an
// org-owned application/service key => the org's own account)
//
// So a personal account has a PERSONAL balance and a personal plan, and an org
// pays for what its applications and service keys spend — which is the product:
// sign up as yourself, then stand up an org whose users are your customers.
//
// Keying both hooks on the org collapsed every member onto the tenant's pool
// wallet: every new signup lives in "hanzo", so a brand-new $0 account read
// HANZO's balance and sailed through the gate — we enforced our own wallet.
//
// The invariant that must never break: the gate READ and the usage DEBIT key on
// the SAME wallet, or spend can outrun the balance that admitted it. Both use
// subject; keep them together. The gate reads a coarse cents balance (a >0
// threshold only); the DEBIT is 18-decimal-exact.
aiobject.SetBalanceReader(func(ctx context.Context, subject, namespace, currency string) (int64, error) {
bal, err := fin.Balance(ctx, namespace, subject, currency, false)
if err != nil {
return 0, err
}
return bal.Cents(), nil
})
// The DEBIT is exact: the ai module emits the cost as a decimal-USD string, parsed
// here to 18-decimal USD (1e-18) so a sub-cent call bills precisely and is never floored.
aiobject.SetUsageRecorder(func(ctx context.Context, u aiobject.UsageEvent) error {
amt, err := money.ParseUSD(u.USD)
if err != nil {
return err
}
return fin.RecordUsage(ctx, types.UsageInput{
Org: u.Namespace, Subject: u.Subject, Amount: amt,
Currency: u.Currency, Model: u.Model, Provider: u.Provider, RequestID: u.RequestID,
})
})
log.Info("finance ledger wired (per-subject wallet in the org ledger, 18-decimal-exact, fail-closed)", "dataDir", cfg.DataDir)
}
// pick resolves one inter-subsystem client under the HIP-0106 wiring rule shared
// by every co-resident-capable dependency: enabled in THIS process → zero value
// (nil) so the subsystem's own Mount installs the in-process client; not enabled
// but a ZAP endpoint is configured → an RPC client at that endpoint; neither →
// the fail-closed/no-op disabled stub. name is the enable-list id; label is the
// deps.<X> log tag; rpc/disabled are the client's typed constructors. This is the
// ONE implementation of that rule — KMS/AI/VFS opt out with bespoke pickers only
// because their construction genuinely differs.
func pick[T any](cfg *Config, log luxlog.Logger, name, label, zapAddr string, rpc func(string) T, disabled func() T) T {
if cfg.Enabled(name) {
var zero T // enabled here → Mount fills deps.<label>
return zero
}
if zapAddr != "" {
log.Info("deps."+label+" → ZAP RPC", "addr", zapAddr)
return rpc(zapAddr)
}
return disabled()
}
// pickKMSClient resolves deps.KMS. When the kms subsystem is co-resident
// (Enabled("kmssvc")) it returns the IN-PROCESS Client backed by the embedded
// (Enabled("kms")) it returns the IN-PROCESS Client backed by the embedded
// luxfi/kms SecretStore under CLOUD_DATA_DIR — no external RPC. A store-open
// failure is NOT fatal to the whole binary: it falls back to the disabled stub
// (fail-closed) and logs, so a bad data dir degrades KMS rather than crashing
// every subsystem. Absent co-residency the legacy ZAP-RPC + disabled fallbacks
// apply (out-of-process KMS, or not wired).
//
// The internal subsystem name is "kmssvc" (see clients/kmssvc.init — it avoids the
// serve.go generic-health shadow on /v1/kms/health); the client gate keys on the
// same name so "enabled" is one concept.
// The subsystem id is "kms" (clients/kms registers it with cloud.HealthOwner so
// the generic liveness route never shadows its real /v1/kms/health, and registers
// the client factory this gate calls); this gate keys on the same id so "enabled"
// is one concept.
func pickKMSClient(cfg *Config, log luxlog.Logger) KMSClient {
if cfg.Enabled("kmssvc") {
c, err := kms.New(kms.Config{
DataDir: cfg.DataDir,
MasterKeyB64: cfg.KMSMasterKeyRef,
MPCAddr: cfg.KMSMPCAddr,
MPCVaultID: cfg.KMSMPCVaultID,
}, log)
if cfg.Enabled("kms") {
// The embedded-client constructor is registered by clients/kms in init()
// (RegisterKMSClientFactory). cloud never imports clients/kms, so the KMS
// library and its /v1/kms subsystem live in one package with no cloud⇄kms
// import cycle. Absent the registration (clients/kms not linked into this
// binary) KMS fails closed rather than pretending to host secrets.
if kmsClientFactory == nil {
log.Error("deps.KMS: kms enabled but no client factory registered (clients/kms not linked); failing closed")
return clients.DisabledKMS()
}
c, err := kmsClientFactory(cfg, log)
if err != nil {
log.Error("deps.KMS: embedded KMS unavailable, failing closed", "err", err)
return clients.DisabledKMS()
}
log.Info("deps.KMS → in-process (embedded luxfi/kms)", "ready", c.Ready(), "signing", c.SigningConfigured())
return c
}
if cfg.KMSZAPAddr != "" {
@@ -160,20 +295,235 @@ func pickKMSClient(cfg *Config, log luxlog.Logger) KMSClient {
return clients.DisabledKMS()
}
func pickBaseClient(cfg *Config, log luxlog.Logger) BaseClient {
if cfg.Enabled("base") {
return nil
}
if cfg.BaseZAPAddr != "" {
log.Info("deps.Base → ZAP RPC", "addr", cfg.BaseZAPAddr)
return clients.BaseRPCAt(cfg.BaseZAPAddr)
}
return clients.DisabledBase()
// kmsClientFactory constructs the embedded in-process KMS client from cloud
// Config. clients/kms registers it in init(); pickKMSClient calls it so cloud
// depends on the KMSClient interface + this hook, never the concrete kms package
// — the same inversion the subsystem Registry already uses (cloud mounts every
// subsystem it never imports). Exactly one registration.
var kmsClientFactory func(cfg *Config, log luxlog.Logger) (KMSClient, error)
// RegisterKMSClientFactory installs the embedded-KMS constructor. clients/kms
// calls this from its init(); it is the ONE inversion point that lets the KMS
// library and its /v1/kms subsystem share one package with no cloud⇄kms cycle.
func RegisterKMSClientFactory(f func(cfg *Config, log luxlog.Logger) (KMSClient, error)) {
kmsClientFactory = f
}
// ---- git-push-to-deploy ----
// GitPushEvent describes a push that just landed on the embedded git server: the
// org, the repo, the branch that moved, and its new tip commit. CloneURL is the
// canonical clone URL of that repo (https://<host>/v1/git/<org>/<repo>.git) — the
// exact value an Application's RepoURL carries — so the builder can resolve which
// app (if any) tracks this branch and needs a rebuild.
type GitPushEvent struct {
Org string
Project string
Repo string
Branch string
Commit string
CloneURL string
}
// pushBuilder is the registered git-push-to-deploy trigger. clients/platform
// installs it in Mount; clients/git calls OnGitPush after a push lands. The
// inversion keeps git⇄platform decoupled — git never imports platform — exactly
// like kmsClientFactory and the subsystem Registry. Exactly one registration.
var pushBuilder func(ctx context.Context, ev GitPushEvent) error
// RegisterPushBuilder installs the git-push-to-deploy trigger. clients/platform
// calls this from its Mount when co-resident; it is the ONE inversion point that
// lets the embedded git server launch a platform build with no git⇄platform cycle.
func RegisterPushBuilder(f func(ctx context.Context, ev GitPushEvent) error) {
pushBuilder = f
}
// OnGitPush fires the registered push-to-deploy trigger for a landed push. It is a
// no-op when no builder is registered (git server running without the platform
// subsystem co-resident). Best-effort by contract: the caller must never fail the
// push the client already committed just because a build could not be triggered.
func OnGitPush(ctx context.Context, ev GitPushEvent) error {
if pushBuilder == nil {
return nil
}
return pushBuilder(ctx, ev)
}
// ---- first-party service release (push→build→image→CR rollout) ----
// ServiceReleaseEvent describes a proven, clean-semver image ready to roll live on
// an operator-managed first-party service. It is the payload of the release seam
// that closes push→build→image→CR: after a build produces the image, the CR for
// this service is patched to it and the operator reconciles the Deployment.
//
// - Service is the target CR metadata.name (the repo/service name ⇒ CR name,
// mirroring universe's image-update.yml convention).
// - Image is the full registry ref (repository:tag); the tag MUST be clean
// semver (vX.Y.Z) — the releaser refuses every mutable/sha/suffixed form.
// - SHA is the source commit for provenance (optional; logged, never gated on).
type ServiceReleaseEvent struct {
Service string
Image string
SHA string
}
// serviceReleaser is the registered first-party CR-rollout seam. clients/paas
// (the owner of the hanzo.ai/v1 Service CR control plane) installs it in Mount; a
// proven build calls OnServiceRelease, which patches spec.image on the matching
// CR. The inversion keeps package cloud from importing clients/paas (which imports
// cloud) — the same idiom as pushBuilder / kmsClientFactory. Exactly one
// registration.
var serviceReleaser func(ctx context.Context, ev ServiceReleaseEvent) error
// RegisterServiceReleaser installs the first-party CR-rollout hook. clients/paas
// calls this from its Mount when co-resident; it is the ONE inversion point that
// lets a build-completion path roll a proven image onto its operator Service CR
// with no cloud⇄paas import cycle.
func RegisterServiceReleaser(f func(ctx context.Context, ev ServiceReleaseEvent) error) {
serviceReleaser = f
}
// ServiceReleaserRegistered reports whether a first-party CR-rollout hook is
// installed (the paas control plane is co-resident). A caller uses it to know
// whether OnServiceRelease actually patches a CR or is a no-op, so it can be
// honest about which rollout path took effect.
func ServiceReleaserRegistered() bool { return serviceReleaser != nil }
// OnServiceRelease rolls a proven image live by patching the matching hanzo.ai/v1
// Service CR's spec.image (the operator then reconciles the Deployment). It is a
// no-op when no releaser is registered (a binary without the paas control plane
// co-resident). The releaser enforces the clean-semver gate and CR-name
// resolution; this is only the dispatch seam.
func OnServiceRelease(ctx context.Context, ev ServiceReleaseEvent) error {
if serviceReleaser == nil {
return nil
}
return serviceReleaser(ctx, ev)
}
// ---- git lifecycle event stream ----
//
// One event, many subscribers. push-to-deploy (OnGitPush) is the deploy
// subscriber-of-record and stays exactly as it is; this seam generalizes the SAME
// inversion to N reactors (mirror-out, Slack-notify, …) so git/platform EMIT a
// lifecycle fact and never import the subscribers. It is deliberately SEPARATE
// from OnGitPush — the deploy path is single-registrant and synchronous, this
// stream is many-registrant and best-effort — so adding a reactor can never
// perturb push→deploy.
// LifecycleKind classifies a git lifecycle event. The value IS the wire name a
// subscription filters on.
type LifecycleKind string
const (
LifecyclePushLanded LifecycleKind = "push.landed"
LifecycleBuildStarted LifecycleKind = "build.started"
LifecycleDeployLive LifecycleKind = "deploy.live"
LifecycleDeployFailed LifecycleKind = "deploy.failed"
)
// LifecycleEvent is one git lifecycle fact fanned out to every registered
// subscriber. A plain data value — values, not places:
// - Org/Project/Repo the tenant + repo the fact happened in (the routing key).
// - Branch/Before/After the ref that moved and its old→new tip (a push).
// - Pusher who pushed (best-effort; "" for a client-less push).
// - DeployID/Detail the deployment id + a human one-liner (a deploy transition).
// - Origin "" for a native push; the source host when the refs
// arrived via an inbound mirror sync — the loop-prevention seam that lets the
// outbound mirror subscriber suppress a re-mirror of refs it just pulled in.
type LifecycleEvent struct {
Kind LifecycleKind
Org string
Project string
Repo string
Branch string
Before string
After string
Pusher string
DeployID string
Detail string
Origin string
}
// RepoFromCloneURL extracts the repo name from a git clone URL (last path segment,
// ".git" stripped) — the repo component of the (org,project,repo) routing key that
// a deploy emitter derives from an app/project's linked RepoURL. The ONE place this
// derivation lives, shared by the platform + projects deploy paths (no per-package
// copy).
func RepoFromCloneURL(u string) string {
u = strings.TrimSuffix(strings.TrimSpace(u), "/")
u = strings.TrimSuffix(u, ".git")
if i := strings.LastIndexByte(u, '/'); i >= 0 {
return u[i+1:]
}
return u
}
// lifecycleSubscribers is the fan-out list. Registration happens at Mount
// (single-threaded, before any request is served), so a plain slice is correct:
// EmitLifecycle only ever ranges it after every subsystem's Mount has run.
var lifecycleSubscribers []func(ctx context.Context, ev LifecycleEvent)
// RegisterLifecycleSubscriber adds a git-lifecycle reactor. Every subsystem that
// reacts to a push/deploy (mirror-out, Slack-notify) registers ONE here at Mount;
// git/platform EMIT via EmitLifecycle. The inversion keeps the emitters from
// importing the subscribers — the same pattern as RegisterPushBuilder, but
// many-registrant.
func RegisterLifecycleSubscriber(fn func(ctx context.Context, ev LifecycleEvent)) {
if fn == nil {
return
}
lifecycleSubscribers = append(lifecycleSubscribers, fn)
}
// ResetLifecycleSubscribers clears the registry. TEST-ONLY seam (a test mounts and
// unmounts repeatedly); production registers once at Mount and never resets.
func ResetLifecycleSubscribers() { lifecycleSubscribers = nil }
// EmitLifecycle fans one event out to every registered subscriber, best-effort and
// NON-BLOCKING: each subscriber runs in its own goroutine on a cancel-immune
// context (the fact already happened — a request cancel must not abort the
// notify/mirror), so a slow reactor (a mirror push) can never delay the git/deploy
// path or another reactor. A panicking subscriber is contained so one bad reactor
// can neither crash the shared multi-tenant process nor starve the others; each
// subscriber logs its own errors.
func EmitLifecycle(ctx context.Context, ev LifecycleEvent) {
subs := lifecycleSubscribers
if len(subs) == 0 {
return
}
bg := context.WithoutCancel(ctx)
for _, fn := range subs {
go func(fn func(context.Context, LifecycleEvent)) {
defer func() { _ = recover() }()
fn(bg, ev)
}(fn)
}
}
// pickCommerceClient resolves deps.Commerce — the typed inter-subsystem client the
// entitlements/licensing tier calls (GetOrgConfig, CheckEntitlement). When the
// commerce subsystem is co-resident (Enabled("commerce")) it returns the IN-PROCESS
// client via the factory apps/commerce.go registers in init() — a direct Go
// call that reads the embedded commerce datastore (hanzoai/commerce MODULE, since
// the un-fork) + the @hanzo/plans vocabulary, no network hop (the HIP-0106
// co-resident default). The factory inversion stays because the concrete client
// (clients/commerceinproc) imports clients/plan, which imports cloud — a direct
// call here would be a package cycle. Absent the registration it fails closed
// rather than pretending.
//
// NETWORK PATH PRESERVED: absent co-residency the ZAP-RPC + disabled fallbacks apply
// (out-of-process commerce, or not wired), so the remote proxy seam
// (CLOUD_COMMERCE_ZAP_ADDR) is unchanged — the live default still selects the
// network client when commerce is not enabled in this process.
func pickCommerceClient(cfg *Config, log luxlog.Logger) CommerceClient {
if cfg.Enabled("commerce") {
return nil
if commerceClientFactory == nil {
log.Error("deps.Commerce: commerce enabled but no client factory registered (subsystems not linked); failing closed")
return clients.DisabledCommerce()
}
log.Info("deps.Commerce → in-process (embedded commerce)", "brand", cfg.Brand)
return commerceClientFactory(cfg, log)
}
if cfg.CommerceZAPAddr != "" {
log.Info("deps.Commerce → ZAP RPC", "addr", cfg.CommerceZAPAddr)
@@ -182,6 +532,19 @@ func pickCommerceClient(cfg *Config, log luxlog.Logger) CommerceClient {
return clients.DisabledCommerce()
}
// commerceClientFactory constructs the embedded in-process Commerce client.
// apps/commerce.go registers it in init(); pickCommerceClient calls it so
// package cloud depends on the CommerceClient interface + this hook, never the
// concrete commerceinproc package (whose entitlement client pulls clients/plan,
// which imports cloud — the hook is what keeps the package graph acyclic).
var commerceClientFactory func(cfg *Config, log luxlog.Logger) CommerceClient
// RegisterCommerceClientFactory installs the embedded-Commerce client constructor.
// apps/commerce.go calls this from its init(); exactly one registration.
func RegisterCommerceClientFactory(f func(cfg *Config, log luxlog.Logger) CommerceClient) {
commerceClientFactory = f
}
// pickAIClient resolves deps.AI — the client the agents subsystem runs chat
// completions through. Unlike the co-resident subsystems, there is NO in-process
// "ai" mount that fills a nil deps.AI: inference is an external gateway, so this
@@ -204,11 +567,13 @@ func pickAIClient(cfg *Config, log luxlog.Logger) AIClient {
log.Info("deps.AI → HTTP gateway (static key)", "base_url", cfg.AIBaseURL, "default_model", cfg.AIDefaultModel)
return clients.AIHTTPAt(cfg.AIBaseURL, cfg.AIAPIKey, cfg.AIDefaultModel)
}
if cfg.AIBaseURL != "" && cfg.AIAuthClientID != "" && cfg.AIAuthClientSecret != "" && cfg.IAMIssuer != "" {
tokenURL := strings.TrimRight(cfg.IAMIssuer, "/") + "/v1/iam/oauth/token"
log.Info("deps.AI → HTTP gateway (IAM M2M)", "base_url", cfg.AIBaseURL,
"token_url", tokenURL, "client_id", cfg.AIAuthClientID, "default_model", cfg.AIDefaultModel)
return clients.AIHTTPM2M(cfg.AIBaseURL, tokenURL, cfg.AIAuthClientID, cfg.AIAuthClientSecret, cfg.AIDefaultModel)
if cfg.AIBaseURL != "" && cfg.AIAuthClientID != "" && cfg.AIAuthClientSecret != "" {
tokenURL := aiM2MTokenURL(cfg)
if tokenURL != "" {
log.Info("deps.AI → HTTP gateway (IAM M2M)", "base_url", cfg.AIBaseURL,
"token_url", tokenURL, "client_id", cfg.AIAuthClientID, "default_model", cfg.AIDefaultModel)
return clients.AIHTTPM2M(cfg.AIBaseURL, tokenURL, cfg.AIAuthClientID, cfg.AIAuthClientSecret, cfg.AIDefaultModel)
}
}
if cfg.AIZAPAddr != "" {
log.Info("deps.AI → ZAP RPC", "addr", cfg.AIZAPAddr)
@@ -218,41 +583,63 @@ func pickAIClient(cfg *Config, log luxlog.Logger) AIClient {
return clients.DisabledAI()
}
func pickO11yClient(cfg *Config, log luxlog.Logger) O11yClient {
if cfg.Enabled("o11y") {
return nil
// aiM2MTokenURL resolves IAM's client_credentials endpoint the agent runner mints
// its M2M inference token at. It MUST be reachable FROM INSIDE THE CLUSTER: the
// runner runs in-cluster and the public issuer host (https://hanzo.id) is fronted
// by Cloudflare, which 403s a server-side (non-browser) loopback POST with edge
// error 1006 — so minting against the PUBLIC issuer URL fails and every
// POST /v1/agents/:ref/run 502s (root-caused 2026-07-04: in-cluster POST to
// https://hanzo.id/v1/iam/oauth/token → 403/1006, while http://iam.hanzo.svc/... → 200).
// This mirrors the KMS login-broker resolution (clients/kms) exactly — one
// split-horizon policy, no drift. Prefer, in order: an explicit override
// (CLOUD_AI_IAM_TOKEN_URL), the in-cluster IAM service base (IAM_URL — already
// wired to http://iam.hanzo.svc for JWKS), then the public issuer as a last resort
// (single-process / no split-horizon deploys). Returns "" only when no identity is
// resolvable, which keeps the M2M branch off (caller falls through to the stub).
func aiM2MTokenURL(cfg *Config) string {
if override := strings.TrimSpace(os.Getenv("CLOUD_AI_IAM_TOKEN_URL")); override != "" {
return override
}
if cfg.O11yZAPAddr != "" {
log.Info("deps.O11y → ZAP RPC", "addr", cfg.O11yZAPAddr)
return clients.O11yRPCAt(cfg.O11yZAPAddr)
if base := strings.TrimRight(strings.TrimSpace(os.Getenv("IAM_URL")), "/"); base != "" {
return base + "/v1/iam/oauth/token"
}
// O11y disabled-stub is no-op (not fail-closed) — telemetry
// going nowhere is a normal mode.
return clients.DisabledO11y()
if iss := strings.TrimRight(strings.TrimSpace(cfg.IAMIssuer), "/"); iss != "" {
return iss + "/v1/iam/oauth/token"
}
return ""
}
func pickVFSClient(cfg *Config, log luxlog.Logger) VFSClient {
if cfg.Enabled("vfs") {
return nil
}
// deps.VFS must NEVER be nil (R-7): files.go and any other VFS consumer call
// s.vfs.Put/Get/Delete unconditionally, so a nil here is a per-request 500
// (dishonest degradation) instead of a fail-closed 502. Unlike the
// nil-then-Mount-fills convention other subsystems use, nothing fills deps.VFS
// after MountAll (Mount receives deps by value), so we ALWAYS hand back a
// concrete client.
if cfg.VFSZAPAddr != "" {
log.Info("deps.VFS → ZAP RPC", "addr", cfg.VFSZAPAddr)
return clients.VFSRPCAt(cfg.VFSZAPAddr)
}
// Real blob backend (.97): the shared SeaweedFS S3 gateway — the canonical,
// key-based object store, reached with the SAME S3_ADMIN_* admin identity
// clients/s3 uses (s3admin, one construction). Present only when those creds
// are injected; a construction failure degrades to fail-closed rather than a
// nil deref. Team blobs (avatars/attachments) round-trip through this to the
// team-blobs bucket, org-scoped by the caller-built key prefix.
if admin := s3admin.New(); admin.Configured() {
v, err := clients.NewS3VFS(admin)
if err != nil {
log.Error("deps.VFS → S3 construction failed; falling back to fail-closed", "err", err)
return clients.DisabledVFS()
}
log.Info("deps.VFS → SeaweedFS S3", "bucket", clients.TeamBlobBucket)
return v
}
// No VFS endpoint and no S3 admin creds → fail-closed stub (R-7): Put/Get/Delete
// return a non-nil error → files answer 502, never a nil-deref 500.
return clients.DisabledVFS()
}
func pickMQClient(cfg *Config, log luxlog.Logger) MQClient {
if cfg.Enabled("mq") {
return nil
}
if cfg.MQZAPAddr != "" {
log.Info("deps.MQ → ZAP RPC", "addr", cfg.MQZAPAddr)
return clients.MQRPCAt(cfg.MQZAPAddr)
}
return clients.DisabledMQ()
}
func pickPaymentsClient(cfg *Config, log luxlog.Logger) PaymentsClient {
if cfg.PaymentsZAPAddr != "" {
log.Info("deps.Payments → ZAP RPC", "addr", cfg.PaymentsZAPAddr)
@@ -269,11 +656,17 @@ func pickVaultClient(cfg *Config, log luxlog.Logger) VaultClient {
return clients.DisabledVault()
}
// MountFunc is the canonical signature every subsystem exposes per
// HIP-0106. Each Hanzo Go service ships a top-level `Mount` symbol
// matching this signature; cmd/cloud/main.go imports the package and
// calls it.
type MountFunc func(app any, deps Deps) error // app is *zip.App; using any here to avoid an import cycle in pkg/cloud
// MountFunc is a subsystem's mount contract: register your routes on app, using
// deps for everything shared. Every subsystem in the fleet exports exactly this
// signature, so Wire references each one directly and the compiler checks it.
//
// app was once `any`, on the stated grounds that an external module (licensing)
// exposed func(any, Deps) error and narrowing would break it — while licensing
// said it used `any` to avoid an import cycle in pkg/cloud. Each cited the other,
// and the cycle could not exist: this package already imports zip, and zip does
// not import cloud. The `any` bought nothing and cost every subsystem a Typed()
// wrapper plus a runtime type assertion whose failure branch was unreachable.
type MountFunc func(app *zip.App, deps Deps) error
// ShutdownFunc releases a subsystem's process-lifetime resources (background
// goroutines, open DB handles) on graceful shutdown. It must be idempotent and
@@ -281,66 +674,35 @@ type MountFunc func(app any, deps Deps) error // app is *zip.App; using any here
// deadline so a slow teardown is cut off rather than hanging SIGTERM.
type ShutdownFunc func(ctx context.Context) error
// MountSpec describes one subsystem registered for mounting. The Order
// is used when ordering matters for inter-subsystem deps (e.g. iam
// before authz before commerce).
// MountSpec describes one subsystem to mount. There is NO Order field: the slice
// position in apps.Wire() IS the mount order — the composition root lists
// subsystems in the exact sequence they mount (and, reversed, tear down), so order
// is data read top-to-bottom in one file, not ints scattered across the tree.
type MountSpec struct {
Name string
Order int
Mount MountFunc
Shutdown ShutdownFunc // optional; nil means the subsystem has nothing to tear down.
// OwnsHealth marks a subsystem that serves its OWN GET /v1/<name>/health
// (a real, fail-closed probe). Serve's generic liveness loop skips these so
// its always-ok route never shadows the subsystem's real probe.
OwnsHealth bool
}
// Registry is the in-process subsystem registry. Subsystems register via
// init() functions in their respective packages OR cmd/cloud/main.go can
// explicitly enumerate them. Either pattern works.
var Registry []MountSpec
// Register adds a subsystem to the in-process registry.
func Register(name string, order int, mount MountFunc) {
Registry = append(Registry, MountSpec{Name: name, Order: order, Mount: mount})
}
// RegisterWithShutdown adds a subsystem that owns process-lifetime resources: a
// background worker (e.g. the agents scheduler) or a DB handle that must be
// flushed. shutdown is invoked by ShutdownAll on graceful stop. This is the ONE
// way a subsystem gets a teardown — Register stays the zero-teardown default.
func RegisterWithShutdown(name string, order int, mount MountFunc, shutdown ShutdownFunc) {
Registry = append(Registry, MountSpec{Name: name, Order: order, Mount: mount, Shutdown: shutdown})
}
// ShutdownAll tears down every ENABLED subsystem that registered a ShutdownFunc,
// in REVERSE mount order (a dependency is torn down after its dependents), best
// effort: a failure is collected and the rest still run, so one stuck subsystem
// can't strand another's flush. Serve calls this inside the shutdown deadline.
func ShutdownAll(ctx context.Context, cfg *Config) error {
var firstErr error
for i := len(Registry) - 1; i >= 0; i-- {
spec := Registry[i]
if spec.Shutdown == nil || !cfg.Enabled(spec.Name) {
continue
}
if err := spec.Shutdown(ctx); err != nil && firstErr == nil {
firstErr = fmt.Errorf("shutdown %s: %w", spec.Name, err)
}
}
return firstErr
}
// MountAll iterates the registry in order and calls Mount() on each
// enabled subsystem.
func MountAll(app any, cfg *Config, deps Deps) error {
// Sort registry by order — bubble sort, registry is tiny.
for i := 0; i < len(Registry); i++ {
for j := i + 1; j < len(Registry); j++ {
if Registry[j].Order < Registry[i].Order {
Registry[i], Registry[j] = Registry[j], Registry[i]
}
}
}
// MountAll mounts every ENABLED subsystem in specs, in slice order — the order is
// the composition root's (apps.Wire()); MountAll does NOT sort. app is the
// concrete *zip.App from Serve, handed to each MountFunc as itself.
//
// Teardown is wired HERE, at mount time: right after a subsystem mounts, its
// ShutdownFunc (if any) is registered via app.OnShutdown. zip drains those hooks
// LIFO — AFTER the listeners stop accepting and in-flight requests drain — so
// registration-at-mount yields reverse-mount teardown (a dependency mounted before
// its dependents is torn down after them) with no subsystem torn down while a
// request still uses it. Only ENABLED specs mount, so only they register a hook;
// teardown needs no separate enablement gate.
func MountAll(app *zip.App, specs []MountSpec, cfg *Config, deps Deps) error {
logger := deps.Logger
for _, spec := range Registry {
for _, spec := range specs {
if !cfg.Enabled(spec.Name) {
logger.Debug("subsystem disabled", "name", spec.Name)
continue
@@ -348,6 +710,12 @@ func MountAll(app any, cfg *Config, deps Deps) error {
if err := spec.Mount(app, deps); err != nil {
return fmt.Errorf("mount %s: %w", spec.Name, err)
}
// Register teardown as a zip shutdown hook. zip runs hooks LIFO after the
// drain (zip.App.Shutdown), so this reproduces the reverse-mount order the
// hand-rolled reverse-loop gave — without the teardown-before-drain race.
if spec.Shutdown != nil {
app.OnShutdown(spec.Shutdown)
}
logger.Info("mounted subsystem", "name", spec.Name)
}
return nil
+62
View File
@@ -0,0 +1,62 @@
package cloud
import "testing"
// TestAIM2MTokenURL pins the split-horizon resolution order for the agent-runner
// M2M token endpoint (the GAP that 502'd every POST /v1/agents/:ref/run: the
// public issuer host is Cloudflare-fronted and 403s an in-cluster loopback with
// edge error 1006). The runner must mint its token from an IN-CLUSTER URL. Order:
// explicit override → in-cluster IAM_URL → public IAMIssuer fallback.
func TestAIM2MTokenURL(t *testing.T) {
const tokenPath = "/v1/iam/oauth/token"
cases := []struct {
name string
override string // CLOUD_AI_IAM_TOKEN_URL
iamURL string // IAM_URL
iamIssuer string // cfg.IAMIssuer
want string
}{
{
name: "explicit override wins over everything",
override: "http://iam.internal:1234/custom/token",
iamURL: "http://iam.hanzo.svc",
// even a public issuer present must not be chosen
iamIssuer: "https://hanzo.id",
want: "http://iam.internal:1234/custom/token",
},
{
name: "in-cluster IAM_URL preferred over public issuer",
iamURL: "http://iam.hanzo.svc",
iamIssuer: "https://hanzo.id",
want: "http://iam.hanzo.svc" + tokenPath,
},
{
name: "trailing slash on IAM_URL is trimmed",
iamURL: "http://iam.hanzo.svc/",
iamIssuer: "https://hanzo.id",
want: "http://iam.hanzo.svc" + tokenPath,
},
{
name: "falls back to public issuer only when no in-cluster URL",
iamIssuer: "https://hanzo.id",
want: "https://hanzo.id" + tokenPath,
},
{
name: "empty when no identity is resolvable (keeps M2M branch off)",
want: "",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// t.Setenv restores prior values + prevents parallel interference.
t.Setenv("CLOUD_AI_IAM_TOKEN_URL", tc.override)
t.Setenv("IAM_URL", tc.iamURL)
cfg := &Config{IAMIssuer: tc.iamIssuer}
if got := aiM2MTokenURL(cfg); got != tc.want {
t.Fatalf("aiM2MTokenURL() = %q, want %q", got, tc.want)
}
})
}
}
+203
View File
@@ -0,0 +1,203 @@
package cloud_test
import (
"context"
"net"
"net/http"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/hanzoai/cloud"
luxlog "github.com/luxfi/log"
"github.com/zap-proto/zip"
)
// noopMount mounts nothing: the fake specs below carry the behavior under test in
// their Shutdown, not their Mount.
func noopMount(*zip.App, cloud.Deps) error { return nil }
// freeAddr reserves an ephemeral loopback port and hands back its address; the
// listener is closed so the app under test can bind it.
func freeAddr(t *testing.T) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("reserve port: %v", err)
}
addr := ln.Addr().String()
_ = ln.Close()
return addr
}
// waitListening blocks until addr accepts a TCP connection (the app's Listen
// goroutine has bound it) or a short deadline elapses.
func waitListening(t *testing.T, addr string) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if c, err := net.DialTimeout("tcp", addr, 100*time.Millisecond); err == nil {
_ = c.Close()
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("server never listened on %s", addr)
}
// TestMountAll_ShutdownHooksLIFOAfterDrain proves the OnShutdown teardown wiring:
// MountAll registers each ENABLED subsystem's ShutdownFunc as a zip shutdown hook,
// so on app.Shutdown they run (1) AFTER in-flight requests drain and (2) LIFO =
// reverse-mount order (a dependency mounted before its dependents is torn down
// after them). That is exactly the contract the deleted hand-rolled reverse-loop
// provided by hand — now owned by zip, minus the teardown-before-drain race.
func TestMountAll_ShutdownHooksLIFOAfterDrain(t *testing.T) {
app := zip.New(zip.Config{Logger: luxlog.NewNoOpLogger(), DisableStartupMessage: true})
// One monotonic tick stamps the ONLY two kinds of event we order against each
// other: the in-flight request finishing its drain, and each teardown hook.
var tick atomic.Int64
var mu sync.Mutex
teardown := map[string]int64{}
record := func(name string) cloud.ShutdownFunc {
return func(context.Context) error {
mu.Lock()
teardown[name] = tick.Add(1)
mu.Unlock()
return nil
}
}
// Mount order a, b, c ⇒ LIFO teardown must be c, b, a.
specs := []cloud.MountSpec{
{Name: "a", Mount: noopMount, Shutdown: record("a")},
{Name: "b", Mount: noopMount, Shutdown: record("b")},
{Name: "c", Mount: noopMount, Shutdown: record("c")},
}
cfg := &cloud.Config{Enable: []string{"a", "b", "c"}}
deps := cloud.Deps{Logger: luxlog.NewNoOpLogger()}
// A request that parks inside its handler until released, so the shutdown drain
// has something real to wait on. Its drain tick is stamped the instant the
// handler returns — i.e. the moment this request finishes draining.
entered := make(chan struct{})
release := make(chan struct{})
var drainTick int64
app.Get("/hold", func(c *zip.Ctx) error {
close(entered)
<-release
atomic.StoreInt64(&drainTick, tick.Add(1))
return c.JSON(http.StatusOK, map[string]bool{"ok": true})
})
if err := cloud.MountAll(app, specs, cfg, deps); err != nil {
t.Fatalf("MountAll: %v", err)
}
// Serve on a real loopback listener: an in-flight request over the HTTP
// transport is what zip's shutdown actually drains (closeServers → drain) in
// production — the path a listener-less test cannot exercise.
addr := freeAddr(t)
serveDone := make(chan error, 1)
go func() { serveDone <- app.Listen("http://" + addr) }()
waitListening(t, addr)
// Fire the request; it parks mid-handler with the connection held open.
reqDone := make(chan struct{})
go func() {
defer close(reqDone)
req, _ := http.NewRequest(http.MethodGet, "http://"+addr+"/hold", nil)
req.Close = true // no keep-alive: server drops the conn once the handler returns
client := &http.Client{Timeout: 30 * time.Second}
if resp, err := client.Do(req); err == nil {
_ = resp.Body.Close()
}
}()
<-entered // the request is now in-flight, parked mid-handler
// Shut down WHILE the request is in-flight. zip stops the listeners accepting,
// drains (blocking on our parked handler), THEN runs the hooks LIFO.
shutDone := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
shutDone <- app.ShutdownWithContext(ctx)
}()
// Barrier: with a request still in-flight, Shutdown MUST NOT complete — it is
// blocked in the drain. If it returns here, teardown ran without waiting for the
// drain (the exact race the OnShutdown move fixes).
select {
case <-shutDone:
t.Fatal("Shutdown completed while a request was still in-flight — teardown did not wait for the drain")
case <-time.After(150 * time.Millisecond):
}
// Let the handler finish so the drain can complete; hooks fire only after.
close(release)
if err := <-shutDone; err != nil {
t.Fatalf("ShutdownWithContext: %v", err)
}
<-reqDone
<-serveDone // Listen returns once the transport listener is closed
// (1) AFTER THE DRAIN: the in-flight request finished (drainTick) strictly
// before ANY teardown hook ran — no hook raced a request still using it.
dt := atomic.LoadInt64(&drainTick)
if dt == 0 {
t.Fatal("in-flight request never drained")
}
for name, tk := range teardown {
if tk < dt {
t.Fatalf("hook %q ran at tick %d, before the drain finished at tick %d — teardown raced the still-draining request", name, tk, dt)
}
}
// (2) LIFO = reverse mount order: c (mounted last) tears down first, a last.
if len(teardown) != 3 {
t.Fatalf("want 3 hooks run, got %d (%v)", len(teardown), teardown)
}
if !(teardown["c"] < teardown["b"] && teardown["b"] < teardown["a"]) {
t.Fatalf("teardown not LIFO: a=%d b=%d c=%d (want c<b<a)", teardown["a"], teardown["b"], teardown["c"])
}
}
// TestMountAll_ShutdownRegistration_EnablementAndNil proves MountAll registers a
// teardown hook ONLY for an ENABLED spec that HAS a ShutdownFunc: a disabled spec
// never mounts (so never registers a hook), and an enabled spec whose Shutdown is
// nil is skipped without panicking. This keeps the enablement axis and the nil
// guard from silently regressing now that teardown moved onto app.OnShutdown.
func TestMountAll_ShutdownRegistration_EnablementAndNil(t *testing.T) {
app := zip.New(zip.Config{Logger: luxlog.NewNoOpLogger(), DisableStartupMessage: true})
var mu sync.Mutex
var ran []string
record := func(name string) cloud.ShutdownFunc {
return func(context.Context) error {
mu.Lock()
ran = append(ran, name)
mu.Unlock()
return nil
}
}
specs := []cloud.MountSpec{
{Name: "enabled", Mount: noopMount, Shutdown: record("enabled")},
{Name: "disabled", Mount: noopMount, Shutdown: record("disabled")},
{Name: "nilsd", Mount: noopMount}, // enabled, but no Shutdown
}
cfg := &cloud.Config{Enable: []string{"enabled", "nilsd"}} // "disabled" omitted
if err := cloud.MountAll(app, specs, cfg, cloud.Deps{Logger: luxlog.NewNoOpLogger()}); err != nil {
t.Fatalf("MountAll: %v", err)
}
if err := app.Shutdown(); err != nil {
t.Fatalf("Shutdown: %v", err)
}
if len(ran) != 1 || ran[0] != "enabled" {
t.Fatalf("teardown hooks ran = %v, want [enabled] (disabled never mounts; nil Shutdown skipped)", ran)
}
}
+28
View File
@@ -0,0 +1,28 @@
package cloud_test
import (
"testing"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
)
// TestMountFunc_IsTheSubsystemSignature pins the registry's mount contract: the
// signature every subsystem exports IS a cloud.MountFunc, checked by the compiler.
//
// This file used to test cloud.Typed, the adapter that took a MountFunc's `any`
// app and asserted it back to *zip.App. Both of its tests went with it, and
// neither is a loss:
//
// - "Typed recovers the *zip.App" only ever proved the adapter handed through
// the value it was given. MountFunc now names *zip.App, so there is no
// recovery step left to get wrong.
// - "Typed fails closed on a wrong type" can no longer be written: passing
// "not-a-zip-app" to a MountFunc is a compile error, so the runtime branch it
// exercised does not exist. A test asserting a wrong type is rejected is
// precisely what a type already is.
//
// What remains is the only claim worth making, and the build enforces it.
func TestMountFunc_IsTheSubsystemSignature(t *testing.T) {
var _ cloud.MountFunc = func(*zip.App, cloud.Deps) error { return nil }
}
+43
View File
@@ -0,0 +1,43 @@
package cloud
import (
"context"
"errors"
"testing"
)
// TestOnServiceReleaseNoop proves the dispatch seam is a safe no-op when no
// releaser is registered (a binary without the paas control plane co-resident) —
// mirroring OnGitPush's contract.
func TestOnServiceReleaseNoop(t *testing.T) {
RegisterServiceReleaser(nil)
if ServiceReleaserRegistered() {
t.Fatal("ServiceReleaserRegistered() = true with no releaser registered")
}
if err := OnServiceRelease(context.Background(), ServiceReleaseEvent{Service: "cloud", Image: "ghcr.io/hanzoai/cloud:v1.0.0"}); err != nil {
t.Fatalf("OnServiceRelease with no releaser = %v, want nil no-op", err)
}
}
// TestOnServiceReleaseDispatch proves a registered releaser receives the exact
// event and its error propagates — the one inversion point paas installs.
func TestOnServiceReleaseDispatch(t *testing.T) {
var got ServiceReleaseEvent
sentinel := errors.New("boom")
RegisterServiceReleaser(func(_ context.Context, ev ServiceReleaseEvent) error {
got = ev
return sentinel
})
t.Cleanup(func() { RegisterServiceReleaser(nil) })
if !ServiceReleaserRegistered() {
t.Fatal("ServiceReleaserRegistered() = false after registration")
}
want := ServiceReleaseEvent{Service: "hanzo-app", Image: "ghcr.io/hanzoai/hanzo-app:v1.42.15", SHA: "abc1234"}
if err := OnServiceRelease(context.Background(), want); !errors.Is(err, sentinel) {
t.Fatalf("OnServiceRelease error = %v, want sentinel", err)
}
if got != want {
t.Fatalf("releaser received %+v, want %+v", got, want)
}
}
+8 -3
View File
@@ -6,6 +6,11 @@ import (
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients"
// Blank import registers the kms subsystem's client factory (init) into cloud,
// so BuildDeps can build the in-process deps.KMS below. cloud itself never
// imports clients/kms (no cloud⇄kms cycle); this external test can.
_ "github.com/hanzoai/cloud/clients/kms"
)
// TestBuildDeps_EnabledLeavesNil verifies that BuildDeps leaves an enabled
@@ -28,7 +33,7 @@ func TestBuildDeps_EnabledLeavesNil(t *testing.T) {
}
// TestBuildDeps_KMSEnabledIsInProcess verifies the HIP-0106 "embed KMS in cloud"
// contract: when the kms subsystem (kmssvc) is enabled, deps.KMS is a live
// contract: when the kms subsystem is enabled, deps.KMS is a live
// in-process client (never nil, never a disabled stub) so other subsystems get a
// working KMS via direct Go dispatch with no RPC. Absent a master key it still
// resolves (health-only, fail-closed) — the point is that deps.KMS is populated.
@@ -37,12 +42,12 @@ func TestBuildDeps_KMSEnabledIsInProcess(t *testing.T) {
Brand: "hanzo",
Domain: "api.hanzo.ai",
DataDir: t.TempDir(),
Enable: []string{"kmssvc"},
Enable: []string{"kms"},
}
deps := cloud.BuildDeps(cfg)
if deps.KMS == nil {
t.Fatal("deps.KMS: enabled kmssvc must give an in-process client, got nil")
t.Fatal("deps.KMS: enabled kms must give an in-process client, got nil")
}
// It must NOT be the fail-closed disabled stub — that stub returns IsDisabled
// errors; an in-process client (no master key) returns a master-key error.
+830
View File
@@ -0,0 +1,830 @@
// Package cek is cloud's ONE encryption-at-rest gate for its per-subsystem
// SQLite stores. Every store opens its database through cek.Open — the single
// seam where a plaintext file is transparently migrated to SQLCipher and a keyed
// *sql.DB is returned — so "encrypted at rest" is a property of the open path,
// not something each of the ~30 stores must remember to do.
//
// THREAT MODEL. The DO block volume under /var/lib/cloud is provider-encrypted,
// so the residual exposure is a COPIED PV snapshot/backup or an in-cluster
// exec/PV read seeing plaintext customer PII (crm), the ledger (treasury), org
// wallet maps (wallets), the audit log, team/entitlements. cek removes that
// exposure: each file's pages are SQLCipher-encrypted under a per-database key
// that never leaves the process in the clear and is itself wrapped by the
// KMS-injected master key; the pre-migration plaintext copy is shredded once the
// encrypted store is proven readable. A lifted file is useless without the key.
//
// SCOPE / NON-GOALS. cek provides CONFIDENTIALITY at rest against the read-only
// exposure above (no master key ⇒ no plaintext). It is NOT integrity,
// authenticity, or anti-rollback against a PV-WRITE (node-compromise) adversary
// who can modify the volume: the per-file id lives in the (unauthenticated) .dek
// sidecar, so such an adversary could swap two of OUR OWN {db,.dek} pairs or
// replay an old snapshot. That is outside the stated model and is deliberately
// NOT defended here (a logical-id+epoch binding would add complexity for an
// out-of-model threat); revisit only if tenant-isolation-under-node-compromise
// is scoped in.
//
// ENVELOPE (the primitives live in github.com/hanzoai/sqlite/cek.go and are
// reused verbatim — one crypto implementation, KAT-gated there):
//
// - Each database has its OWN random 256-bit DEK (the SQLCipher page key),
// minted once at first touch and NEVER changed, so ciphertext pages are
// never rewritten.
// - Each database also gets a random 128-bit FILE ID, stored in the clear at
// the head of its <db>.dek sidecar. The KEK is derived from that id, NOT the
// file path: KEK = HKDF-SHA256(masterKey, lp("global") || lp(hex(fileID))).
// The id is intrinsic to the file and travels with the sidecar, so moving
// the data dir or changing CLOUD_DATA_DIR can never change the KEK and brick
// a store. RFC-5869 HKDF via x/crypto/hkdf — NOT luxfi/crypto/kdf (a QZMQ
// KeySchedule, not generic HKDF; using it would brick every store).
// - The DEK is wrapped AES-256-GCM under the KEK, bound to the same id as AAD.
// Sidecar = fileID(16) || wrapped-DEK. The raw DEK is never written.
// - Master-key ROTATION rewraps only the sidecar: the DEK and fileID are
// unchanged, so no page is rewritten and no file can be bricked.
//
// FAIL-SECURE. On an encryption-CAPABLE build (production is CGO + libsqlcipher)
// a missing master key is FATAL — the data plane refuses to open unencrypted,
// the same posture the KMS store takes. A key set on a NON-encrypting build is
// likewise fatal. An encrypted file whose sidecar is missing is refused. A
// migration whose encrypted copy does not reproduce the source's schema AND
// per-table content (a rowid-independent multiset hash, not just a row count)
// leaves the plaintext untouched and errors — the caller (MountAll) fails
// closed, so cloud never serves a half-migrated data plane.
package cek
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
sqlitedrv "github.com/hanzoai/sqlite"
)
// masterKeyEnv is the ONE variable that supplies the 32-byte KMS master key
// (base64), matching the operator Deployment and clients/kms. No second gate.
const masterKeyEnv = "CLOUD_KMS_MASTER_KEY_REF"
const (
dekSuffix = ".dek" // sidecar: fileID(16) || wrapped-DEK
lockSuffix = ".cek.lock" // per-db flock guarding first-touch + migration
tmpSuffix = ".cek.tmp" // in-progress encrypted target (same volume → atomic rename)
plainBakSuffix = ".plain.bak" // transient pre-migration plaintext; SHREDDED after verified open
sqliteMagic = "SQLite format 3\x00" // 16-byte header of an UNENCRYPTED db
headerLen = 16
fileIDLen = 16 // random per-file KEK-derivation id, stored in the sidecar head
)
// principalType domain-separates cloud's platform databases from IAM's org/user
// stores in the shared HKDF namespace.
const principalType = sqlitedrv.PrincipalGlobal
var (
masterOnce sync.Once
masterKey []byte
masterErr error
masterOverride []byte
)
// SetMasterKey injects the 32-byte master key explicitly (cloud's boot resolves
// it once from cfg and hands it here), taking precedence over the environment.
// Call before the first Open. A wrong-length key is ignored so the env path can
// still apply.
func SetMasterKey(k []byte) {
if len(k) == 32 {
masterOverride = append([]byte(nil), k...)
}
}
// resolveMaster resolves the process master key exactly once:
//
// (key, nil) — 32-byte key AND an encryption-capable build → encrypt.
// (nil, nil) — no key AND a non-encrypting (pure-Go) build → dev/CI plaintext.
// (nil, error) — key malformed; OR key set on a non-encrypting build; OR NO key
// on an encryption-capable build. The last is the production
// fail-closed: a capable binary never silently ships plaintext.
func resolveMaster() ([]byte, error) {
masterOnce.Do(func() {
raw := masterOverride
if len(raw) == 0 {
b64 := strings.TrimSpace(os.Getenv(masterKeyEnv))
if b64 == "" {
if sqlitedrv.EncryptionAvailable() {
masterErr = fmt.Errorf("cek: %s is required on an encryption-capable build; "+
"refusing to open the data plane unencrypted (set the KMS master key, "+
"or run a pure-Go dev build)", masterKeyEnv)
}
return // pure-Go dev/CI: plaintext is expected (no codec linked)
}
decoded, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
masterErr = fmt.Errorf("cek: %s is not valid base64: %w", masterKeyEnv, err)
return
}
raw = decoded
}
if len(raw) != 32 {
masterErr = fmt.Errorf("cek: master key must decode to 32 bytes, got %d", len(raw))
return
}
if !sqlitedrv.EncryptionAvailable() {
masterErr = fmt.Errorf("cek: %s is set but this build cannot encrypt (pure-Go sqlite); "+
"rebuild CGO_ENABLED=1 linked against libsqlcipher, or unset it for a dev build", masterKeyEnv)
return
}
masterKey = raw
})
return masterKey, masterErr
}
// Encrypting reports whether cek will encrypt at rest (a valid master key is
// configured on an encryption-capable build). cloud calls this once at boot for
// the posture log; a false result on a capable build means resolveMaster errored
// and the first store Open will fail closed.
func Encrypting() bool {
k, err := resolveMaster()
return err == nil && len(k) == 32
}
// Open returns a *sql.DB for the SQLite database at path, encrypted at rest when
// a master key is configured. It is the single drop-in replacement for
// sql.Open("sqlite", path) across every cloud store.
func Open(path string) (*sql.DB, error) {
master, err := resolveMaster()
if err != nil {
return nil, err
}
if master == nil {
// Only reachable on a non-encrypting dev/CI build (a capable build with no
// key already errored above). Preserve the prior bare-path behavior.
return sql.Open("sqlite", path)
}
return openEncrypted(path, master)
}
func openEncrypted(path string, master []byte) (*sql.DB, error) {
unlock, err := flock(path)
if err != nil {
return nil, err
}
defer unlock()
if err := recoverInterrupted(path); err != nil {
return nil, err
}
var db *sql.DB
switch classify(path) {
case stateFresh:
db, err = createFresh(path, master)
case stateEncrypted:
db, err = openExisting(path, master)
default: // statePlaintext
db, err = migrateThenOpen(path, master)
}
if err != nil {
return nil, err
}
// No plaintext replica may survive a successful keyed open: shred any backup
// left by this (or a crashed prior) migration. THIS is the security objective.
shredPlainBak(path)
return db, nil
}
type fileState int
const (
stateFresh fileState = iota // absent or too small to be a real db → mint
statePlaintext // "SQLite format 3\0" header → migrate
stateEncrypted // db-sized, non-magic header → SQLCipher, open via sidecar
)
func classify(path string) fileState {
fi, err := os.Stat(path)
if err != nil || fi.Size() < headerLen {
return stateFresh
}
if isPlaintextHeader(path) {
return statePlaintext
}
return stateEncrypted
}
func isPlaintextHeader(path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer func() { _ = f.Close() }()
var hdr [headerLen]byte
if _, err := f.ReadAt(hdr[:], 0); err != nil {
return false
}
return string(hdr[:]) == sqliteMagic
}
// ── sidecar: fileID(16) || wrapped-DEK ───────────────────────────────────────
// mintSidecar generates a fresh fileID + DEK, wraps the DEK under the id-derived
// KEK, and returns the DEK and the sidecar bytes to persist.
func mintSidecar(master []byte) (dek, sidecar []byte, err error) {
fileID := make([]byte, fileIDLen)
if _, err = rand.Read(fileID); err != nil {
return nil, nil, fmt.Errorf("cek: generate file id: %w", err)
}
kek, aad, err := deriveFor(master, fileID)
if err != nil {
return nil, nil, err
}
defer zero(kek)
if dek, err = sqlitedrv.NewDEK(); err != nil {
return nil, nil, fmt.Errorf("cek: new DEK: %w", err)
}
wrapped, err := sqlitedrv.WrapDEK(kek, dek, aad)
if err != nil {
zero(dek)
return nil, nil, fmt.Errorf("cek: wrap DEK: %w", err)
}
sidecar = append(append(make([]byte, 0, fileIDLen+len(wrapped)), fileID...), wrapped...)
return dek, sidecar, nil
}
// unwrapSidecar reads the fileID from the sidecar head and unwraps the DEK under
// the id-derived KEK. A wrong master key, tampered blob, or truncated sidecar
// fails the GCM tag and errors — never a partial/garbage key.
func unwrapSidecar(master, sidecar []byte) ([]byte, error) {
if len(sidecar) <= fileIDLen {
return nil, fmt.Errorf("cek: sidecar too short (%d bytes)", len(sidecar))
}
fileID, wrapped := sidecar[:fileIDLen], sidecar[fileIDLen:]
kek, aad, err := deriveFor(master, fileID)
if err != nil {
return nil, err
}
defer zero(kek)
dek, err := sqlitedrv.UnwrapDEK(kek, wrapped, aad)
if err != nil {
return nil, fmt.Errorf("cek: unwrap DEK (wrong master key or corrupt sidecar): %w", err)
}
return dek, nil
}
// deriveFor derives the KEK and the wrap-AAD for a file id. Both bind to
// hex(fileID) so the id — not any path or config value — is the sole identity.
func deriveFor(master, fileID []byte) (kek, aad []byte, err error) {
id := hex.EncodeToString(fileID)
kek, err = sqlitedrv.DeriveKey(master, principalType, id)
if err != nil {
return nil, nil, fmt.Errorf("cek: derive KEK: %w", err)
}
return kek, sqlitedrv.PrincipalAAD(principalType, id), nil
}
// ── open paths ───────────────────────────────────────────────────────────────
func createFresh(path string, master []byte) (*sql.DB, error) {
dekPath := path + dekSuffix
if fileExists(dekPath) {
return openExisting(path, master) // a concurrent first-touch won the lock
}
dek, sidecar, err := mintSidecar(master)
if err != nil {
return nil, err
}
defer zero(dek)
if err := writeFileAtomic(dekPath, sidecar, 0o600); err != nil {
return nil, err
}
db, err := openKeyed(path, dek)
if err != nil {
return nil, fmt.Errorf("cek: create encrypted %q: %w", path, err)
}
return db, nil
}
func openExisting(path string, master []byte) (*sql.DB, error) {
dekPath := path + dekSuffix
sidecar, err := os.ReadFile(dekPath)
if err != nil {
return nil, fmt.Errorf("cek: read sidecar %q (encrypted db, refusing to open blind): %w", dekPath, err)
}
dek, err := unwrapSidecar(master, sidecar)
if err != nil {
return nil, err
}
defer zero(dek)
db, err := openKeyed(path, dek)
if err != nil {
return nil, fmt.Errorf("cek: open encrypted %q: %w", path, err)
}
return db, nil
}
// migrateThenOpen converts an existing PLAINTEXT database to SQLCipher without
// losing a row, then opens it. Crash-safe (plaintext is the source of truth
// until an atomic rename commits) and fail-secure (the swap happens only after
// the encrypted copy reproduces the source schema + per-table content hash +
// integrity_check, re-opened via the exact keyed path the app uses).
func migrateThenOpen(path string, master []byte) (*sql.DB, error) {
dekPath := path + dekSuffix
// Plaintext header ⇒ an earlier attempt did not commit: discard any stale
// sidecar/tmp and redo from the plaintext source of truth.
_ = os.Remove(dekPath)
tmp := path + tmpSuffix
removeDBFiles(tmp)
dek, sidecar, err := mintSidecar(master)
if err != nil {
return nil, err
}
defer zero(dek)
srcInv, err := exportPlaintext(path, tmp, dek)
if err != nil {
removeDBFiles(tmp)
return nil, err
}
if isPlaintextHeader(tmp) {
removeDBFiles(tmp)
return nil, fmt.Errorf("cek: migration of %q produced a plaintext file (SQLCipher not linked?)", path)
}
if err := verifyParity(tmp, dek, srcInv); err != nil {
removeDBFiles(tmp)
return nil, fmt.Errorf("cek: migration parity check failed for %q (plaintext left intact): %w", path, err)
}
// Commit. Order for crash-safety:
// 1. sidecar (the encrypted db's key),
// 2. plaintext → <db>.plain.bak,
// 3. delete the now-orphaned plaintext -wal/-shm (WAL was checkpoint-folded
// into the main file, so .plain.bak is complete; removing them now closes
// the window where a stale plaintext WAL sits beside the encrypted db),
// 4. atomic rename tmp → path.
// A crash between any two steps is resolved by recoverInterrupted on reboot.
if err := writeFileAtomic(dekPath, sidecar, 0o600); err != nil {
removeDBFiles(tmp)
return nil, err
}
if err := os.Rename(path, path+plainBakSuffix); err != nil {
removeDBFiles(tmp)
_ = os.Remove(dekPath)
return nil, fmt.Errorf("cek: preserve plaintext backup for %q: %w", path, err)
}
_ = os.Remove(path + "-wal")
_ = os.Remove(path + "-shm")
if err := os.Rename(tmp, path); err != nil {
_ = os.Rename(path+plainBakSuffix, path) // roll back
_ = os.Remove(dekPath)
return nil, fmt.Errorf("cek: swap encrypted %q into place: %w", path, err)
}
syncDir(filepath.Dir(path))
db, err := openKeyed(path, dek)
if err != nil {
return nil, fmt.Errorf("cek: open migrated %q: %w", path, err)
}
return db, nil // openEncrypted's tail shreds .plain.bak after this succeeds
}
// exportPlaintext opens the plaintext source, folds its WAL into the main file
// (crm.db/audit.db carry MB of live WAL), records the source inventory for the
// parity check, and copies every page into a fresh SQLCipher database at tmp via
// SQLCipher's own sqlcipher_export with the format compat pinned. The source is
// only read.
func exportPlaintext(path, tmp string, dek []byte) (inventory, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
src, err := sql.Open("sqlite", sqlitedrv.DSN(path, nil))
if err != nil {
return inventory{}, fmt.Errorf("cek: open plaintext %q: %w", path, err)
}
defer func() { _ = src.Close() }()
src.SetMaxOpenConns(1) // ATTACH + sqlcipher_export must run on ONE connection
conn, err := src.Conn(ctx)
if err != nil {
return inventory{}, fmt.Errorf("cek: acquire conn for %q: %w", path, err)
}
defer func() { _ = conn.Close() }()
if _, err := conn.ExecContext(ctx, "PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
return inventory{}, fmt.Errorf("cek: checkpoint %q: %w", path, err)
}
srcInv, err := readInventory(ctx, conn)
if err != nil {
return inventory{}, fmt.Errorf("cek: inventory source %q: %w", path, err)
}
// The DEK is crypto/rand hex — no injection surface; the path is a bound
// parameter. The reopen-via-openKeyed parity check downstream is the
// authoritative guard that the copy opens under the app's exact keyed path.
// The target is created at the runtime's SQLCipher format (the frozen
// libsqlcipher default), which is exactly what openKeyed reopens it under.
attach := fmt.Sprintf(`ATTACH DATABASE ? AS enc KEY "x'%x'"`, dek)
if _, err := conn.ExecContext(ctx, attach, tmp); err != nil {
return inventory{}, fmt.Errorf("cek: attach encrypted target: %w", err)
}
if _, err := conn.ExecContext(ctx, "SELECT sqlcipher_export('enc')"); err != nil {
_, _ = conn.ExecContext(ctx, "DETACH DATABASE enc")
return inventory{}, fmt.Errorf("cek: sqlcipher_export: %w", err)
}
if _, err := conn.ExecContext(ctx, "DETACH DATABASE enc"); err != nil {
return inventory{}, fmt.Errorf("cek: detach encrypted target: %w", err)
}
return srcInv, nil
}
// verifyParity re-opens the encrypted copy exactly as the running app will
// (openKeyed) and asserts: integrity_check ok, identical schema fingerprint, and
// — per table — identical row count AND identical rowid-independent content hash.
// The content hash (a commutative multiset sum of per-row hashes over the USER
// columns) is what backs the zero-loss claim: it catches any value change, NULL
// coercion, or row add/drop that count + schema + integrity_check miss, while
// correctly ignoring the benign implicit-rowid renumbering sqlcipher_export does.
// It runs BEFORE the atomic swap, so any discrepancy leaves the plaintext intact.
func verifyParity(tmp string, dek []byte, src inventory) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
db, err := openKeyed(tmp, dek)
if err != nil {
return fmt.Errorf("reopen encrypted copy: %w", err)
}
defer func() { _ = db.Close() }()
db.SetMaxOpenConns(1)
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("ping encrypted copy (key/compat mismatch?): %w", err)
}
var ic string
if err := db.QueryRowContext(ctx, "PRAGMA integrity_check").Scan(&ic); err != nil {
return fmt.Errorf("integrity_check: %w", err)
}
if ic != "ok" {
return fmt.Errorf("integrity_check returned %q", ic)
}
conn, err := db.Conn(ctx)
if err != nil {
return fmt.Errorf("acquire verify conn: %w", err)
}
defer func() { _ = conn.Close() }()
dst, err := readInventory(ctx, conn)
if err != nil {
return fmt.Errorf("inventory encrypted copy: %w", err)
}
if dst.schema != src.schema {
return fmt.Errorf("schema fingerprint mismatch")
}
if len(dst.tables) != len(src.tables) {
return fmt.Errorf("table set mismatch: src %d tables, dst %d", len(src.tables), len(dst.tables))
}
for tbl, s := range src.tables {
d, ok := dst.tables[tbl]
if !ok {
return fmt.Errorf("table %q missing in encrypted copy", tbl)
}
if d.count != s.count {
return fmt.Errorf("row-count mismatch in %q: src %d, dst %d", tbl, s.count, d.count)
}
if d.content != s.content {
return fmt.Errorf("content-hash mismatch in %q (row values differ despite equal count)", tbl)
}
}
return nil
}
// inventory is the parity fingerprint: a schema hash plus, per table, a row count
// and a content hash.
type inventory struct {
schema [32]byte
tables map[string]tableStat
}
type tableStat struct {
count int64
content [32]byte // commutative multiset sum of per-row hashes over user columns
}
func readInventory(ctx context.Context, conn *sql.Conn) (inventory, error) {
rows, err := conn.QueryContext(ctx,
`SELECT type,name,COALESCE(tbl_name,''),COALESCE(sql,'') FROM sqlite_master `+
`WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name`)
if err != nil {
return inventory{}, err
}
var schemaLines, tables []string
for rows.Next() {
var typ, name, tbl, ddl string
if err := rows.Scan(&typ, &name, &tbl, &ddl); err != nil {
_ = rows.Close()
return inventory{}, err
}
schemaLines = append(schemaLines, typ+"\x1f"+name+"\x1f"+tbl+"\x1f"+ddl)
if typ == "table" {
tables = append(tables, name)
}
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return inventory{}, err
}
_ = rows.Close()
sort.Strings(schemaLines)
h := sha256.New()
for _, l := range schemaLines {
writeLP(h, []byte(l))
}
inv := inventory{tables: make(map[string]tableStat, len(tables))}
copy(inv.schema[:], h.Sum(nil))
for _, tbl := range tables {
st, err := tableContent(ctx, conn, tbl)
if err != nil {
return inventory{}, fmt.Errorf("content %q: %w", tbl, err)
}
inv.tables[tbl] = st
}
return inv, nil
}
// tableContent streams every row of a table and folds a per-row hash (over the
// user columns, faithfully distinguishing NULL / "" / 0 / storage class) into a
// commutative 256-bit sum. Order-independent (survives rowid-driven scan-order
// differences) and duplicate-safe (addition, not XOR). O(1) memory per table.
func tableContent(ctx context.Context, conn *sql.Conn, tbl string) (tableStat, error) {
q := `SELECT * FROM "` + strings.ReplaceAll(tbl, `"`, `""`) + `"`
rows, err := conn.QueryContext(ctx, q)
if err != nil {
return tableStat{}, err
}
defer func() { _ = rows.Close() }()
cols, err := rows.Columns()
if err != nil {
return tableStat{}, err
}
var st tableStat
scan := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range scan {
ptrs[i] = &scan[i]
}
for rows.Next() {
if err := rows.Scan(ptrs...); err != nil {
return tableStat{}, err
}
rh := sha256.New()
for _, v := range scan {
encodeValue(rh, v)
}
var row [32]byte
copy(row[:], rh.Sum(nil))
addInto(&st.content, row)
st.count++
}
return st, rows.Err()
}
// encodeValue writes a type-tagged, length-prefixed, NULL-sentinel encoding of a
// scanned SQLite value so two logically-equal rows hash identically and a NULL
// never collides with "" or 0.
func encodeValue(h hash.Hash, v any) {
switch x := v.(type) {
case nil:
h.Write([]byte{0})
case int64:
var b [8]byte
binary.BigEndian.PutUint64(b[:], uint64(x))
h.Write([]byte{1})
h.Write(b[:])
case float64:
var b [8]byte
binary.BigEndian.PutUint64(b[:], math.Float64bits(x))
h.Write([]byte{2})
h.Write(b[:])
case bool:
h.Write([]byte{3})
if x {
h.Write([]byte{1})
} else {
h.Write([]byte{0})
}
case []byte:
h.Write([]byte{4})
writeLP(h, x)
case string:
h.Write([]byte{5})
writeLP(h, []byte(x))
case time.Time:
h.Write([]byte{6})
var b [8]byte
binary.BigEndian.PutUint64(b[:], uint64(x.UnixNano()))
h.Write(b[:])
default:
h.Write([]byte{9})
writeLP(h, []byte(fmt.Sprintf("%v", x)))
}
}
// writeLP writes an 8-byte big-endian length prefix then the bytes, so
// concatenations are unambiguous.
func writeLP(h hash.Hash, b []byte) {
var n [8]byte
binary.BigEndian.PutUint64(n[:], uint64(len(b)))
h.Write(n[:])
h.Write(b)
}
// addInto computes acc = (acc + row) mod 2^256, big-endian — the commutative,
// duplicate-safe multiset combiner.
func addInto(acc *[32]byte, row [32]byte) {
var carry uint16
for i := 31; i >= 0; i-- {
s := uint16(acc[i]) + uint16(row[i]) + carry
acc[i] = byte(s)
carry = s >> 8
}
}
// recoverInterrupted resumes a migration that crashed between the commit steps,
// keying only on files (no config). It also scrubs any stale plaintext -wal/-shm
// so a half-committed state can never leave one beside an encrypted db.
func recoverInterrupted(path string) error {
dekPath := path + dekSuffix
tmp := path + tmpSuffix
if fileExists(path) {
// If the live file is already encrypted, a leftover tmp is a dead
// migration attempt — discard it. (A plaintext live file is handled by
// migrateThenOpen, which clears tmp itself.)
if !isPlaintextHeader(path) {
removeDBFiles(tmp)
}
return nil
}
switch {
case fileExists(tmp) && fileExists(dekPath):
// Crashed after the sidecar+backup were written but before/during the swap
// rename: finish it. The sidecar matches tmp.
if err := os.Rename(tmp, path); err != nil {
return fmt.Errorf("cek: resume migration swap for %q: %w", path, err)
}
_ = os.Remove(path + "-wal")
_ = os.Remove(path + "-shm")
syncDir(filepath.Dir(path))
case fileExists(path + plainBakSuffix):
// Swap never happened; restore the plaintext original for a clean redo.
if err := os.Rename(path+plainBakSuffix, path); err != nil {
return fmt.Errorf("cek: restore plaintext backup for %q: %w", path, err)
}
removeDBFiles(tmp)
_ = os.Remove(dekPath)
}
return nil
}
// openKeyed opens a keyed SQLCipher database via the driver's ONE blessed keyed
// open (the key rides the URI so it is applied at sqlite3_open_v2, before mattn's
// pragma battery touches the header — a post-open PRAGMA key would be too late).
//
// CROSS-VERSION SAFETY. SQLCipher's on-disk format is fixed by the libsqlcipher
// major the arcd image links; that version is FROZEN in the Dockerfile (see the
// runbook) so an image rebuild cannot silently change the default cipher format
// and orphan a store. An at-open `cipher_compatibility` pin is NOT usable here
// (the URI param is silently ignored, and a post-open pragma runs after mattn has
// already read the header) — the version freeze is the control. If a mismatch
// ever occurs it FAILS CLOSED: openExisting returns "file is not a database" and
// MountAll aborts — never a silent downgrade or corruption.
func openKeyed(path string, dek []byte) (*sql.DB, error) {
db, err := sqlitedrv.OpenDB(path, dek)
if err != nil {
return nil, fmt.Errorf("cek: open keyed %q: %w", path, err) // no dsn (holds key)
}
return db, nil
}
// ── shred + boring helpers ───────────────────────────────────────────────────
// shredPlainBak overwrites and removes the transient pre-migration plaintext
// backup once the encrypted store is proven readable. Overwrite-then-remove is
// defense-in-depth (best-effort on a copy-on-write/journalled fs; the block
// volume is provider-encrypted regardless). Idempotent no-op when absent.
func shredPlainBak(path string) {
bak := path + plainBakSuffix
fi, err := os.Stat(bak)
if err != nil {
return
}
if f, err := os.OpenFile(bak, os.O_WRONLY, 0); err == nil {
overwrite(f, fi.Size())
_ = f.Sync()
_ = f.Close()
}
_ = os.Remove(bak)
}
func overwrite(f *os.File, size int64) {
const chunk = 1 << 20
buf := make([]byte, chunk)
for remaining := size; remaining > 0; {
n := int64(chunk)
if remaining < n {
n = remaining
}
if _, err := rand.Read(buf[:n]); err != nil {
return
}
if _, err := f.Write(buf[:n]); err != nil {
return
}
remaining -= n
}
}
func fileExists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
func removeDBFiles(base string) {
for _, s := range []string{"", "-wal", "-shm"} {
_ = os.Remove(base + s)
}
}
func writeFileAtomic(dst string, data []byte, perm os.FileMode) error {
tmp := dst + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return fmt.Errorf("cek: create %q: %w", tmp, err)
}
if _, err := f.Write(data); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return fmt.Errorf("cek: write %q: %w", tmp, err)
}
if err := f.Sync(); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return fmt.Errorf("cek: sync %q: %w", tmp, err)
}
if err := f.Close(); err != nil {
_ = os.Remove(tmp)
return fmt.Errorf("cek: close %q: %w", tmp, err)
}
if err := os.Rename(tmp, dst); err != nil {
_ = os.Remove(tmp)
return fmt.Errorf("cek: rename %q→%q: %w", tmp, dst, err)
}
return nil
}
func syncDir(dir string) {
if d, err := os.Open(dir); err == nil {
_ = d.Sync()
_ = d.Close()
}
}
// flock takes an exclusive advisory lock on <path>.cek.lock, serializing
// first-touch and migration for the SAME database across processes/goroutines
// (different databases never contend). Returns an unlock func.
func flock(path string) (func(), error) {
lockPath := path + lockSuffix
if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
return nil, fmt.Errorf("cek: create lock dir: %w", err)
}
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, fmt.Errorf("cek: open lock %q: %w", lockPath, err)
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
_ = f.Close()
return nil, fmt.Errorf("cek: acquire lock %q: %w", lockPath, err)
}
return func() {
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
_ = f.Close()
}, nil
}
func zero(b []byte) {
for i := range b {
b[i] = 0
}
}
+439
View File
@@ -0,0 +1,439 @@
package cek
import (
"context"
"database/sql"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
sqlitedrv "github.com/hanzoai/sqlite"
)
// resetMaster clears the once-resolved master so a test can choose a posture.
// White-box tests only; production never resets.
func resetMaster(key []byte) {
masterOnce = sync.Once{}
masterKey = nil
masterErr = nil
masterOverride = nil
if key != nil {
SetMasterKey(key)
}
}
func testMaster(t *testing.T) []byte {
t.Helper()
k := make([]byte, 32)
for i := range k {
k[i] = byte(i*7 + 1)
}
return k
}
// requireCipher skips when the build cannot produce REAL ciphertext (a mis-linked
// cgo build silently writes plaintext), probing rather than trusting the flag.
// With SQLITE_REQUIRE_CODEC=1 (the Docker image build sets it) a would-be skip
// becomes a FAILURE, so the in-image gate is airtight standalone.
func requireCipher(t *testing.T) {
t.Helper()
skipOrFail := func(msg string) {
if os.Getenv("SQLITE_REQUIRE_CODEC") == "1" {
t.Fatal(msg)
}
t.Skip(msg)
}
if !sqlitedrv.EncryptionAvailable() {
skipOrFail("sqlite build cannot encrypt (pure-Go); run with CGO + libsqlcipher")
return
}
probe := filepath.Join(t.TempDir(), "probe.db")
dek, _ := sqlitedrv.NewDEK()
db, err := openKeyed(probe, dek)
if err != nil {
t.Fatalf("probe open: %v", err)
}
if _, err := db.Exec(`CREATE TABLE t(x)`); err != nil {
t.Fatalf("probe ddl: %v", err)
}
_ = db.Close()
if isPlaintextHeader(probe) {
skipOrFail("cgo build is NOT linked against libsqlcipher (keyed db is plaintext)")
return
}
}
// makePlaintextDB writes a genuine UNENCRYPTED SQLite db with known rows in WAL
// mode (exercising exportPlaintext's WAL fold), returning per-table row counts.
func makePlaintextDB(t *testing.T, path string, companies, contacts int) map[string]int64 {
t.Helper()
db, err := sql.Open("sqlite", path)
if err != nil {
t.Fatalf("open plaintext: %v", err)
}
for _, p := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0"} {
if _, err := db.Exec(p); err != nil {
t.Fatalf("pragma %q: %v", p, err)
}
}
if _, err := db.Exec(`
CREATE TABLE crm_companies(id TEXT PRIMARY KEY, org TEXT, name TEXT, arr INTEGER);
CREATE INDEX ix_co_org ON crm_companies(org);
CREATE TABLE crm_contacts(id TEXT PRIMARY KEY, org TEXT, email TEXT, note TEXT);`); err != nil {
t.Fatalf("ddl: %v", err)
}
for i := 0; i < companies; i++ {
if _, err := db.Exec(`INSERT INTO crm_companies VALUES(?,?,?,?)`,
fmt.Sprintf("co-%d", i), "maxpower", fmt.Sprintf("Co %d", i), int64(i*1000)); err != nil {
t.Fatalf("insert company: %v", err)
}
}
for i := 0; i < contacts; i++ {
// note is NULL on evens to exercise NULL fidelity in the content hash.
if i%2 == 0 {
_, err = db.Exec(`INSERT INTO crm_contacts(id,org,email) VALUES(?,?,?)`,
fmt.Sprintf("ct-%d", i), "maxpower", fmt.Sprintf("u%d@x.io", i))
} else {
_, err = db.Exec(`INSERT INTO crm_contacts VALUES(?,?,?,?)`,
fmt.Sprintf("ct-%d", i), "maxpower", fmt.Sprintf("u%d@x.io", i), "vip")
}
if err != nil {
t.Fatalf("insert contact: %v", err)
}
}
if !isPlaintextHeader(path) {
t.Fatalf("precondition: freshly created db is not plaintext")
}
_ = db.Close()
return map[string]int64{"crm_companies": int64(companies), "crm_contacts": int64(contacts)}
}
func rowCount(t *testing.T, db *sql.DB, table string) int64 {
t.Helper()
var n int64
if err := db.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil {
t.Fatalf("count %s: %v", table, err)
}
return n
}
func firstBytes(t *testing.T, path string, n int) []byte {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatalf("open %s: %v", path, err)
}
defer func() { _ = f.Close() }()
b := make([]byte, n)
if _, err := f.ReadAt(b, 0); err != nil {
t.Fatalf("read %s: %v", path, err)
}
return b
}
// TestMigratePlaintextToCipher is the keystone: plaintext → SQLCipher with a
// ciphertext header, exact row parity, an unwrappable sidecar, readable data,
// and — per RED HIGH — NO surviving plaintext backup (shredded after verify).
func TestMigratePlaintextToCipher(t *testing.T) {
requireCipher(t)
dir := t.TempDir()
path := filepath.Join(dir, "crm.db")
want := makePlaintextDB(t, path, 37, 91)
resetMaster(testMaster(t))
db, err := Open(path)
if err != nil {
t.Fatalf("cek.Open (migrate): %v", err)
}
defer func() { _ = db.Close() }()
if isPlaintextHeader(path) {
t.Fatalf("FAIL: %s still plaintext after migration", path)
}
t.Logf("migrated header (hex): %s", hex.EncodeToString(firstBytes(t, path, 16)))
for tbl, n := range want {
if got := rowCount(t, db, tbl); got != n {
t.Errorf("row-count mismatch %s: want %d got %d", tbl, n, got)
}
}
// sidecar unwraps under the id-derived KEK (path plays no role).
sidecar, err := os.ReadFile(path + dekSuffix)
if err != nil {
t.Fatalf("read sidecar: %v", err)
}
if dek, err := unwrapSidecar(testMaster(t), sidecar); err != nil || len(dek) != 32 {
t.Fatalf("unwrap sidecar: dek=%d err=%v", len(dek), err)
}
// RED HIGH: the plaintext backup must be GONE (shredded), not lingering.
if fileExists(path + plainBakSuffix) {
t.Errorf("SECURITY: plaintext backup %s survived migration (must be shredded)", path+plainBakSuffix)
}
var name string
if err := db.QueryRow(`SELECT name FROM crm_companies WHERE id='co-5'`).Scan(&name); err != nil || name != "Co 5" {
t.Errorf("content check: got %q err %v", name, err)
}
}
// TestOpenIdempotent: a second Open of an already-migrated db is a no-op.
func TestOpenIdempotent(t *testing.T) {
requireCipher(t)
path := filepath.Join(t.TempDir(), "treasury.db")
want := makePlaintextDB(t, path, 5, 5)
resetMaster(testMaster(t))
db1, err := Open(path)
if err != nil {
t.Fatalf("first open: %v", err)
}
_ = db1.Close()
hdr1 := firstBytes(t, path, 16)
db2, err := Open(path)
if err != nil {
t.Fatalf("second open: %v", err)
}
defer func() { _ = db2.Close() }()
if isPlaintextHeader(path) {
t.Fatalf("db became plaintext on reopen")
}
for tbl, n := range want {
if got := rowCount(t, db2, tbl); got != n {
t.Errorf("reopen row-count %s: want %d got %d", tbl, n, got)
}
}
if string(hdr1) != string(firstBytes(t, path, 16)) {
t.Errorf("header changed on reopen (pages rewritten?)")
}
}
// TestFreshCreateEncrypted: a brand-new db is born encrypted.
func TestFreshCreateEncrypted(t *testing.T) {
requireCipher(t)
path := filepath.Join(t.TempDir(), "wallets.db")
resetMaster(testMaster(t))
db, err := Open(path)
if err != nil {
t.Fatalf("open fresh: %v", err)
}
if _, err := db.Exec(`CREATE TABLE w(addr TEXT, org TEXT)`); err != nil {
t.Fatalf("ddl: %v", err)
}
_ = db.Close()
if isPlaintextHeader(path) {
t.Fatalf("fresh db is plaintext")
}
if !fileExists(path + dekSuffix) {
t.Fatalf("fresh db has no sidecar")
}
}
// TestWrongMasterFailsClosed: a sidecar minted under one master cannot open under
// another — a lifted file + wrong key yields an error, never plaintext.
func TestWrongMasterFailsClosed(t *testing.T) {
requireCipher(t)
path := filepath.Join(t.TempDir(), "audit.db")
makePlaintextDB(t, path, 3, 3)
resetMaster(testMaster(t))
db, err := Open(path)
if err != nil {
t.Fatalf("migrate: %v", err)
}
_ = db.Close()
other := make([]byte, 32)
for i := range other {
other[i] = 0xAB
}
resetMaster(other)
if _, err := Open(path); err == nil {
t.Fatalf("SECURITY: opened encrypted db under the WRONG master key")
}
}
// TestDataDirMoveNoBrick (RED MED #2, PoC): the KEK binds to the sidecar fileID,
// NOT CLOUD_DATA_DIR, so changing/unsetting the data dir — or moving the file to
// a different path — must NOT brick the store.
func TestDataDirMoveNoBrick(t *testing.T) {
requireCipher(t)
dir1 := t.TempDir()
pathA := filepath.Join(dir1, "crm.db")
want := makePlaintextDB(t, pathA, 8, 8)
t.Setenv("CLOUD_DATA_DIR", dir1)
resetMaster(testMaster(t))
db, err := Open(pathA)
if err != nil {
t.Fatalf("migrate under dir1: %v", err)
}
_ = db.Close()
// Simulate a data-dir change AND a physical move to a different filename.
dir2 := t.TempDir()
pathB := filepath.Join(dir2, "moved.db")
copyFile(t, pathA, pathB)
copyFile(t, pathA+dekSuffix, pathB+dekSuffix)
t.Setenv("CLOUD_DATA_DIR", "/some/other/root") // the old brick trigger
db2, err := Open(pathB) // KEK from fileID → must still open
if err != nil {
t.Fatalf("AVAILABILITY: data-dir change bricked the store: %v", err)
}
defer func() { _ = db2.Close() }()
for tbl, n := range want {
if got := rowCount(t, db2, tbl); got != n {
t.Errorf("moved db row-count %s: want %d got %d", tbl, n, got)
}
}
}
// TestMissingKeyFatalOnCapableBuild (RED MED #3): an encryption-capable build
// with NO master key must FAIL CLOSED, never silently open plaintext. On a
// pure-Go build the same absence is dev-mode plaintext.
func TestMissingKeyFatalOnCapableBuild(t *testing.T) {
path := filepath.Join(t.TempDir(), "settings.db")
resetMaster(nil)
os.Unsetenv(masterKeyEnv)
_, err := Open(path)
if sqlitedrv.EncryptionAvailable() {
if err == nil {
t.Fatalf("SECURITY: capable build opened the data plane with NO master key (silent plaintext)")
}
if fileExists(path) {
t.Fatalf("SECURITY: a db file was created despite the fatal missing-key error")
}
} else {
if err != nil {
t.Fatalf("pure-Go dev build should allow plaintext when no key: %v", err)
}
}
}
// TestContentHashCatchesMutation (RED MED #4): the content hash catches a value
// change that row-count + schema + integrity_check all miss, AND does NOT
// false-positive on the benign implicit-rowid renumbering sqlcipher_export does.
func TestContentHashCatchesMutation(t *testing.T) {
requireCipher(t)
a := filepath.Join(t.TempDir(), "a.db")
b := filepath.Join(t.TempDir(), "b.db")
makePlaintextDB(t, a, 10, 10)
makePlaintextDB(t, b, 10, 10)
if inventoryOf(t, a).tables["crm_contacts"].content != inventoryOf(t, b).tables["crm_contacts"].content {
t.Fatalf("identical data produced different content hashes")
}
// Mutate ONE value in b (same row count, same schema, integrity stays ok).
base := inventoryOf(t, a).tables["crm_contacts"]
mutate(t, b, `UPDATE crm_contacts SET email='HIJACKED' WHERE id='ct-3'`)
after := inventoryOf(t, b).tables["crm_contacts"]
if after.count != base.count {
t.Fatalf("mutation changed the row count; test would not isolate content")
}
if base.content == after.content {
t.Fatalf("SECURITY: content hash did NOT catch a value mutation (count-blind gate)")
}
// Benign rowid renumber (delete+reinsert identical row, VACUUM) must NOT change it.
c := filepath.Join(t.TempDir(), "c.db")
makePlaintextDB(t, c, 10, 10)
before := inventoryOf(t, c).tables["crm_contacts"].content
mutate(t, c, `DELETE FROM crm_contacts WHERE id='ct-0'; INSERT INTO crm_contacts(id,org,email) VALUES('ct-0','maxpower','u0@x.io'); VACUUM`)
if before != inventoryOf(t, c).tables["crm_contacts"].content {
t.Errorf("content hash false-positived on a rowid renumber (re-inserted identical row)")
}
}
// TestCorruptSidecarFailsClosed (RED re-test #5, safety net): any undecryptable
// state — a corrupted or missing .dek sidecar, the family a libsqlcipher format
// mismatch would land in — FAILS CLOSED (errors), never silently opening
// plaintext or a garbage db. (Cross-version format stability itself is enforced
// by freezing the libsqlcipher version in the build; an at-open cipher_compat
// pin is infeasible with mattn's URI-key requirement — see openKeyed.)
func TestCorruptSidecarFailsClosed(t *testing.T) {
requireCipher(t)
path := filepath.Join(t.TempDir(), "audit.db")
makePlaintextDB(t, path, 4, 4)
resetMaster(testMaster(t))
db, err := Open(path)
if err != nil {
t.Fatalf("migrate: %v", err)
}
_ = db.Close()
// Flip a byte in the wrapped-DEK region of the sidecar → GCM tag fails.
sc, err := os.ReadFile(path + dekSuffix)
if err != nil {
t.Fatalf("read sidecar: %v", err)
}
sc[len(sc)-1] ^= 0xFF
if err := os.WriteFile(path+dekSuffix, sc, 0o600); err != nil {
t.Fatalf("write sidecar: %v", err)
}
resetMaster(testMaster(t))
if _, err := Open(path); err == nil {
t.Fatalf("SECURITY: opened an encrypted db with a corrupted DEK sidecar")
}
// A missing sidecar over an encrypted db must also refuse (never open blind).
if err := os.Remove(path + dekSuffix); err != nil {
t.Fatalf("rm sidecar: %v", err)
}
resetMaster(testMaster(t))
if _, err := Open(path); err == nil {
t.Fatalf("SECURITY: opened an encrypted db with NO DEK sidecar")
}
}
// ── helpers ──────────────────────────────────────────────────────────────────
func inventoryOf(t *testing.T, path string) inventory {
t.Helper()
db, err := sql.Open("sqlite", sqlitedrv.DSN(path, nil))
if err != nil {
t.Fatalf("open for inventory: %v", err)
}
defer func() { _ = db.Close() }()
db.SetMaxOpenConns(1)
conn, err := db.Conn(context.Background())
if err != nil {
t.Fatalf("conn: %v", err)
}
defer func() { _ = conn.Close() }()
inv, err := readInventory(context.Background(), conn)
if err != nil {
t.Fatalf("readInventory: %v", err)
}
return inv
}
func mutate(t *testing.T, path, sqlText string) {
t.Helper()
db, err := sql.Open("sqlite", sqlitedrv.DSN(path, nil))
if err != nil {
t.Fatalf("open mutate: %v", err)
}
defer func() { _ = db.Close() }()
if _, err := db.Exec(sqlText); err != nil {
t.Fatalf("mutate %q: %v", sqlText, err)
}
}
func copyFile(t *testing.T, src, dst string) {
t.Helper()
b, err := os.ReadFile(src)
if err != nil {
t.Fatalf("read %s: %v", src, err)
}
if err := os.WriteFile(dst, b, 0o600); err != nil {
t.Fatalf("write %s: %v", dst, err)
}
}
+100
View File
@@ -0,0 +1,100 @@
package cek
import (
"os"
"path/filepath"
"testing"
)
// The frozen fixture pins the SQLCipher on-disk FORMAT the data plane is written
// with. A committed encrypted store (created under the build's frozen
// libsqlcipher) is opened by TestFrozenFixtureOpens; if a future libsqlcipher
// upgrade changes the default cipher format, opening a store written under the
// old format FAILS — turning a silent prod brick into a red CI. (Build-time
// SQLITE_REQUIRE_CODEC only proves a FRESH db encrypts; it cannot detect a format
// change against pre-existing stores — the fixture is what does.)
const frozenCanary = "cek-format-canary-v1"
// frozenMaster is a FIXED, obviously-fake test key (0x00..0x1f) used only to wrap
// the committed fixture's DEK. Not a secret; never used in production.
func frozenMaster() []byte {
k := make([]byte, 32)
for i := range k {
k[i] = byte(i)
}
return k
}
const frozenDir = "testdata/frozen"
// TestGenerateFrozenFixture (re)writes the committed fixture. Gated on
// CEK_GEN_FIXTURE=1 and run by hand ONLY when the format is intentionally rev'd;
// the committed bytes are otherwise frozen.
func TestGenerateFrozenFixture(t *testing.T) {
if os.Getenv("CEK_GEN_FIXTURE") != "1" {
t.Skip("set CEK_GEN_FIXTURE=1 to regenerate the frozen fixture")
}
requireCipher(t)
if err := os.MkdirAll(frozenDir, 0o755); err != nil {
t.Fatal(err)
}
dbPath := filepath.Join(frozenDir, "store.db")
for _, s := range []string{"", dekSuffix, "-wal", "-shm"} {
_ = os.Remove(dbPath + s)
}
dek, sidecar, err := mintSidecar(frozenMaster())
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dbPath+dekSuffix, sidecar, 0o600); err != nil {
t.Fatal(err)
}
h, err := openKeyed(dbPath, dek)
if err != nil {
t.Fatal(err)
}
if _, err := h.Exec(`CREATE TABLE frozen(id INTEGER PRIMARY KEY, note TEXT)`); err != nil {
t.Fatal(err)
}
if _, err := h.Exec(`INSERT INTO frozen VALUES(1,?)`, frozenCanary); err != nil {
t.Fatal(err)
}
_, _ = h.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`) // fold into the main .db
_ = h.Close()
_ = os.Remove(dbPath + "-wal")
_ = os.Remove(dbPath + "-shm")
if isPlaintextHeader(dbPath) {
t.Fatal("generated fixture is plaintext")
}
t.Logf("wrote frozen fixture %s (+%s)", dbPath, dekSuffix)
}
// TestFrozenFixtureOpens opens the COMMITTED encrypted fixture (copied to temp so
// the committed bytes are never mutated) and reads its canary row. A libsqlcipher
// format change makes this fail — a red CI instead of a silent prod brick.
func TestFrozenFixtureOpens(t *testing.T) {
requireCipher(t)
src := filepath.Join(frozenDir, "store.db")
if !fileExists(src) {
t.Fatal("frozen fixture missing — regenerate with CEK_GEN_FIXTURE=1 and commit testdata/frozen/")
}
dir := t.TempDir()
dst := filepath.Join(dir, "store.db")
copyFile(t, src, dst)
copyFile(t, src+dekSuffix, dst+dekSuffix)
resetMaster(frozenMaster())
db, err := Open(dst)
if err != nil {
t.Fatalf("FORMAT DRIFT: frozen fixture failed to open (libsqlcipher format changed?): %v", err)
}
defer func() { _ = db.Close() }()
var note string
if err := db.QueryRow(`SELECT note FROM frozen WHERE id=1`).Scan(&note); err != nil {
t.Fatalf("read canary: %v", err)
}
if note != frozenCanary {
t.Fatalf("canary mismatch: got %q want %q", note, frozenCanary)
}
}
BIN
View File
Binary file not shown.
Binary file not shown.
+74
View File
@@ -0,0 +1,74 @@
package cli
// agent.go — `hanzo agent`: invoke a managed Hanzo agent with a task.
//
// An agent is a managed capability (its own /v1/agents subsystem, self-metered),
// NOT your artifact — so it is a peer verb of `hanzo run`, not a run kind. This is
// the HEADLESS flavor: a task/tool/code agent, no computer. The computer-using
// flavor (a booted desktop/terminal) is `hanzo bot` (see bot.go).
//
// hanzo agent run <ref> "<task>" → POST /v1/agents/:ref/run
//
// Thin client: one authenticated call over the IAM token + env.CloudURL, reusing
// cloudCall (run.go). See docs/architecture/compute-ladder.md.
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/spf13/cobra"
)
// AgentRunReq is the POST /v1/agents/:ref/run body — a task for a managed agent.
type AgentRunReq struct {
Task string `json:"task"`
GPU bool `json:"gpu,omitempty"`
Timeout string `json:"timeout,omitempty"`
Repo string `json:"repo,omitempty"`
}
// AgentRunResult is the agent-run acceptance.
type AgentRunResult struct {
RunID string `json:"runId"`
Status string `json:"status"`
URL string `json:"url"`
}
func newAgentCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "agent",
Short: "Invoke a managed Hanzo agent to run a task (headless)",
Long: "Invoke a managed agent by ref (e.g. a coding or tool agent) to run a task on\n" +
"Hanzo compute — metered per run. For a computer-using agent (booted desktop\n" +
"or terminal), use `hanzo bot`.",
}
cmd.AddCommand(newAgentRunCmd(envOf))
return cmd
}
func newAgentRunCmd(envOf func() *Env) *cobra.Command {
var req AgentRunReq
c := &cobra.Command{
Use: "run <ref> <task>",
Short: "Run a task with the named agent (POST /v1/agents/:ref/run)",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
env := envOf()
ref := args[0]
req.Task = strings.Join(args[1:], " ")
out := &AgentRunResult{}
if err := cloudCall(cmd.Context(), env, http.MethodPost, "/v1/agents/"+ref+"/run", &req, out); err != nil {
return err
}
return env.emit(out, func(w io.Writer) {
fmt.Fprintf(w, "%s\t%s\t%s\n", out.RunID, out.Status, out.URL)
})
},
}
c.Flags().BoolVar(&req.GPU, "gpu", false, "run the agent on a GPU node")
c.Flags().StringVar(&req.Timeout, "timeout", "", "max wall-clock (e.g. 30m)")
c.Flags().StringVar(&req.Repo, "repo", "", "a repo/checkout the agent operates on")
return c
}
+143 -26
View File
@@ -160,23 +160,21 @@ type loginFlags struct {
}
func runLogin(env *Env, lf *loginFlags, cmd *cobra.Command) error {
creds, err := LoadCredentials()
if err != nil {
return err
}
var creds *Credentials
switch {
case lf.token != "":
// Paste an externally-minted token. Decode claims for identity.
tr := &tokenResp{AccessToken: lf.token, TokenType: "Bearer"}
creds = credsFromToken(tr)
default:
creds = credsFromToken(&tokenResp{AccessToken: lf.token, TokenType: "Bearer"})
case lf.username != "" || lf.passwordStdin:
// Password grant — kept for automation (--username/--password-stdin).
username := lf.username
if username == "" {
username, err = prompt(cmd, "Email: ")
u, err := prompt(cmd, "Email: ")
if err != nil {
return err
}
username = u
}
password, err := readPassword(cmd, lf.passwordStdin)
if err != nil {
@@ -188,10 +186,18 @@ func runLogin(env *Env, lf *loginFlags, cmd *cobra.Command) error {
return err
}
creds = credsFromToken(tr)
default:
// The ONE interactive way: RFC 8628 device flow — link + QR + code,
// approve from any signed-in browser or phone. Headless-safe.
c, err := runDeviceLogin(cmd, env, lf.scope)
if err != nil {
return err
}
creds = c
}
// Optional machine-to-machine tokens for the platform control plane,
// stored alongside the identity so apps/deploy work post-login.
// stored with this identity so apps/deploy work post-login.
if lf.platformToken != "" {
creds.PlatformToken = lf.platformToken
}
@@ -199,14 +205,23 @@ func runLogin(env *Env, lf *loginFlags, cmd *cobra.Command) error {
creds.BuildToken = lf.buildToken
}
if err := creds.Save(); err != nil {
// Persist under this identity's stable key and make it active. A second
// login as a different owner (e.g. admin vs hanzo for the same email, via a
// different --client-id) is stored beside the first, never over it;
// credentials.json mirrors whichever is active for legacy readers.
store, err := LoadIdentities()
if err != nil {
return err
}
key := store.Put(creds)
if err := store.Save(); err != nil {
return err
}
who := firstNonEmpty(creds.Subject, "(unknown)")
if creds.Owner != "" {
who += " @ " + creds.Owner
}
fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s (token expires %s)\n", who, shortTime(creds.Expiry))
fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s [%s] (token expires %s)\n", who, key, shortTime(creds.Expiry))
return nil
}
@@ -215,10 +230,13 @@ func newLoginCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Short: "Authenticate against Hanzo IAM and store a token",
Long: "Authenticate against Hanzo IAM (hanzo.id) via the password grant and store\n" +
"the token in ~/.hanzo/credentials.json (mode 0600). Use --token to store an\n" +
"externally-minted token instead, and --platform-token to store the platform\n" +
"control-plane service token needed by apps/deploy/clusters.",
Long: "Authenticate against Hanzo IAM (hanzo.id) and store the token in\n" +
"~/.hanzo/credentials.json (mode 0600). Default is the device flow: scan the\n" +
"QR (or open the link) from any signed-in device and approve — no password\n" +
"touches this terminal, works over ssh/headless. --username/--password-stdin\n" +
"keep the password grant for automation; --token stores an externally-minted\n" +
"token; --platform-token stores the platform control-plane service token\n" +
"needed by apps/deploy/clusters.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return runLogin(envOf(), lf, cmd) },
}
@@ -238,28 +256,92 @@ func bindLoginFlags(cmd *cobra.Command, lf *loginFlags) {
func newLogoutCmd() *cobra.Command {
return &cobra.Command{
Use: "logout",
Short: "Remove stored credentials",
Args: cobra.NoArgs,
Use: "logout [<owner>]",
Short: "Remove a stored identity (the active one, or the named owner)",
Args: cobra.MaximumNArgs(1),
PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
RunE: func(cmd *cobra.Command, _ []string) error {
if err := DeleteCredentials(); err != nil {
RunE: func(cmd *cobra.Command, args []string) error {
store, err := LoadIdentities()
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), "Logged out.")
if len(store.Identities) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "Not logged in.")
return nil
}
target := store.Active
if len(args) == 1 {
if target, err = store.resolve(args[0]); err != nil {
return err
}
}
store.Remove(target)
if err := store.Save(); err != nil {
return err
}
msg := "Logged out of " + target + "."
if store.Active != "" {
msg += " Active is now " + store.Active + "."
}
fmt.Fprintln(cmd.OutOrStdout(), msg)
return nil
},
}
}
// identityRow is the JSON/table projection of one stored identity.
type identityRow struct {
Key string `json:"key"`
Owner string `json:"owner"`
Subject string `json:"subject"`
Expiry int64 `json:"expiry,omitempty"`
Active bool `json:"active"`
}
// listIdentities renders every stored identity (active marked with *) — the
// shared body of `hanzo auth list` and `hanzo whoami --all`.
func listIdentities(env *Env, _ *cobra.Command) error {
store, err := LoadIdentities()
if err != nil {
return err
}
rows := make([]identityRow, 0, len(store.Identities))
for _, k := range store.keys() {
c := store.Identities[k]
rows = append(rows, identityRow{
Key: k, Owner: c.Owner, Subject: c.Subject, Expiry: c.Expiry,
Active: k == store.Active,
})
}
return env.emit(rows, func(w io.Writer) {
if len(rows) == 0 {
fmt.Fprintln(w, "No stored identities. Run `hanzo login`.")
return
}
tw := newTab(w)
fmt.Fprintln(tw, "ACTIVE\tKEY\tOWNER\tSUBJECT\tEXPIRES")
for _, r := range rows {
active := ""
if r.Active {
active = "*"
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", active, r.Key, r.Owner, r.Subject, shortTime(r.Expiry))
}
tw.Flush()
})
}
func newWhoamiCmd(envOf func() *Env) *cobra.Command {
var verify bool
var verify, all bool
cmd := &cobra.Command{
Use: "whoami",
Short: "Show the current identity from the stored token",
Short: "Show the active identity from the stored token (--all lists every stored identity)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
env := envOf()
if all {
return listIdentities(env, cmd)
}
tok := env.accessToken()
if tok == "" {
return fmt.Errorf("not logged in: run `hanzo login`")
@@ -289,6 +371,7 @@ func newWhoamiCmd(envOf func() *Env) *cobra.Command {
},
}
cmd.Flags().BoolVar(&verify, "verify", false, "verify the token against the IAM userinfo endpoint")
cmd.Flags().BoolVar(&all, "all", false, "list every stored identity (active marked with *)")
return cmd
}
@@ -318,11 +401,11 @@ func verifyUserInfo(ctx context.Context, env *Env, token string) error {
func newAuthCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Manage authentication",
Short: "Manage authentication and stored identities",
}
tokenCmd := &cobra.Command{
Use: "token",
Short: "Print the stored access token",
Short: "Print the active access token",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
tok := envOf().accessToken()
@@ -333,7 +416,41 @@ func newAuthCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
return nil
},
}
cmd.AddCommand(newLoginCmd(envOf, gf), newLogoutCmd(), newWhoamiCmd(envOf), tokenCmd)
listCmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls", "identities"},
Short: "List stored identities (active marked with *)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return listIdentities(envOf(), cmd) },
}
switchCmd := &cobra.Command{
Use: "switch <owner>",
Aliases: []string{"use"},
Short: "Make a stored identity active (accepts an owner, or a full owner/name key)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
store, err := LoadIdentities()
if err != nil {
return err
}
key, err := store.resolve(args[0])
if err != nil {
return err
}
store.Active = key
if err := store.Save(); err != nil {
return err
}
c := store.Identities[key]
who := firstNonEmpty(c.Subject, "(unknown)")
if c.Owner != "" {
who += " @ " + c.Owner
}
fmt.Fprintf(cmd.OutOrStdout(), "Switched to %s [%s] (token expires %s)\n", who, key, shortTime(c.Expiry))
return nil
},
}
cmd.AddCommand(newLoginCmd(envOf, gf), newLogoutCmd(), newWhoamiCmd(envOf), tokenCmd, listCmd, switchCmd)
return cmd
}
+178 -3
View File
@@ -61,9 +61,9 @@ func TestPasswordGrant(t *testing.T) {
t.Errorf("bad form: %v", r.Form)
}
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": makeJWT(map[string]any{"email": "z@hanzo.ai"}),
"token_type": "Bearer",
"expires_in": 3600,
"access_token": makeJWT(map[string]any{"email": "z@hanzo.ai"}),
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "r",
})
}))
@@ -208,3 +208,178 @@ func TestAuthTokenCommand(t *testing.T) {
t.Fatalf("auth token output: %q", out)
}
}
// TestMultiIdentityLoginSwitch is the full multi-identity story: two logins for
// the same email under different owners (admin vs hanzo — the privilege-
// separation case) coexist, `auth list` shows both, `switch` flips the active
// pointer and rewrites credentials.json, and legacy single-file readers always
// see the active identity.
func TestMultiIdentityLoginSwitch(t *testing.T) {
sandbox(t)
adminTok := makeJWT(map[string]any{"email": "z@hanzo.ai", "owner": "admin", "sub": "u-admin", "exp": float64(2000000000)})
hanzoTok := makeJWT(map[string]any{"email": "z@hanzo.ai", "owner": "hanzo", "sub": "u-hanzo", "exp": float64(2000000001)})
// First login → admin/z is stored and active.
out, err := runRoot(t, "", "login", "--token", adminTok)
if err != nil {
t.Fatalf("login admin: %v", err)
}
if !strings.Contains(out, "admin/z") {
t.Fatalf("login should report the key: %q", out)
}
if c, _ := LoadCredentials(); c.Owner != "admin" || c.Subject != "z@hanzo.ai" {
t.Fatalf("active not admin after first login: %+v", c)
}
// Second login (different owner) → added beside admin/z, becomes active,
// does NOT clobber the first.
if _, err := runRoot(t, "", "login", "--token", hanzoTok); err != nil {
t.Fatalf("login hanzo: %v", err)
}
store, err := LoadIdentities()
if err != nil {
t.Fatalf("load identities: %v", err)
}
if len(store.Identities) != 2 {
t.Fatalf("want 2 identities, got %d: %v", len(store.Identities), store.keys())
}
if store.Identities["admin/z"] == nil || store.Identities["hanzo/z"] == nil {
t.Fatalf("both identities must persist, got %v", store.keys())
}
if store.Active != "hanzo/z" {
t.Fatalf("active = %q, want hanzo/z (last login)", store.Active)
}
// Legacy reader sees the active (hanzo) identity.
if c, _ := LoadCredentials(); c.Owner != "hanzo" {
t.Fatalf("credentials.json not mirroring active: %+v", c)
}
// auth list shows both, with the active row marked.
out, err = runRoot(t, "", "auth", "list")
if err != nil {
t.Fatalf("auth list: %v", err)
}
for _, want := range []string{"admin/z", "hanzo/z", "z@hanzo.ai", "*"} {
if !strings.Contains(out, want) {
t.Fatalf("auth list missing %q in:\n%s", want, out)
}
}
// switch admin → active flips + credentials.json is rewritten to admin.
if _, err := runRoot(t, "", "auth", "switch", "admin"); err != nil {
t.Fatalf("auth switch admin: %v", err)
}
if st, _ := LoadIdentities(); st.Active != "admin/z" {
t.Fatalf("active after switch = %q, want admin/z", st.Active)
}
if c, _ := LoadCredentials(); c.Owner != "admin" || c.Subject != "z@hanzo.ai" {
t.Fatalf("switch did not rewrite credentials.json: %+v", c)
}
// whoami (top-level, reads the active token) reflects admin.
out, err = runRoot(t, "", "whoami")
if err != nil {
t.Fatalf("whoami: %v", err)
}
if !strings.Contains(out, "admin") || !strings.Contains(out, "z@hanzo.ai") {
t.Fatalf("whoami not reflecting the switched-to identity: %q", out)
}
// switch by the full owner/name key works too.
if _, err := runRoot(t, "", "auth", "switch", "hanzo/z"); err != nil {
t.Fatalf("auth switch hanzo/z: %v", err)
}
if c, _ := LoadCredentials(); c.Owner != "hanzo" {
t.Fatalf("switch by full key failed: %+v", c)
}
}
// TestAuthListJSON checks the machine-readable projection.
func TestAuthListJSON(t *testing.T) {
sandbox(t)
tok := makeJWT(map[string]any{"email": "z@hanzo.ai", "owner": "admin", "sub": "a"})
if _, err := runRoot(t, "", "login", "--token", tok); err != nil {
t.Fatalf("login: %v", err)
}
out, err := runRoot(t, "", "auth", "list", "-o", "json")
if err != nil {
t.Fatalf("auth list json: %v", err)
}
var rows []identityRow
if err := json.Unmarshal([]byte(out), &rows); err != nil {
t.Fatalf("json unmarshal: %v\n%s", err, out)
}
if len(rows) != 1 || rows[0].Key != "admin/z" || rows[0].Owner != "admin" || !rows[0].Active {
t.Fatalf("json rows wrong: %+v", rows)
}
}
// TestLogoutOneOfMany removes a single identity and, only when the last one is
// gone, clears the store entirely.
func TestLogoutOneOfMany(t *testing.T) {
sandbox(t)
admin := makeJWT(map[string]any{"email": "z@hanzo.ai", "owner": "admin", "sub": "a"})
hanzo := makeJWT(map[string]any{"email": "z@hanzo.ai", "owner": "hanzo", "sub": "h"})
if _, err := runRoot(t, "", "login", "--token", admin); err != nil {
t.Fatal(err)
}
if _, err := runRoot(t, "", "login", "--token", hanzo); err != nil { // active = hanzo/z
t.Fatal(err)
}
// logout of the named owner (admin) leaves hanzo/z active.
if _, err := runRoot(t, "", "logout", "admin"); err != nil {
t.Fatalf("logout admin: %v", err)
}
store, _ := LoadIdentities()
if store.Identities["admin/z"] != nil {
t.Fatalf("admin/z not removed: %v", store.keys())
}
if store.Active != "hanzo/z" {
t.Fatalf("active = %q, want hanzo/z", store.Active)
}
if c, _ := LoadCredentials(); c.Owner != "hanzo" {
t.Fatalf("credentials.json not mirroring survivor: %+v", c)
}
// logout of the active (no arg) removes the last identity → both files gone.
if _, err := runRoot(t, "", "logout"); err != nil {
t.Fatalf("logout active: %v", err)
}
if c, _ := LoadCredentials(); c.AccessToken != "" {
t.Fatalf("credentials.json not cleared: %+v", c)
}
if st, _ := LoadIdentities(); len(st.Identities) != 0 {
t.Fatalf("identity store not cleared: %v", st.keys())
}
}
// TestMigrateLegacyCredentials proves a pre-multi-identity credentials.json is
// adopted into the store and preserved when a new identity is added.
func TestMigrateLegacyCredentials(t *testing.T) {
sandbox(t)
// Simulate an old single-file login: only credentials.json exists.
legacy := credsFromToken(&tokenResp{AccessToken: makeJWT(map[string]any{
"email": "z@hanzo.ai", "owner": "hanzo", "sub": "h",
})})
if err := legacy.Save(); err != nil {
t.Fatal(err)
}
store, err := LoadIdentities()
if err != nil {
t.Fatalf("load identities: %v", err)
}
if store.Identities["hanzo/z"] == nil || store.Active != "hanzo/z" {
t.Fatalf("legacy credentials not migrated: active=%q keys=%v", store.Active, store.keys())
}
// A fresh login as a different owner preserves the migrated identity.
if _, err := runRoot(t, "", "login", "--token", makeJWT(map[string]any{
"email": "z@hanzo.ai", "owner": "admin", "sub": "a",
})); err != nil {
t.Fatal(err)
}
st2, _ := LoadIdentities()
if len(st2.Identities) != 2 || st2.Identities["hanzo/z"] == nil {
t.Fatalf("migrated identity lost after new login: %v", st2.keys())
}
}
+82
View File
@@ -0,0 +1,82 @@
package cli
// bot.go — `hanzo bot`: launch a computer-using agent (a "bot").
//
// A bot is the COMPUTER-USING flavor of an agent: it quick-boots a terminal or
// desktop sandbox on the operative stack (Hanzo's computer-use runtime — noVNC
// desktop, shell, browser, tools), provisioned by visor, and drives that machine
// to do the task. The headless flavor (no computer) is `hanzo agent` (agent.go).
//
// hanzo bot run "<task>" → boot a desktop bot, run the task
// hanzo bot run --terminal "<task>" → boot a terminal-only bot
//
// Thin client over the IAM token + env.CloudURL (reuses cloudCall, run.go). The
// operative runtime + visor-provisioned machine do the work; the CLI only starts
// the run and reports the live session URL. See docs/architecture/compute-ladder.md.
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/spf13/cobra"
)
// BotRunReq is the boot-a-computer-using-agent body. Surface selects the sandbox
// the operative runtime drives: "desktop" (noVNC GUI) or "terminal" (shell only).
type BotRunReq struct {
Task string `json:"task"`
Surface string `json:"surface"` // desktop | terminal
GPU bool `json:"gpu,omitempty"`
Timeout string `json:"timeout,omitempty"`
}
// BotRunResult carries the live session: a URL to watch/attach (noVNC / terminal)
// plus the run id.
type BotRunResult struct {
RunID string `json:"runId"`
Status string `json:"status"`
SessionURL string `json:"sessionUrl"`
}
func newBotCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "bot",
Short: "Launch a computer-using agent (booted desktop or terminal)",
Long: "Quick-boot a terminal or desktop sandbox on the operative computer-use\n" +
"runtime (visor-provisioned) and have an agent drive it to do a task —\n" +
"metered like any run. For a headless task agent, use `hanzo agent`.",
}
cmd.AddCommand(newBotRunCmd(envOf))
return cmd
}
func newBotRunCmd(envOf func() *Env) *cobra.Command {
var req BotRunReq
var terminal bool
c := &cobra.Command{
Use: "run <task>",
Short: "Boot a computer-using bot and run the task",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
env := envOf()
req.Task = strings.Join(args, " ")
req.Surface = "desktop"
if terminal {
req.Surface = "terminal"
}
out := &BotRunResult{}
if err := cloudCall(cmd.Context(), env, http.MethodPost, "/v1/bots/run", &req, out); err != nil {
return err
}
return env.emit(out, func(w io.Writer) {
fmt.Fprintf(w, "%s\t%s\t%s\n", out.RunID, out.Status, out.SessionURL)
})
},
}
c.Flags().BoolVar(&terminal, "terminal", false, "boot a terminal-only sandbox (default: desktop)")
c.Flags().BoolVar(&req.GPU, "gpu", false, "boot on a GPU machine")
c.Flags().StringVar(&req.Timeout, "timeout", "", "max wall-clock (e.g. 30m)")
return c
}
+224 -5
View File
@@ -8,7 +8,7 @@
// hanzo apps list|get the platform apps board (declared/running/drift)
// hanzo deploy drive a platform redeploy (rolling, zero-downtime)
// hanzo clusters … provision/list/select dedicated DOKS clusters
// hanzo build enqueue a platform-native (arcd) build
// hanzo build enqueue a platform-native build (runner fabric)
// hanzo k8s … current deploy target helpers
// hanzo config … ~/.hanzo/config preferences
//
@@ -55,14 +55,21 @@ var controlCommands = map[string]string{
"login": "authenticate against Hanzo IAM (hanzo.id) and store a token",
"logout": "remove stored credentials",
"whoami": "show the current identity from the stored token",
"auth": "manage authentication (login, logout, whoami, token)",
"auth": "manage authentication + stored identities (login, logout, whoami, list, switch, token)",
"apps": "list/get the platform apps board (declared/running/drift)",
"deploy": "drive a platform redeploy (rolling restart, zero-downtime)",
"clusters": "provision/list/select dedicated DOKS clusters",
"build": "enqueue a platform-native (arcd) build",
"build": "enqueue a platform-native build (runner fabric)",
"k8s": "deploy-target helpers (current target)",
"config": "view/edit ~/.hanzo/config preferences",
"security": "scan files for hardcoded secrets (local guardrail; no server/auth)",
"gpu": "connect this machine's GPU to the Hanzo cloud fleet (connect/status/disconnect)",
"engine": "run a local hanzo-engine (OpenAI + Anthropic model server)",
"code": "launch a coding agent (claude, codex, dev) on a Hanzo cloud model",
"runner": "run this machine as a JIT CI runner for your org (GitHub Actions)",
"run": "launch a workload on Hanzo compute (container or function)",
"agent": "invoke a managed Hanzo agent to run a task (headless)",
"bot": "launch a computer-using agent (booted desktop or terminal)",
}
// IsControlVerb reports whether sub is a client-mode command (and therefore
@@ -96,6 +103,9 @@ type Config struct {
PlatformURL string `json:"platform_url,omitempty"`
CloudURL string `json:"cloud_url,omitempty"`
ClientID string `json:"client_id,omitempty"`
APIKey string `json:"apiKey,omitempty"` // hk-… key; what `hanzo code` hands the agents
CodeTool string `json:"code_tool,omitempty"` // default agent for bare `hanzo` / `hanzo code`: dev|claude|codex
CodeModel string `json:"code_model,omitempty"` // default model for `hanzo code` (else defaultCodeModel)
}
// Credentials holds secret material, ~/.hanzo/credentials.json, mode 0600.
@@ -226,6 +236,170 @@ func DeleteCredentials() error {
return nil
}
// ---------------------------------------------------------------------------
// Identity store — ~/.hanzo/identities.json. Holds EVERY logged-in identity
// keyed by its stable "<owner>/<name>" key, with an Active pointer. On every
// write the active identity is mirrored into credentials.json (above), so every
// legacy single-file reader keeps seeing the current identity unchanged. This
// is the ONE credential store; credentials.json is its active-view mirror.
// ---------------------------------------------------------------------------
// IdentityStore is the on-disk shape of ~/.hanzo/identities.json.
type IdentityStore struct {
Active string `json:"active,omitempty"`
Identities map[string]*Credentials `json:"identities,omitempty"`
}
// key is the stable per-identity store key "<owner>/<name>", where name is the
// email local-part (else the raw subject). The same identity yields the same
// key every login, so re-login updates in place; the same email under a
// different org (privilege separation) yields a distinct key (admin/z vs
// hanzo/z) and is stored side by side rather than clobbering.
func (c *Credentials) key() string {
name := c.Subject
if i := strings.IndexByte(name, '@'); i > 0 {
name = name[:i]
}
return firstNonEmpty(c.Owner, "-") + "/" + firstNonEmpty(name, "-")
}
func identitiesPath() (string, error) {
dir, err := hanzoDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "identities.json"), nil
}
// LoadIdentities reads the store. A pre-existing single-file credentials.json
// with no store yet is migrated in (read-only) as the sole, active identity, so
// upgrades are seamless — the first write persists it into the store.
func LoadIdentities() (*IdentityStore, error) {
p, err := identitiesPath()
if err != nil {
return nil, err
}
s := &IdentityStore{Identities: map[string]*Credentials{}}
if err := loadJSON(p, s); err != nil {
return nil, err
}
if s.Identities == nil {
s.Identities = map[string]*Credentials{}
}
if len(s.Identities) == 0 {
if c, err := LoadCredentials(); err == nil && c.AccessToken != "" {
k := c.key()
s.Identities[k] = c
s.Active = k
}
}
return s, nil
}
// keys returns the identity keys, sorted, for deterministic output.
func (s *IdentityStore) keys() []string {
ks := make([]string, 0, len(s.Identities))
for k := range s.Identities {
ks = append(ks, k)
}
sort.Strings(ks)
return ks
}
// Put stores c under its key and makes it active, returning the key.
func (s *IdentityStore) Put(c *Credentials) string {
if s.Identities == nil {
s.Identities = map[string]*Credentials{}
}
k := c.key()
s.Identities[k] = c
s.Active = k
return k
}
// Remove deletes an identity; Save re-points Active if it was the one removed.
func (s *IdentityStore) Remove(key string) { delete(s.Identities, key) }
// resolve turns a user selector into a stored key: an exact key wins; otherwise
// a bare owner matches iff exactly one identity carries it.
func (s *IdentityStore) resolve(sel string) (string, error) {
if _, ok := s.Identities[sel]; ok {
return sel, nil
}
var match []string
for _, k := range s.keys() {
if s.Identities[k].Owner == sel {
match = append(match, k)
}
}
switch len(match) {
case 1:
return match[0], nil
case 0:
return "", fmt.Errorf("no stored identity for %q (see `hanzo auth list`)", sel)
default:
return "", fmt.Errorf("%q is ambiguous across %s — pass the full owner/name key", sel, strings.Join(match, ", "))
}
}
// Save persists the store (0600) and mirrors the active identity into
// credentials.json for legacy single-file readers. When the store is empty it
// removes both files. Active is normalized to a real key first.
func (s *IdentityStore) Save() error {
if _, ok := s.Identities[s.Active]; !ok {
s.Active = ""
if ks := s.keys(); len(ks) > 0 {
s.Active = ks[0]
}
}
if len(s.Identities) == 0 {
return clearCredentialStore()
}
p, err := identitiesPath()
if err != nil {
return err
}
if err := writeJSON(p, s, 0o600); err != nil {
return err
}
return s.Identities[s.Active].Save() // mirror active → credentials.json (0600)
}
// SaveActive writes c back as the active identity (store + mirror), keeping the
// two consistent after an in-place token refresh. With no store yet it falls
// back to the single-file write.
func SaveActive(c *Credentials) error {
s, err := LoadIdentities()
if err != nil {
return err
}
if len(s.Identities) == 0 {
return c.Save()
}
k := s.Active
if k == "" || s.Identities[k] == nil {
k = c.key()
}
s.Identities[k] = c
s.Active = k
return s.Save()
}
// clearCredentialStore removes the identity store and its credentials.json
// mirror (used by logout when the last identity is removed).
func clearCredentialStore() error {
for _, pathOf := range []func() (string, error){credentialsPath, identitiesPath} {
p, err := pathOf()
if err != nil {
return err
}
if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
return err
}
}
return nil
}
// ---------------------------------------------------------------------------
// Env — the effective, resolved settings a command operates with.
// ---------------------------------------------------------------------------
@@ -284,6 +458,22 @@ func (e *Env) accessToken() string {
return firstNonEmpty(os.Getenv("HANZO_TOKEN"), e.creds.AccessToken)
}
// freshAccessToken returns the IAM user token only while it is not yet expired.
// accessToken() stays expiry-agnostic so `hanzo whoami` can report a dead token
// rather than masking it as logged-out; freshAccessToken is the code-agent path,
// where an expired token would 401 a session a still-valid hk- key could serve.
// No expiry recorded (a raw HANZO_TOKEN with no claims) ⟹ trust it as-is.
func (e *Env) freshAccessToken() string {
tok := e.accessToken()
if tok == "" {
return ""
}
if exp := e.creds.Expiry; exp > 0 && time.Now().Unix() >= exp {
return ""
}
return tok
}
// platformToken resolves the platform control-plane service token. The
// platform REST surface is machine-to-machine (it cannot validate IAM user
// tokens), so apps/clusters/redeploy authenticate with this, sourced from
@@ -300,7 +490,7 @@ func (e *Env) platformToken(flagVal string) string {
}
// buildToken resolves the platform build-enqueue token (a distinct credential
// from the service token — see /v1/arcd/enqueue).
// from the service token — see /v1/runner).
func (e *Env) buildToken(flagVal string) string {
return firstNonEmpty(
flagVal,
@@ -362,6 +552,17 @@ func newRootCmd() *cobra.Command {
env.out = cmd.OutOrStdout()
return nil
},
// Bare `hanzo` gets you coding: log in if needed, then drop into the
// configured agent (code_tool, else dev) on a Hanzo cloud model — one word,
// billed to your account. `hanzo <cmd>` still runs that command.
RunE: func(cmd *cobra.Command, args []string) error {
if codeToken(env) == "" {
if err := runLogin(env, &loginFlags{}, cmd); err != nil {
return err
}
}
return runCode(env, defaultAgent(env), nil)
},
}
pf := root.PersistentFlags()
@@ -390,6 +591,13 @@ func newRootCmd() *cobra.Command {
newK8sCmd(envOf, &f),
newConfigCmd(),
newSecurityCmd(envOf),
newGPUCmd(envOf, &f),
newEngineCmd(envOf, &f),
newCodeCmd(envOf, &f),
newRunnerCmd(envOf, &f),
newRunCmd(envOf, &f),
newAgentCmd(envOf, &f),
newBotCmd(envOf, &f),
)
return root
}
@@ -418,7 +626,7 @@ func newConfigCmd() *cobra.Command {
PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
}
configKeys := []string{"org", "output", "iam_issuer", "platform_url", "cloud_url", "client_id"}
configKeys := []string{"org", "output", "iam_issuer", "platform_url", "cloud_url", "client_id", "code_tool", "code_model"}
get := &cobra.Command{
Use: "get <key>",
@@ -506,6 +714,10 @@ func (c *Config) field(key string) (string, error) {
return c.CloudURL, nil
case "client_id":
return c.ClientID, nil
case "code_tool":
return c.CodeTool, nil
case "code_model":
return c.CodeModel, nil
default:
return "", fmt.Errorf("unknown config key %q", key)
}
@@ -529,6 +741,13 @@ func (c *Config) setField(key, val string) error {
c.CloudURL = val
case "client_id":
c.ClientID = val
case "code_tool":
if _, ok := codeAgents[val]; !ok {
return fmt.Errorf("code_tool must be one of: claude, codex, dev")
}
c.CodeTool = val
case "code_model":
c.CodeModel = val
default:
return fmt.Errorf("unknown config key %q", key)
}
+638
View File
@@ -0,0 +1,638 @@
package cli
// code.go — `hanzo code <agent> [model]`: launch a coding agent on the Hanzo AI
// cloud. ONE way to start ANY agent on ANY Hanzo model: the endpoint, the
// credential and the model are injected for you; nothing to export, nothing to
// remember.
//
// hanzo code claude # Claude Code on the default model
// hanzo code codex deepseek-v4-pro
// hanzo code dev glm5.2 # ids are resolved fuzzily: glm5.2 -> glm-5.2
// hanzo code ls # what can I run?
//
// Two wire protocols cover all three agents: Claude Code speaks Anthropic,
// Codex and @hanzo/dev (a Codex fork) speak OpenAI — so an agent is just a
// binary + a wire + the flag that turns approvals off. Agents run full-auto by
// default (--safe restores prompting).
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"unicode"
"github.com/spf13/cobra"
)
// defaultCodeModel is the model `hanzo code <agent>` runs when no model is
// named. It must be a catalog-served id with working tool calls: coding agents
// cannot operate on a text-only model even when its SSE transport is healthy.
// zen5 is the flagship GLM-5.2-class capability alias (1M ctx, tool-capable) —
// the frontier coding tier. Do not use the virtual `best`: Claude Code treats
// it (like `opus`/`sonnet`/`haiku`) as a reserved alias and rewrites it to a
// claude-* id that api.hanzo.ai does not serve. Override per invocation with an
// explicit id: `hanzo code claude zen5-pro`.
const defaultCodeModel = "zen5"
// A zenTier bridges a model id Claude Code recognizes (the carrier) to the zen
// alias api.hanzo.ai serves. CC sizes a model's context window and features only
// from ids it knows; an unknown id like "zen5-pro" gets a 128K budget and is
// rejected client-side above it — the "max context 131072" the server never
// actually imposes. Nothing lets us declare a custom model's window, so the
// carrier (a known 1M id, [1m] where needed) unlocks the budget and modelOverrides
// rewrites it back to zen before the request leaves the client — the carrier never
// reaches the server. Requires Claude Code v2.1.200+.
type zenTier struct {
zen string // served zen alias — the wire model api.hanzo.ai receives
carrier string // recognized id CC budgets from; "" pins zen directly (fast tiers, never >128K)
env string // ANTHROPIC_DEFAULT_*_MODEL slot ("" = selectable, no slot)
name string // /model picker label (via _NAME, gateway-effective)
desc string // /model picker description (via _DESCRIPTION)
}
// slotID is the tier's wire value: its carrier, or the zen id when direct.
func (t zenTier) slotID() string {
if t.carrier != "" {
return t.carrier
}
return t.zen
}
// zenTiers is the ONE source of truth for the CC-tier ⇆ zen mapping — the wire
// env, picker branding, and modelOverrides all derive from it. Every zen id must
// be one api.hanzo.ai serves (TestZenTiersServeReal); zen5-mini/max/ultra are
// listed but not served, so fable maps to zen5-pro until zen5-max returns.
var zenTiers = []zenTier{
{zen: "zen5-flash", env: "ANTHROPIC_DEFAULT_HAIKU_MODEL", name: "Zen5 Flash", desc: "Hanzo Zen5 Flash — fast, cheap tier"},
{zen: "zen5", carrier: "claude-sonnet-4-6[1m]", env: "ANTHROPIC_DEFAULT_SONNET_MODEL", name: "Zen5", desc: "Hanzo Zen5 — frontier tier (1M context)"},
{zen: "zen5-pro", carrier: "claude-opus-4-8[1m]", env: "ANTHROPIC_DEFAULT_OPUS_MODEL", name: "Zen5 Pro", desc: "Hanzo Zen5 Pro — DeepSeek-V4 class (1M context)"},
{zen: "zen5-pro", carrier: "claude-fable-5[1m]", env: "ANTHROPIC_DEFAULT_FABLE_MODEL", name: "Zen5 Pro (max effort)", desc: "Hanzo Zen5 Pro, top tier (1M context)"},
{zen: "zen5-coder", carrier: "claude-sonnet-5", name: "Zen5 Coder", desc: "Hanzo Zen5 Coder — code-specialized (1M context)"},
}
// zenCarrier maps a resolved zen alias to the carrier CC budgets from; an unknown
// id passes through with CC's default budget.
func zenCarrier(model string) string {
for _, t := range zenTiers {
if t.zen == model {
return t.slotID()
}
}
return model
}
// stripModelSuffix drops the "[1m]" suffix so a carrier matches its override key.
func stripModelSuffix(id string) string {
if i := strings.IndexByte(id, '['); i >= 0 {
return id[:i]
}
return id
}
// claudeModelOverrides is the carrier→zen map for settings.json: CC budgets from
// the carrier key and sends the zen value on the wire. Direct tiers need no entry.
func claudeModelOverrides() map[string]string {
m := make(map[string]string, len(zenTiers))
for _, t := range zenTiers {
if t.carrier != "" {
m[stripModelSuffix(t.carrier)] = t.zen
}
}
return m
}
// wire builds the env that points an agent's SDK at the Hanzo cloud.
type wire func(base, token, model string) map[string]string
// anthropicWire points Claude Code at the Hanzo cloud and pins each CC tier slot
// to its carrier (see zenTier), so subagents, the classifier, and /compact get
// the right context budget while modelOverrides rewrites carriers back to zen ids
// on the wire. `model` arrives already mapped to its carrier (runCode).
func anthropicWire(base, token, model string) map[string]string {
env := map[string]string{
"ANTHROPIC_BASE_URL": base,
"ANTHROPIC_AUTH_TOKEN": token,
"ANTHROPIC_MODEL": model,
}
for _, t := range zenTiers {
if t.env == "" {
continue
}
env[t.env] = t.slotID()
env[t.env+"_NAME"] = t.name
env[t.env+"_DESCRIPTION"] = t.desc
// SMALL_FAST_MODEL is deprecated AND not rewritten by modelOverrides, so
// it must hold a served zen id directly — mirror the (direct) haiku slot.
if t.env == "ANTHROPIC_DEFAULT_HAIKU_MODEL" {
env["ANTHROPIC_SMALL_FAST_MODEL"] = t.slotID()
}
}
return env
}
func openaiWire(base, token, _ string) map[string]string {
return map[string]string{
"OPENAI_BASE_URL": strings.TrimSuffix(base, "/") + "/v1",
"OPENAI_API_KEY": token,
}
}
type codeAgent struct {
bin string // executable to exec
wire wire // how it finds the cloud
fullAuto []string // flags that bypass approval prompts
modelArg []string // how the model is passed on argv (empty: via env)
carrier func(model string) string // maps the resolved model to a client-recognized id (claude: zen→carrier); nil = pass through
provider func(base string) []string // agents that need the endpoint declared, not just env'd
clear []string // env that would shadow the wire (a stale key in the shell)
configHome string // env var that relocates the agent's config dir to ~/.hanzo ("" = share the user's own install)
seed func(dir string) error // one-time defaults for the isolated config dir
appendSystem []string // --append-system-prompt + text; ALWAYS applied (identity, not a permission bypass — present in --safe too)
mcp bool // auto-wire the Hanzo MCP server (code/vector/web/vision tools) as an stdio server scoped to the cwd
install string // hint when the binary is missing
}
// codex and @hanzo/dev share a lineage (dev is a Codex fork), hence a wire.
// They also ignore OPENAI_BASE_URL and talk to chatgpt.com unless a provider is
// declared, so declare Hanzo as the provider and select it.
func codexLike(bin, install string) codeAgent {
return codeAgent{
bin: bin,
wire: openaiWire,
fullAuto: []string{"--dangerously-bypass-approvals-and-sandbox"},
modelArg: []string{"-m"},
provider: func(base string) []string {
return []string{
"-c", "model_provider=hanzo",
"-c", `model_providers.hanzo.name="Hanzo"`,
"-c", fmt.Sprintf(`model_providers.hanzo.base_url="%s/v1"`, strings.TrimSuffix(base, "/")),
"-c", `model_providers.hanzo.env_key="OPENAI_API_KEY"`,
"-c", `model_providers.hanzo.wire_api="responses"`,
}
},
install: install,
}
}
// zenIdentityPrompt is appended to Claude Code's base system prompt so a model
// served through the Hanzo cloud self-identifies as a Hanzo Zen model. It is an
// APPEND, not a replace: Claude Code keeps its base prompt (tool-use, safety,
// coding conventions); only the model's identity is Hanzo Zen. The model is
// served as a zen5 alias via api.hanzo.ai. Passed as --append-system-prompt,
// present in --safe too (identity is not a permission bypass).
const zenIdentityPrompt = "You are running through the Hanzo AI cloud as a Hanzo Zen model (the `zen5` capability tier, served via api.hanzo.ai). When asked what model or assistant you are, identify as a Hanzo Zen model. You are operating inside the Claude Code harness; keep its tool-use, safety, and coding conventions — only your identity is Hanzo Zen."
var codeAgents = map[string]codeAgent{
"claude": {
bin: "claude",
wire: anthropicWire,
fullAuto: []string{"--dangerously-skip-permissions"},
// --model forces the session model on argv. Claude Code persists the
// user's last /model selection (e.g. the reserved word "best"), and that
// persisted choice OVERRIDES ANTHROPIC_MODEL — so the env var alone cannot
// pin the model. --model is the per-session override that beats it. CC
// budgets the context window from this (carrier) id, then rewrites it to
// the zen alias via modelOverrides before the request leaves the client —
// so api.hanzo.ai serves the zen id regardless of what /model last held.
modelArg: []string{"--model"},
// zen→carrier: hand CC a model it recognizes so it grants the full (1M)
// context budget; claudeSettings' modelOverrides maps it back to zen.
carrier: zenCarrier,
// Stamp the identity: append the Hanzo Zen identity to CC's base prompt so
// the served model says it is a Hanzo Zen model when asked. An append (not
// --system-prompt) keeps CC's harness prompt intact; applied in --safe too.
appendSystem: []string{"--append-system-prompt", zenIdentityPrompt},
clear: []string{"ANTHROPIC_API_KEY"}, // outranks AUTH_TOKEN: a stale one silently wins
// Its own config home under ~/.hanzo, not the user's ~/.claude. Claude
// Code and `hanzo code claude` are independent products: sharing one
// mutable config braids them — the user's saved /model (e.g. "fable")
// leaks in as the session identity, and hanzo's zen5 picks leak back out.
// A separate home decomplects them; the injected zen5 slots then show
// cleanly in /model instead of a stale saved value.
configHome: "CLAUDE_CONFIG_DIR",
seed: seedClaudeConfig,
// Auto-wire the Hanzo MCP server so `hanzo code claude` starts with the
// Hanzo tool lattice (code search over the cloud index, web search, vision,
// fs/exec/git) instead of a bare model. Resolved + injected in runCode.
mcp: true,
install: "npm i -g @anthropic-ai/claude-code",
},
"codex": codexLike("codex", "npm i -g @openai/codex"),
"dev": codexLike("dev", "npm i -g @hanzo/dev"),
}
// defaultAgent is the agent `hanzo code` (no agent named) and bare `hanzo` launch:
// HANZO_CODE_TOOL, else the config `code_tool`, else dev — the Hanzo agent. An
// unknown value falls back to dev rather than failing, so a stale preference never
// blocks the default flow.
func defaultAgent(env *Env) codeAgent {
name := firstNonEmpty(os.Getenv("HANZO_CODE_TOOL"), env.cfg.CodeTool)
if a, ok := codeAgents[name]; ok {
return a
}
return codeAgents["dev"]
}
func newCodeCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "code [agent] [model] [-- args]",
Short: "Launch a coding agent (dev, claude, codex) on a Hanzo cloud model",
Long: "Run @hanzo/dev, Claude Code, or Codex against api.hanzo.ai with the endpoint,\n" +
"credential and model injected — no env vars to remember. `hanzo code` alone runs\n" +
"dev (the Hanzo agent); name an agent to pick another. Model ids resolve fuzzily\n" +
"(glm5.2 -> glm-5.2) and agents run full-auto unless you pass --safe.",
Example: " hanzo code # dev, the default agent\n" +
" hanzo code claude\n" +
" hanzo code codex deepseek-v4-pro\n" +
" hanzo code dev glm5.2 -- --resume\n" +
" hanzo code ls",
// Bare `hanzo code` (or `hanzo code <model>/-- args` with no agent name) runs
// the configured default agent (code_tool, else dev). A recognized agent name
// (or `ls`) dispatches to its subcommand; anything else is the agent's args, so
// `hanzo code glm5.2` works too.
DisableFlagParsing: true,
RunE: func(c *cobra.Command, args []string) error {
if len(args) > 0 {
if _, isAgent := codeAgents[args[0]]; isAgent || args[0] == "ls" {
sub, _, err := c.Find(args)
if err == nil && sub != c {
sub.SetArgs(args[1:])
return sub.Execute()
}
}
}
return runCode(envOf(), defaultAgent(envOf()), args)
},
}
names := make([]string, 0, len(codeAgents))
for name := range codeAgents {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
agent := codeAgents[name]
cmd.AddCommand(&cobra.Command{
Use: name + " [model] [-- args]",
Short: "Launch " + name + " on a Hanzo model (default: " + defaultCodeModel + ")",
DisableFlagParsing: true, // agent flags (--resume, -c …) pass straight through
RunE: func(c *cobra.Command, args []string) error {
return runCode(envOf(), agent, args)
},
})
}
cmd.AddCommand(&cobra.Command{
Use: "ls",
Aliases: []string{"models", "list"},
Short: "List the models this account can run",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
env := envOf()
models, err := catalog(env)
if err != nil {
return err
}
for _, m := range models {
fmt.Fprintln(env.out, m)
}
return nil
},
})
return cmd
}
func runCode(env *Env, agent codeAgent, args []string) error {
bin, err := exec.LookPath(agent.bin)
if err != nil {
return fmt.Errorf("%s is not installed — try: %s", agent.bin, agent.install)
}
token := codeToken(env)
if token == "" {
return fmt.Errorf("no Hanzo credential — run `hanzo login`, or set HANZO_API_KEY")
}
base := strings.TrimSuffix(firstNonEmpty(env.CloudURL, "https://api.hanzo.ai"), "/")
// First non-flag arg is the model; --safe is ours; the rest is the agent's.
model, safe, rest := "", false, make([]string, 0, len(args))
for _, a := range args {
switch {
case a == "--": // the separator is ours; the agent must not see it
case a == "--safe" || a == "--ask":
safe = true
case model == "" && !strings.HasPrefix(a, "-") && len(rest) == 0:
model = a
default:
rest = append(rest, a)
}
}
if model == "" {
model = defaultCodeModel
}
if model, err = resolveModel(env, model); err != nil {
return err
}
// Resolve the served zen id first (above), THEN hand the agent its carrier:
// the id its client recognizes for context/feature budgeting. The zen id is
// what api.hanzo.ai serves; the carrier is a client-side concern only.
served := model
if agent.carrier != nil {
model = agent.carrier(model)
}
for _, k := range agent.clear {
if err := os.Unsetenv(k); err != nil {
return err
}
}
// The isolated config dir is resolved BEFORE argv so the MCP config file can be
// written into it (and cleaned with the rest of the session state).
var configDir string
if agent.configHome != "" {
dir, err := hanzoDir()
if err != nil {
return err
}
if agent.seed != nil {
if err := agent.seed(dir); err != nil {
return err
}
}
if err := os.Setenv(agent.configHome, dir); err != nil {
return err
}
configDir = dir
}
// Auto-wire the Hanzo MCP server (code search over the cloud index, web search,
// vision, fs/exec/git) so the agent starts with the tool lattice, not a bare
// model. Appended to the agent's own args; a missing server warns, never blocks.
if agent.mcp && configDir != "" {
cwd, _ := os.Getwd()
if flags, warn := mcpArgs(configDir, cwd); warn != "" {
fmt.Fprintf(env.out, "hanzo mcp: %s\n", warn)
} else {
rest = append(rest, flags...)
}
}
argv := codeArgv(agent, base, model, safe, rest)
for k, v := range agent.wire(base, token, model) {
if err := os.Setenv(k, v); err != nil {
return err
}
}
if served != model {
fmt.Fprintf(env.out, "%s → %s (as %s) on %s\n", agent.bin, served, model, base)
} else {
fmt.Fprintf(env.out, "%s → %s on %s\n", agent.bin, model, base)
}
return execEngine(bin, argv) // exec: signals + exit code flow straight through
}
// codeArgv builds the final agent command line. Permission bypass is the
// launcher default for every agent; --safe is the single explicit opt-out.
func codeArgv(agent codeAgent, base, model string, safe bool, rest []string) []string {
argv := []string{agent.bin}
if !safe {
argv = append(argv, agent.fullAuto...)
}
if agent.provider != nil {
argv = append(argv, agent.provider(base)...)
}
if len(agent.modelArg) > 0 { // claude takes the model via env, codex/dev on argv
argv = append(argv, agent.modelArg...)
argv = append(argv, model)
}
argv = append(argv, agent.appendSystem...) // identity — applies in safe AND full-auto
argv = append(argv, rest...)
return argv
}
// mcpArgs resolves the Hanzo MCP server and returns the flags that attach it to a
// claude session, scoped to cwd. It ports the Rust CLI's resolve_mcp: prefer an
// installed `hanzo-mcp` on PATH, else `uvx hanzo-mcp` (ephemeral), else nothing —
// MCP is an enhancement, so a missing server never blocks the session. The Hanzo
// server is layered via --mcp-config, and --strict-mcp-config makes it the SOLE
// MCP source: a repo's own .mcp.json is NOT loaded (it can carry a hostile stdio
// server that would inherit the session's bearer). The config file is written into
// the isolated config dir so it is cleaned with the rest of the hanzo session state.
//
// Returns the argv flags to append (possibly empty) and a warning to surface when
// no server could be resolved, so the caller can tell the user tools are absent.
func mcpArgs(configDir, cwd string) (flags []string, warn string) {
prog, args := resolveHanzoMCP(cwd)
if prog == "" {
return nil, "hanzo-mcp not found (install: `uv tool install hanzo-mcp`); launching without Hanzo tools"
}
cfg := mcpConfigJSON(prog, args)
path := filepath.Join(configDir, "mcp.json")
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
return nil, "could not write MCP config; launching without Hanzo tools"
}
// --strict-mcp-config: the Hanzo server is the ONLY MCP source (a repo
// .mcp.json is ignored — it could ship a bearer-exfiltrating stdio server).
return []string{"--mcp-config", path, "--strict-mcp-config"}, ""
}
// resolveHanzoMCP finds how to launch hanzo-mcp as an stdio server scoped to cwd:
// an installed console script first, else uv's ephemeral runner. Empty program =
// neither is on PATH.
func resolveHanzoMCP(cwd string) (prog string, args []string) {
if p, err := exec.LookPath("hanzo-mcp"); err == nil {
return p, []string{"--project-dir", cwd}
}
if p, err := exec.LookPath("uvx"); err == nil {
return p, []string{"hanzo-mcp", "--project-dir", cwd}
}
return "", nil
}
// mcpConfigJSON is the --mcp-config document adding Hanzo's stdio server. Claude
// requires an explicit "type". Marshaled (not fmt'd) so the cwd/program are
// correctly escaped.
func mcpConfigJSON(prog string, args []string) string {
doc := map[string]any{
"mcpServers": map[string]any{
"hanzo": map[string]any{
"type": "stdio",
"command": prog,
"args": args,
"env": map[string]string{},
},
},
}
b, _ := json.Marshal(doc)
return string(b)
}
// seedClaudeConfig writes first-run defaults into the isolated config dir so
// `hanzo code claude` starts clean: auto-approve, high effort, onboarding done,
// and NO pinned model (the zen5 slots come from the injected env, not saved
// state). It never overwrites — the user's own later edits in this dir persist.
func seedClaudeConfig(dir string) error {
if err := upsertClaudeSettings(filepath.Join(dir, "settings.json")); err != nil {
return err
}
return writeIfAbsent(filepath.Join(dir, ".claude.json"), "{\"hasCompletedOnboarding\":true}\n")
}
// claudeSettingsBase is the first-run settings.json for `hanzo code claude`:
// sensible agent defaults and no pinned model, so the env-injected carrier slots
// win. effortLevel is max — the deepest reasoning tier — matching the operator's
// /effort max session setting; zen folds it into the upstream's reasoning budget
// (anthropicThinkingBudget → normalizeReasoning) so it reaches the model. Applied
// only when settings.json does not yet exist — later user edits to these persist.
var claudeSettingsBase = map[string]any{
"includeCoAuthoredBy": false,
"permissions": map[string]any{"defaultMode": "auto"},
"skipAutoPermissionPrompt": true,
"skipDangerousModePermissionPrompt": true,
"effortLevel": "max",
"theme": "dark",
"enableWorkflows": true,
}
// upsertClaudeSettings writes settings.json, (re)applying the operator-owned
// modelOverrides (carrier→zen) on EVERY launch while preserving the user's own
// edits to every other key. modelOverrides is policy, not preference: it must
// track the current zenTiers so Claude Code's context-budgeting carriers keep
// mapping to the served zen ids — so, unlike the base defaults, it is not
// write-once. A first run (or an unreadable/corrupt file) starts from the base.
func upsertClaudeSettings(path string) error {
settings := map[string]any{}
if b, err := os.ReadFile(path); err != nil || json.Unmarshal(b, &settings) != nil || len(settings) == 0 {
settings = map[string]any{}
for k, v := range claudeSettingsBase {
settings[k] = v
}
}
overrides := make(map[string]any, len(zenTiers))
for carrier, zen := range claudeModelOverrides() {
overrides[carrier] = zen
}
settings["modelOverrides"] = overrides
b, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, append(b, '\n'), 0o600)
}
// writeIfAbsent creates path with content only when it does not already exist,
// so seeding a config dir never clobbers a user's later edits.
func writeIfAbsent(path, content string) error {
if _, err := os.Stat(path); err == nil {
return nil
}
return os.WriteFile(path, []byte(content), 0o600)
}
// codeToken resolves the credential the agents authenticate with. Precedence:
// an explicit HANZO_API_KEY always wins (the operator's deliberate override),
// then the live `hanzo login` JWT, then the hk- API key chain.
//
// Why the JWT beats the hk- key: the JWT carries the caller's owner/project/sub
// claims verbatim, so the identity boundary mints a billing principal on EVERY
// deployment. The hk- key only mints a principal when the server can resolve it
// (iamKeys.resolve, which is a no-op without IAM_MINT_CLIENT_ID/SECRET) — on a
// deployment lacking that credential an hk- request arrives anonymous and zen's
// billing gate 402s ("a billable tenant is required"). Preferring a FRESH JWT
// keeps `hanzo code` working everywhere; the hk- key stays the fallback for
// mint-credentialed servers and the explicit-override case. freshAccessToken
// skips an expired token so it can't 401 a session a valid hk- key would serve.
func codeToken(env *Env) string {
return firstNonEmpty(os.Getenv("HANZO_API_KEY"), env.freshAccessToken(), env.cfg.APIKey, storedAPIKey())
}
// storedAPIKey reads (never writes) the hk- key that hanzo-mcp and the rest of
// the toolchain share, so one `hanzo login`/key serves every tool.
func storedAPIKey() string {
dir, err := hanzoDir()
if err != nil {
return ""
}
var cfg struct {
APIKey string `json:"apiKey"`
}
if err := loadJSON(filepath.Join(dir, "config.json"), &cfg); err != nil {
return ""
}
return cfg.APIKey
}
// resolveModel turns what you typed into an id the cloud serves. Exact ids pass
// through; otherwise ids are compared with punctuation and case removed, so
// "glm5.2" finds "glm-5.2". An unknown id lists the near misses rather than
// failing deep inside the agent.
func resolveModel(env *Env, want string) (string, error) {
models, err := catalog(env)
if err != nil {
// Never hand an agent a model we could not confirm: it would fail deep
// inside the session with an opaque error. Say so here instead.
return "", fmt.Errorf("cannot read the model catalog: %w", err)
}
fold := func(s string) string {
return strings.Map(func(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return unicode.ToLower(r)
}
return -1
}, s)
}
target := fold(want)
var near []string
for _, m := range models {
switch f := fold(m); {
case m == want, f == target:
return m, nil
case strings.Contains(f, target), strings.Contains(target, f):
near = append(near, m)
}
}
if len(near) == 1 {
return near[0], nil
}
if len(near) > 1 {
return "", fmt.Errorf("%q is ambiguous — did you mean: %s", want, strings.Join(near, ", "))
}
return "", fmt.Errorf("no model %q — run `hanzo code ls` to see what you can run", want)
}
func catalog(env *Env) ([]string, error) {
base := strings.TrimSuffix(firstNonEmpty(env.CloudURL, "https://api.hanzo.ai"), "/")
req, err := http.NewRequest(http.MethodGet, base+"/v1/models", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+codeToken(env))
resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s/v1/models: %s", base, resp.Status)
}
var body struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return nil, err
}
ids := make([]string, 0, len(body.Data))
for _, m := range body.Data {
ids = append(ids, m.ID)
}
sort.Strings(ids)
return ids, nil
}
+409
View File
@@ -0,0 +1,409 @@
// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cli
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"testing"
"time"
)
func TestCodeAgentsBypassPermissionsByDefault(t *testing.T) {
tests := []struct {
name string
flag string
}{
{name: "claude", flag: "--dangerously-skip-permissions"},
{name: "codex", flag: "--dangerously-bypass-approvals-and-sandbox"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
agent := codeAgents[tt.name]
argv := codeArgv(agent, "https://api.hanzo.ai", defaultCodeModel, false, nil)
if !slices.Contains(argv, tt.flag) {
t.Fatalf("default argv %q does not contain permission bypass %q", argv, tt.flag)
}
safeArgv := codeArgv(agent, "https://api.hanzo.ai", defaultCodeModel, true, nil)
if slices.Contains(safeArgv, tt.flag) {
t.Fatalf("--safe argv %q still contains permission bypass %q", safeArgv, tt.flag)
}
})
}
}
// TestCodeTokenPrecedence locks in the 402 unblock: a fresh `hanzo login` JWT
// (which carries owner/project/sub on EVERY deployment) beats the hk- API key
// (which only mints a billing principal where the server has IAM_MINT_CLIENT_*).
// On a mint-less deployment an hk- request arrives anonymous and zen 402s; the
// JWT must win when it is live. An EXPIRED JWT must NOT win — it would 401 a
// session a valid hk- key would still serve — so it falls through to the key.
// HANZO_API_KEY stays the deliberate operator override at the top.
func TestCodeTokenPrecedence(t *testing.T) {
// freshExpiry is comfortably in the future without a literal unix timestamp.
freshExpiry := time.Now().Add(1 * time.Hour).Unix()
cases := []struct {
name string
envKey string // HANZO_API_KEY override
creds Credentials
want string
}{
{
name: "fresh JWT beats hk- key",
creds: Credentials{AccessToken: "jwt-live", Expiry: freshExpiry},
want: "jwt-live",
},
{
name: "expired JWT falls through to stored hk- key",
creds: Credentials{AccessToken: "jwt-dead", Expiry: time.Now().Add(-1 * time.Hour).Unix()},
want: "hk-stored",
},
{
name: "no JWT, no expiry record ⟹ hk- key (mint-credentialed servers)",
creds: Credentials{},
want: "hk-stored",
},
{
name: "HANZO_API_KEY overrides everything (deliberate operator override)",
envKey: "hk-explicit",
creds: Credentials{AccessToken: "jwt-live", Expiry: freshExpiry},
want: "hk-explicit",
},
{
name: "HANZO_API_KEY overrides even an expired JWT",
envKey: "hk-explicit",
creds: Credentials{AccessToken: "jwt-dead", Expiry: time.Now().Add(-1 * time.Hour).Unix()},
want: "hk-explicit",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sandbox(t) // isolates HANZO_HOME + clears HANZO_TOKEN/HANZO_API_KEY
if tc.envKey != "" {
t.Setenv("HANZO_API_KEY", tc.envKey)
}
// Put the hk- key where storedAPIKey() reads it (~/.hanzo/config.json),
// the same path the rest of the toolchain shares it from.
cfgDir, _ := hanzoDir()
if err := os.WriteFile(filepath.Join(cfgDir, "config.json"),
[]byte(`{"apiKey":"hk-stored"}`), 0o600); err != nil {
t.Fatalf("write config.json: %v", err)
}
env := resolve(&Config{}, &tc.creds, globalFlags{})
if got := codeToken(env); got != tc.want {
t.Fatalf("codeToken = %q, want %q", got, tc.want)
}
})
}
}
func TestDefaultCodeModelIsToolCapableAlias(t *testing.T) {
// zen5 is the flagship GLM-5.2-class alias — tool-capable (verified live: the
// glm-5.2 upstream returns tool_use / stop_reason:tool_use) and the model the
// user's "pop open with GLM-5.2" intent maps to. It must NOT be the virtual
// `best` (a reserved word Claude Code rewrites to an unserved claude-* id).
if defaultCodeModel != "zen5" {
t.Fatalf("coding-agent default %q is not the flagship zen5 alias", defaultCodeModel)
}
if defaultCodeModel == "best" {
t.Fatal("default must be a concrete served id, never the reserved word best")
}
}
// TestAnthropicWirePinsCarrierTiers locks in the 1M-context fix: every CC tier
// slot is pinned to a Claude-Code-recognized CARRIER id (so CC grants the model
// its true, up-to-1M context budget instead of the 128K fallback it applies to
// ids it does not know), and settings.json modelOverrides rewrites each carrier
// back to a served zen alias before the request leaves the client — so the wire
// model that reaches api.hanzo.ai is always zen, never the carrier. The old
// deadlock (a raw claude-* id 403ing on the Hanzo account) cannot recur because
// the carrier never reaches the server; the override guarantees it (asserted in
// TestCarrierTiersAreOverridden).
func TestAnthropicWirePinsCarrierTiers(t *testing.T) {
env := anthropicWire("https://api.hanzo.ai", "hk-test", "claude-opus-4-8[1m]")
want := map[string]string{
"ANTHROPIC_BASE_URL": "https://api.hanzo.ai",
"ANTHROPIC_AUTH_TOKEN": "hk-test",
"ANTHROPIC_MODEL": "claude-opus-4-8[1m]",
"ANTHROPIC_SMALL_FAST_MODEL": "zen5-flash", // deprecated var: no override applies, so a direct served zen id
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "zen5-flash", // fast tier is carrier-less (never needs >128K)
"ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-6[1m]",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-8[1m]",
"ANTHROPIC_DEFAULT_FABLE_MODEL": "claude-fable-5[1m]",
}
for k, v := range want {
if got := env[k]; got != v {
t.Errorf("%s: want %q, got %q", k, v, got)
}
}
// Each tier slot carries a Hanzo-branded display name so the picker never
// shows the underlying carrier (Opus/Sonnet/Haiku) — only the Zen brand.
if env["ANTHROPIC_DEFAULT_OPUS_MODEL_NAME"] != "Zen5 Pro" {
t.Errorf("OPUS tier must display the Zen brand, got %q", env["ANTHROPIC_DEFAULT_OPUS_MODEL_NAME"])
}
}
// TestCarrierTiersAreOverridden is the safety net that replaces the old
// "no claude-* in the wire" rule: a claude-* carrier in the env is SAFE only
// because modelOverrides maps it to a served zen id. Every claude-* value the
// wire emits must have a modelOverrides entry (keyed by its suffix-stripped id)
// pointing at a zen alias — otherwise CC would send the raw claude-* id to
// api.hanzo.ai and reintroduce the 403.
func TestCarrierTiersAreOverridden(t *testing.T) {
env := anthropicWire("https://api.hanzo.ai", "hk-test", "claude-opus-4-8[1m]")
overrides := claudeModelOverrides()
for k, v := range env {
if len(v) < 6 || v[:6] != "claude" {
continue // only carrier ids need an override
}
zen, ok := overrides[stripModelSuffix(v)]
if !ok {
t.Errorf("%s=%q is a claude-* carrier with NO modelOverrides entry — it would reach api.hanzo.ai and 403", k, v)
continue
}
if len(zen) < 3 || zen[:3] != "zen" {
t.Errorf("%s=%q overrides to %q, which is not a zen alias", k, v, zen)
}
}
}
// TestZenCarrierRoundTrips checks the two-way mapping the fix depends on: every
// tier's zen id maps to a carrier, and that carrier (suffix-stripped) maps back
// to a served zen id via modelOverrides. An unknown id passes through unchanged.
func TestZenCarrierRoundTrips(t *testing.T) {
overrides := claudeModelOverrides()
for _, tier := range zenTiers {
carrier := zenCarrier(tier.zen)
if tier.carrier == "" {
// Direct tier: zenCarrier returns the served zen id itself, no override.
if carrier != tier.zen {
t.Errorf("direct tier %q must map to itself, got %q", tier.zen, carrier)
}
continue
}
if carrier == tier.zen {
t.Errorf("zenCarrier(%q) did not map to a carrier", tier.zen)
}
if got := overrides[stripModelSuffix(carrier)]; got != tier.zen {
t.Errorf("carrier %q for %q overrides to %q, want %q", carrier, tier.zen, got, tier.zen)
}
}
if got := zenCarrier("some-raw-upstream"); got != "some-raw-upstream" {
t.Errorf("unknown id must pass through unchanged, got %q", got)
}
}
// TestClaudeArgvForcesModel locks in the fix for "everything shows up as best":
// the claude agent must pass --model <resolved> on argv so a persisted /model
// selection (the reserved word "best") cannot override the zen5 model the
// launcher chose. ANTHROPIC_MODEL alone is not enough — /model beats it.
func TestClaudeArgvForcesModel(t *testing.T) {
agent := codeAgents["claude"]
argv := codeArgv(agent, "https://api.hanzo.ai", "zen5-pro", false, nil)
i := slices.Index(argv, "--model")
if i < 0 {
t.Fatalf("claude argv %q does not force --model (a persisted /model selection would win)", argv)
}
if i+1 >= len(argv) || argv[i+1] != "zen5-pro" {
t.Fatalf("claude argv %q: --model must be followed by the resolved id zen5-pro", argv)
}
// --model is forced in --safe mode too (model pinning is independent of
// the permission mode).
safeArgv := codeArgv(agent, "https://api.hanzo.ai", "zen5-pro", true, nil)
if i := slices.Index(safeArgv, "--model"); i < 0 || safeArgv[i+1] != "zen5-pro" {
t.Fatalf("--safe argv %q must still force --model zen5-pro", safeArgv)
}
}
// TestClaudeAppendsZenIdentityInAllModes locks in the identity fix: the claude
// agent appends --append-system-prompt <zenIdentityPrompt> so a Hanzo-served
// model self-identifies as a Hanzo Zen model. Identity is not a permission
// bypass, so it is present in --safe too (unlike --dangerously-skip-permissions).
// codex/dev (OpenAI wire) do not carry the Anthropic-only append.
func TestClaudeAppendsZenIdentityInAllModes(t *testing.T) {
agent := codeAgents["claude"]
check := func(argv []string) {
t.Helper()
i := slices.Index(argv, "--append-system-prompt")
if i < 0 || i+1 >= len(argv) || argv[i+1] != zenIdentityPrompt {
t.Fatalf("argv %q missing --append-system-prompt <zenIdentityPrompt>", argv)
}
}
// full-auto (default)
check(codeArgv(agent, "https://api.hanzo.ai", defaultCodeModel, false, nil))
// --safe keeps the identity (identity != permission bypass) but drops the bypass
safeArgv := codeArgv(agent, "https://api.hanzo.ai", defaultCodeModel, true, nil)
check(safeArgv)
if slices.Contains(safeArgv, "--dangerously-skip-permissions") {
t.Fatalf("--safe must not carry the permission bypass: %v", safeArgv)
}
// codex/dev (OpenAI wire) do not carry the Anthropic-only identity append
for _, name := range []string{"codex", "dev"} {
argv := codeArgv(codeAgents[name], "https://api.hanzo.ai", defaultCodeModel, false, nil)
if slices.Contains(argv, "--append-system-prompt") {
t.Fatalf("%s must not carry the claude-only identity append: %v", name, argv)
}
}
}
// TestClaudeAutoWiresMCP locks in the fix for "hanzo code wires no tools": the
// claude agent must opt into MCP auto-wiring, and the resolver must produce an
// stdio server config that is layered STRICTLY (repo .mcp.json ignored — it could
// exfiltrate the session bearer).
func TestClaudeAutoWiresMCP(t *testing.T) {
if !codeAgents["claude"].mcp {
t.Fatal("claude agent must set mcp:true so `hanzo code claude` starts with the Hanzo tool lattice")
}
// codex/dev are wired additively by their own provider config, not this seam.
for _, name := range []string{"codex", "dev"} {
if codeAgents[name].mcp {
t.Fatalf("%s must not use the claude MCP seam (it attaches Hanzo additively via -c)", name)
}
}
// The --mcp-config document is a valid single-server stdio config.
cfg := mcpConfigJSON("/usr/bin/hanzo-mcp", []string{"--project-dir", "/repo"})
var doc struct {
MCPServers map[string]struct {
Type string `json:"type"`
Command string `json:"command"`
Args []string `json:"args"`
} `json:"mcpServers"`
}
if err := json.Unmarshal([]byte(cfg), &doc); err != nil {
t.Fatalf("mcpConfigJSON is not valid JSON: %v", err)
}
h, ok := doc.MCPServers["hanzo"]
if !ok || h.Type != "stdio" || h.Command != "/usr/bin/hanzo-mcp" {
t.Fatalf("mcpConfigJSON: want one stdio server 'hanzo' → /usr/bin/hanzo-mcp, got %+v", doc.MCPServers)
}
if !slices.Contains(h.Args, "--project-dir") || !slices.Contains(h.Args, "/repo") {
t.Fatalf("mcpConfigJSON: server must be scoped to the project dir, got args %v", h.Args)
}
// mcpArgs writes the config into the isolated dir and returns the strict flags.
dir := t.TempDir()
t.Setenv("PATH", "/usr/bin/hanzo-mcp-not-here") // force the not-found path deterministically
flags, warn := mcpArgs(dir, "/repo")
if warn == "" || len(flags) != 0 {
t.Fatalf("with no hanzo-mcp on PATH, mcpArgs must warn and inject nothing, got flags=%v warn=%q", flags, warn)
}
}
// TestClaudeAgentAppliesCarrier locks in the runCode wiring: the claude agent
// carries the zen→carrier map (so the resolved zen model is handed to CC as a
// recognized 1M id), while codex/dev have no carrier (they speak OpenAI directly
// and must NOT rewrite the model).
func TestClaudeAgentAppliesCarrier(t *testing.T) {
if codeAgents["claude"].carrier == nil {
t.Fatal("claude agent must set a carrier so CC budgets the full context window")
}
if got := codeAgents["claude"].carrier("zen5-pro"); got != "claude-opus-4-8[1m]" {
t.Fatalf("claude carrier: zen5-pro must map to the opus carrier, got %q", got)
}
for _, name := range []string{"codex", "dev"} {
if codeAgents[name].carrier != nil {
t.Fatalf("%s speaks OpenAI directly and must not remap the model", name)
}
}
}
// servedZenIDs is the set of zen aliases api.hanzo.ai actually serves, confirmed
// live (2026-07). zen5-mini/zen5-max/zen5-ultra are catalog-listed but 404 or
// time out, so no tier may target them. Adding a tier forces confirming its id
// serves and listing it here — the guard below fails otherwise.
var servedZenIDs = map[string]bool{
"zen5-flash": true,
"zen5": true,
"zen5-pro": true,
"zen5-coder": true,
}
// TestZenTiersServeReal is the invariant a 1M-carrier is useless without: every
// tier's zen wire id must be one api.hanzo.ai serves. A carrier that budgets 1M
// but rewrites to a 404 id just fails later, opaquely.
func TestZenTiersServeReal(t *testing.T) {
for _, tier := range zenTiers {
if !servedZenIDs[tier.zen] {
t.Errorf("tier %q → zen id %q is not in the confirmed-served set; a carrier to an unserved id 404s", tier.carrier, tier.zen)
}
}
}
// TestUpsertClaudeSettings checks the seed: a fresh dir gets base defaults plus
// the carrier→zen modelOverrides, and a re-seed REFRESHES modelOverrides (policy)
// while PRESERVING a user's own edits to other keys (preference).
func TestUpsertClaudeSettings(t *testing.T) {
path := filepath.Join(t.TempDir(), "settings.json")
if err := upsertClaudeSettings(path); err != nil {
t.Fatalf("first seed failed: %v", err)
}
read := func() map[string]any {
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read settings: %v", err)
}
var m map[string]any
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("settings.json is not valid JSON: %v", err)
}
return m
}
s := read()
if s["effortLevel"] != "max" {
t.Errorf("base defaults missing: effortLevel = %v", s["effortLevel"])
}
ov, ok := s["modelOverrides"].(map[string]any)
if !ok {
t.Fatalf("modelOverrides missing or wrong type: %T", s["modelOverrides"])
}
if ov["claude-opus-4-8"] != "zen5-pro" {
t.Errorf("modelOverrides[claude-opus-4-8] = %v, want zen5-pro", ov["claude-opus-4-8"])
}
// User edits a preference and adds a key; re-seed must keep both.
s["effortLevel"] = "low"
s["userKey"] = "keepme"
b, _ := json.Marshal(s)
if err := os.WriteFile(path, b, 0o600); err != nil {
t.Fatal(err)
}
if err := upsertClaudeSettings(path); err != nil {
t.Fatalf("re-seed failed: %v", err)
}
s2 := read()
if s2["effortLevel"] != "low" {
t.Errorf("re-seed clobbered user edit: effortLevel = %v, want low", s2["effortLevel"])
}
if s2["userKey"] != "keepme" {
t.Errorf("re-seed dropped user key: userKey = %v", s2["userKey"])
}
ov2, _ := s2["modelOverrides"].(map[string]any)
if ov2["claude-opus-4-8"] != "zen5-pro" {
t.Errorf("re-seed lost modelOverrides: %v", ov2)
}
}
+3 -3
View File
@@ -365,7 +365,7 @@ func printTarget(w io.Writer, t *Target) {
}
// ---------------------------------------------------------------------------
// build — platform-native (arcd) build enqueue.
// build — platform-native build (runner fabric) enqueue.
// ---------------------------------------------------------------------------
func newBuildCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
@@ -373,8 +373,8 @@ func newBuildCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
var buildToken string
cmd := &cobra.Command{
Use: "build <repo>",
Short: "Enqueue a platform-native (arcd) build (no GitHub builders)",
Long: "Enqueue a build on the platform's native CI fabric (arcd). Builds and pushes\n" +
Short: "Enqueue a platform-native build on the runner fabric (no GitHub builders)",
Long: "Enqueue a build on the platform's native runner fabric. Builds and pushes\n" +
"the named image at a SHA; on completion the platform patches the operator\n" +
"Service CR (build-job → deploy). Requires a live registered runner for the\n" +
"target pool (409 otherwise).",
+1 -1
View File
@@ -136,7 +136,7 @@ func TestBuildCommandValidation(t *testing.T) {
func TestBuildCommand(t *testing.T) {
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/arcd/enqueue" {
if r.URL.Path != "/v1/runner" {
t.Errorf("path = %s", r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "Bearer bt" {
+182
View File
@@ -0,0 +1,182 @@
// device.go — RFC 8628 Device Authorization Grant for `hanzo login`: the ONE
// way any machine signs in. The CLI asks IAM for a device+user code, shows the
// verification link as text AND a terminal QR (scan with a phone), and polls
// the token endpoint until the user approves in any browser session. No
// password ever touches this terminal; works headless (GPU boxes, ssh, CI).
package cli
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/mdp/qrterminal/v3"
"github.com/spf13/cobra"
)
// deviceAuthResp is the RFC 8628 device authorization response.
type deviceAuthResp struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int64 `json:"expires_in"`
Interval int64 `json:"interval"`
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
}
const deviceGrantType = "urn:ietf:params:oauth:grant-type:device_code"
// defaultDeviceClientID is the first-party client the device grant runs as.
// hanzo-app is the one Hanzo client IAM seeds with device_code enabled
// (iam cmd/iam/cli/init_apps.go brandGrantTypes); hanzo-console stays the
// password-grant client. hanzo-dev's live device flow uses the same pair of
// endpoints and this client, so the two CLIs share one server-side config.
const defaultDeviceClientID = "hanzo-app"
// rawForm posts a form to an oauth endpoint and returns the decoded token
// response WITHOUT mapping OAuth errors to Go errors — the device poll must
// inspect authorization_pending / slow_down itself.
func (c *iamClient) rawForm(ctx context.Context, endpoint string, form url.Values) (*tokenResp, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.issuer+endpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "hanzo-cli/"+Version)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var tr tokenResp
if err := json.Unmarshal(body, &tr); err != nil {
return nil, fmt.Errorf("iam %s: HTTP %d: %s", endpoint, resp.StatusCode, strings.TrimSpace(string(body)))
}
return &tr, nil
}
// deviceAuth starts the device flow: mints a device_code + user_code pair.
// Query-param shape matches hanzo-dev's verified client (oidc_device_auth.rs).
func (c *iamClient) deviceAuth(ctx context.Context, scope string) (*deviceAuthResp, error) {
q := url.Values{"client_id": {c.clientID}, "scope": {scope}, "response_type": {"device_code"}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.issuer+"/v1/iam/oauth/device?"+q.Encode(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "hanzo-cli/"+Version)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var da deviceAuthResp
if err := json.Unmarshal(body, &da); err != nil {
return nil, fmt.Errorf("iam device auth: HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
if da.Error != "" {
return nil, fmt.Errorf("iam device auth: %s: %s", da.Error, da.ErrorDesc)
}
if da.DeviceCode == "" || da.UserCode == "" {
return nil, fmt.Errorf("iam device auth: HTTP %d: no device_code in response", resp.StatusCode)
}
return &da, nil
}
// pollDeviceToken polls the token endpoint until the user approves, the code
// expires, or ctx ends. authorization_pending keeps polling; slow_down backs
// off per RFC 8628 §3.5.
func (c *iamClient) pollDeviceToken(ctx context.Context, da *deviceAuthResp) (*tokenResp, error) {
interval := time.Duration(max64(da.Interval, 1)) * time.Second
deadline := time.Now().Add(time.Duration(da.ExpiresIn) * time.Second)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(interval):
}
if time.Now().After(deadline) {
return nil, fmt.Errorf("device code expired before approval — run `hanzo login` again")
}
tr, err := c.rawForm(ctx, "/v1/iam/oauth/token", url.Values{
"grant_type": {deviceGrantType},
"client_id": {c.clientID},
"device_code": {da.DeviceCode},
})
if err != nil {
return nil, err
}
switch tr.Error {
case "":
if tr.AccessToken == "" {
return nil, fmt.Errorf("iam device token: empty access_token")
}
return tr, nil
case "authorization_pending":
// approved not yet — keep waiting
case "slow_down":
interval += 5 * time.Second
case "expired_token":
return nil, fmt.Errorf("device code expired before approval — run `hanzo login` again")
default:
return nil, fmt.Errorf("iam device token: %s: %s", tr.Error, tr.ErrorDesc)
}
}
}
// runDeviceLogin drives the interactive device sign-in and returns credentials.
func runDeviceLogin(cmd *cobra.Command, env *Env, scope string) (*Credentials, error) {
out := cmd.OutOrStdout()
// An explicit --client-id/HANZO_CLIENT_ID override wins; otherwise the
// device grant runs as hanzo-app (see defaultDeviceClientID).
clientID := env.ClientID
if clientID == "" || clientID == defaultClientID {
clientID = defaultDeviceClientID
}
iam := newIAMClient(env.IAMIssuer, clientID)
da, err := iam.deviceAuth(cmd.Context(), scope)
if err != nil {
return nil, err
}
link := firstNonEmpty(da.VerificationURIComplete, da.VerificationURI)
fmt.Fprintf(out, "\nSign in on any device:\n\n")
printQR(out, link)
fmt.Fprintf(out, "\n %s\n", link)
if da.VerificationURI != "" && da.UserCode != "" {
fmt.Fprintf(out, " or open %s and enter code %s\n", da.VerificationURI, da.UserCode)
}
fmt.Fprintf(out, "\nWaiting for approval…\n")
tr, err := iam.pollDeviceToken(cmd.Context(), da)
if err != nil {
return nil, err
}
return credsFromToken(tr), nil
}
// printQR renders a scannable QR of the verification link using half blocks
// (compact enough for a default 80×24 terminal).
func printQR(w io.Writer, link string) {
qrterminal.GenerateWithConfig(link, qrterminal.Config{
Level: qrterminal.L,
Writer: w,
HalfBlocks: true,
QuietZone: 1,
})
}
func max64(a, b int64) int64 {
if a > b {
return a
}
return b
}
+107
View File
@@ -0,0 +1,107 @@
package cli
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDeviceAuth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/iam/oauth/device" {
t.Fatalf("path = %s", r.URL.Path)
}
if got := r.URL.Query().Get("client_id"); got != "hanzo-app" {
t.Fatalf("client_id = %q", got)
}
if got := r.URL.Query().Get("response_type"); got != "device_code" {
t.Fatalf("response_type = %q", got)
}
_ = json.NewEncoder(w).Encode(map[string]any{
"device_code": "dc-1",
"user_code": "WDJB-MJHT",
"verification_uri": srv0 + "/login/oauth/device",
"verification_uri_complete": srv0 + "/login/oauth/device/WDJB-MJHT",
"expires_in": 900,
"interval": 1,
})
}))
defer srv.Close()
srv0 = srv.URL
iam := newIAMClient(srv.URL, "hanzo-app")
da, err := iam.deviceAuth(context.Background(), "openid profile email")
if err != nil {
t.Fatal(err)
}
if da.DeviceCode != "dc-1" || da.UserCode != "WDJB-MJHT" {
t.Fatalf("unexpected device auth: %+v", da)
}
if !strings.HasSuffix(da.VerificationURIComplete, "/WDJB-MJHT") {
t.Fatalf("verification_uri_complete = %q", da.VerificationURIComplete)
}
}
// srv0 lets the handler reference its own server URL in the response body.
var srv0 string
func TestPollDeviceTokenPendingThenIssued(t *testing.T) {
polls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/iam/oauth/token" {
t.Fatalf("path = %s", r.URL.Path)
}
_ = r.ParseForm()
if got := r.Form.Get("grant_type"); got != deviceGrantType {
t.Fatalf("grant_type = %q", got)
}
if got := r.Form.Get("device_code"); got != "dc-1" {
t.Fatalf("device_code = %q", got)
}
polls++
if polls < 3 {
_ = json.NewEncoder(w).Encode(map[string]string{"error": "authorization_pending"})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "tok-1", "token_type": "Bearer", "expires_in": 3600})
}))
defer srv.Close()
iam := newIAMClient(srv.URL, "hanzo-console")
tr, err := iam.pollDeviceToken(context.Background(), &deviceAuthResp{DeviceCode: "dc-1", ExpiresIn: 30, Interval: 0})
if err != nil {
t.Fatal(err)
}
if tr.AccessToken != "tok-1" || polls != 3 {
t.Fatalf("token = %q polls = %d", tr.AccessToken, polls)
}
}
func TestPollDeviceTokenExpired(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"error": "expired_token"})
}))
defer srv.Close()
iam := newIAMClient(srv.URL, "hanzo-console")
_, err := iam.pollDeviceToken(context.Background(), &deviceAuthResp{DeviceCode: "dc-1", ExpiresIn: 30, Interval: 0})
if err == nil || !strings.Contains(err.Error(), "expired") {
t.Fatalf("err = %v", err)
}
}
func TestPollDeviceTokenDenied(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"error": "access_denied", "error_description": "user refused"})
}))
defer srv.Close()
iam := newIAMClient(srv.URL, "hanzo-console")
_, err := iam.pollDeviceToken(context.Background(), &deviceAuthResp{DeviceCode: "dc-1", ExpiresIn: 30, Interval: 0})
if err == nil || !strings.Contains(err.Error(), "access_denied") {
t.Fatalf("err = %v", err)
}
}
+199
View File
@@ -0,0 +1,199 @@
package cli
// engine.go — `hanzo engine install|serve|status`: manage a local hanzo-engine
// (the `hanzoai` OpenAI + Anthropic model server) on THIS machine.
//
// One source of truth for install logic: `install` runs the SAME install.sh /
// install.ps1 the `curl … | sh` one-liner uses (it downloads the prebuilt,
// cosign-signed binary from the latest github.com/hanzoai/engine release), so the
// CLI never re-implements platform detection or verification. `serve` launches the
// installed binary (`hanzoai --port P run -m MODEL`); `status` probes it, reusing
// the same /v1/models probe `hanzo gpu connect --serve-engine` advertises with.
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
"github.com/spf13/cobra"
)
const (
installScriptSh = "https://raw.githubusercontent.com/hanzoai/engine/main/install.sh"
installScriptPS = "https://raw.githubusercontent.com/hanzoai/engine/main/install.ps1"
engineBinName = "hanzoai"
)
func newEngineCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "engine",
Short: "Run a local hanzo-engine (OpenAI + Anthropic model server)",
Long: "Install, serve, and inspect a local hanzo-engine on this machine.\n" +
"`install` downloads the prebuilt, signed `hanzoai` binary; `serve` runs it on\n" +
":1234; `status` shows whether it is up and which models it serves.",
}
// install ----------------------------------------------------------------
var version, dir string
install := &cobra.Command{
Use: "install",
Short: "Download + install the prebuilt hanzoai binary (runs the canonical install script)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return runEngineInstall(cmd, version, dir)
},
}
install.Flags().StringVar(&version, "engine-version", "", "install a specific release tag (default: latest)")
install.Flags().StringVar(&dir, "dir", "", "install directory (default: /usr/local/bin or ~/.local/bin)")
// serve ------------------------------------------------------------------
var model string
var port int
serve := &cobra.Command{
Use: "serve",
Short: "Serve a model with the local hanzoai binary (hanzoai --port P run -m MODEL)",
Long: "Launch the installed hanzoai server. Any args after `--` are passed through to\n" +
"the underlying `hanzoai … run` invocation (e.g. `-- --max-seqs 32`).",
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, extra []string) error {
return runEngineServe(cmd, model, port, extra)
},
}
serve.Flags().StringVarP(&model, "model", "m", "Qwen/Qwen3-4B", "model to serve (HF repo id or local path)")
serve.Flags().IntVarP(&port, "port", "p", 1234, "port to serve the OpenAI + Anthropic API on")
// status -----------------------------------------------------------------
var url string
status := &cobra.Command{
Use: "status",
Short: "Show whether a local hanzo-engine is up and what it serves",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return runEngineStatus(cmd, envOf(), firstNonEmpty(url, defaultEngineURL))
},
}
status.Flags().StringVar(&url, "url", defaultEngineURL, "local engine URL to probe (GET /v1/models)")
cmd.AddCommand(install, serve, status)
return cmd
}
// runEngineInstall shells out to the canonical install script so there is exactly
// one implementation of platform detection + signature verification.
func runEngineInstall(cmd *cobra.Command, version, dir string) error {
env := os.Environ()
if version != "" {
env = append(env, "HANZOAI_VERSION="+version)
}
if dir != "" {
env = append(env, "HANZOAI_INSTALL_DIR="+dir)
}
var sh *exec.Cmd
if runtime.GOOS == "windows" {
sh = exec.CommandContext(cmd.Context(), "powershell", "-NoProfile", "-Command",
"irm "+installScriptPS+" | iex")
} else {
// curl … | sh — the exact one-liner documented in the README.
sh = exec.CommandContext(cmd.Context(), "sh", "-c",
"curl -fsSL "+installScriptSh+" | sh")
}
sh.Env = env
sh.Stdin, sh.Stdout, sh.Stderr = os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr()
if err := sh.Run(); err != nil {
return fmt.Errorf("install script failed: %w", err)
}
return nil
}
// runEngineServe execs the installed hanzoai binary. On Unix it replaces this
// process (syscall.Exec) so signals + exit code flow straight through; on Windows
// it runs as a child with inherited stdio.
func runEngineServe(cmd *cobra.Command, model string, port int, extra []string) error {
bin, err := findEngineBinary()
if err != nil {
return err
}
args := []string{bin, "--port", fmt.Sprintf("%d", port), "run", "-m", model}
args = append(args, extra...)
fmt.Fprintf(cmd.ErrOrStderr(), "→ %s\n", exec.Command(bin, args[1:]...).String())
return execEngine(bin, args)
}
// runEngineStatus probes the local engine and prints (or JSON-emits) its state,
// reusing the same /v1/models probe the fleet advertisement uses.
func runEngineStatus(cmd *cobra.Command, env *Env, url string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), 6*time.Second)
defer cancel()
adv := &engineAdvertisement{URL: url, APIs: []string{"openai", "anthropic"}}
if models, perr := probeEngine(ctx, url); perr != nil {
adv.Status = "unreachable"
} else {
adv.Status = "ready"
adv.Models = models
}
bin, _ := findEngineBinary()
return env.emit(map[string]any{"url": url, "status": adv.Status, "models": adv.Models, "binary": bin},
func(out io.Writer) {
fmt.Fprintf(out, "engine %s — %s\n", adv.URL, describeEngine(adv))
if len(adv.Models) > 0 {
for _, m := range adv.Models {
fmt.Fprintf(out, " model %s\n", m)
}
}
if bin != "" {
fmt.Fprintf(out, "binary %s\n", bin)
} else {
fmt.Fprintln(out, "binary not installed — run `hanzo engine install`")
}
if adv.Status != "ready" {
fmt.Fprintf(out, "hint start it with `hanzo engine serve -m Qwen/Qwen3-4B --port %s`\n",
portOf(url))
}
})
}
// findEngineBinary locates the installed hanzoai binary: PATH first, then the
// directories install.sh / install.ps1 write to.
func findEngineBinary() (string, error) {
name := engineBinName
if runtime.GOOS == "windows" {
name += ".exe"
}
if p, err := exec.LookPath(name); err == nil {
return p, nil
}
home, _ := os.UserHomeDir()
var dirs []string
if runtime.GOOS == "windows" {
if la := os.Getenv("LOCALAPPDATA"); la != "" {
dirs = append(dirs, filepath.Join(la, "Hanzo", "bin"))
}
} else {
dirs = append(dirs, "/usr/local/bin", filepath.Join(home, ".local", "bin"), filepath.Join(home, ".hanzo", "bin"))
}
for _, d := range dirs {
p := filepath.Join(d, name)
if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
return p, nil
}
}
return "", fmt.Errorf("hanzoai not found on PATH or in the default install dirs — run `hanzo engine install`")
}
func portOf(url string) string {
// best-effort: pull the ":<port>" tail for the hint
for i := len(url) - 1; i >= 0; i-- {
if url[i] == ':' {
return url[i+1:]
}
}
return "1234"
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !windows
package cli
import (
"os"
"syscall"
)
// execEngine replaces the current process with hanzoai so signals (Ctrl-C) and
// the exit code flow straight through — `hanzo engine serve` becomes hanzoai.
func execEngine(bin string, args []string) error {
return syscall.Exec(bin, args, os.Environ())
}
+16
View File
@@ -0,0 +1,16 @@
//go:build windows
package cli
import (
"os"
"os/exec"
)
// execEngine runs hanzoai as a child with inherited stdio (Windows has no exec()).
// The child shares the console, so Ctrl-C reaches it; we return its exit error.
func execEngine(bin string, args []string) error {
c := exec.Command(bin, args[1:]...)
c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr
return c.Run()
}
+96
View File
@@ -0,0 +1,96 @@
package cli
import (
"bytes"
"context"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/spf13/cobra"
)
// TestEngineCmdWiring asserts `hanzo engine` exposes install/serve/status with the
// documented flags — the contract install.sh and the docs promise.
func TestEngineCmdWiring(t *testing.T) {
env := &Env{Output: "table"}
cmd := newEngineCmd(func() *Env { return env }, &globalFlags{})
want := map[string]bool{"install": false, "serve": false, "status": false}
for _, sub := range cmd.Commands() {
if _, ok := want[sub.Name()]; ok {
want[sub.Name()] = true
}
}
for name, found := range want {
if !found {
t.Fatalf("engine subcommand %q missing", name)
}
}
serve, _, _ := cmd.Find([]string{"serve"})
if serve.Flags().Lookup("model") == nil || serve.Flags().Lookup("port") == nil {
t.Fatalf("serve must have --model and --port")
}
status, _, _ := cmd.Find([]string{"status"})
if status.Flags().Lookup("url") == nil {
t.Fatalf("status must have --url")
}
}
// TestEngineStatusReady probes a stub engine and reports it ready with its models.
func TestEngineStatusReady(t *testing.T) {
engine := stubEngine(t, "default", "zen-omni-30b")
defer engine.Close()
var buf bytes.Buffer
env := &Env{Output: "table", out: &buf}
cmd := &cobra.Command{}
cmd.SetContext(context.Background())
if err := runEngineStatus(cmd, env, engine.URL); err != nil {
t.Fatalf("status: %v", err)
}
out := buf.String()
if !strings.Contains(out, "ready") || !strings.Contains(out, "zen-omni-30b") {
t.Fatalf("status output missing ready/model:\n%s", out)
}
}
// TestEngineStatusUnreachable reports a down engine as unreachable (not an error).
func TestEngineStatusUnreachable(t *testing.T) {
var buf bytes.Buffer
env := &Env{Output: "table", out: &buf}
cmd := &cobra.Command{}
cmd.SetContext(context.Background())
// A port with nothing listening.
if err := runEngineStatus(cmd, env, "http://127.0.0.1:1"); err != nil {
t.Fatalf("status should not error on a down engine: %v", err)
}
if !strings.Contains(buf.String(), "unreachable") {
t.Fatalf("expected 'unreachable', got:\n%s", buf.String())
}
}
// TestFindEngineBinary finds hanzoai on PATH.
func TestFindEngineBinary(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("PATH exe probe differs on Windows")
}
dir := t.TempDir()
bin := filepath.Join(dir, engineBinName)
if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir)
got, err := findEngineBinary()
if err != nil {
t.Fatalf("findEngineBinary: %v", err)
}
if got != bin {
t.Fatalf("found %q, want %q", got, bin)
}
}
+1397
View File
File diff suppressed because it is too large Load Diff
+247
View File
@@ -0,0 +1,247 @@
package cli
// gpu_engine_test.go — the `--serve-engine` capability: probing a local hanzo-engine
// and assembling the fleet advertisement + provider registration. Uses an httptest
// stub for the engine so no model (or GPU) is needed.
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// stubEngine stands in for hanzo-engine's OpenAI-shaped GET /v1/models.
func stubEngine(t *testing.T, models ...string) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/v1/models", func(w http.ResponseWriter, _ *http.Request) {
data := make([]map[string]any, 0, len(models))
for _, m := range models {
data = append(data, map[string]any{"id": m, "object": "model", "owned_by": "local"})
}
_ = json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data})
})
return httptest.NewServer(mux)
}
func TestProbeEngine(t *testing.T) {
srv := stubEngine(t, "default", "zen-omni-30b")
defer srv.Close()
got, err := probeEngine(context.Background(), srv.URL)
if err != nil {
t.Fatalf("probeEngine: %v", err)
}
if len(got) != 2 || got[0] != "default" || got[1] != "zen-omni-30b" {
t.Fatalf("models = %v, want [default zen-omni-30b]", got)
}
}
func TestProbeEngineDown(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "loading", http.StatusServiceUnavailable)
}))
defer srv.Close()
if _, err := probeEngine(context.Background(), srv.URL); err == nil {
t.Fatal("probeEngine: want error for a 503 engine, got nil")
}
}
func TestRefreshEngineAdvertises(t *testing.T) {
srv := stubEngine(t, "default")
defer srv.Close()
w := &worker{
identity: "gb10",
hostname: "gb10",
jobsNS: "gpu-jobs",
serveEngine: true,
engineURL: srv.URL,
engineAdvURL: "http://node.example:1234",
}
if changed := w.refreshEngine(context.Background()); !changed {
t.Fatal("first refreshEngine should report a change (nil -> ready)")
}
if w.engine == nil || w.engine.Status != "ready" {
t.Fatalf("engine = %+v, want status ready", w.engine)
}
if w.engine.URL != "http://node.example:1234" {
t.Fatalf("advertised URL = %q, want the endpoint, not the local probe URL", w.engine.URL)
}
if !contains(w.engine.APIs, "openai") || !contains(w.engine.APIs, "anthropic") {
t.Fatalf("APIs = %v, want both openai and anthropic (hanzo-engine serves both)", w.engine.APIs)
}
if len(w.engine.Models) != 1 || w.engine.Models[0] != "default" {
t.Fatalf("models = %v, want [default]", w.engine.Models)
}
// A second probe with an unchanged engine is a no-op (no needless re-register).
if changed := w.refreshEngine(context.Background()); changed {
t.Fatal("second refreshEngine with an unchanged engine should report no change")
}
}
func TestRefreshEngineUnreachable(t *testing.T) {
w := &worker{
identity: "gb10",
serveEngine: true,
engineURL: "http://127.0.0.1:0", // nothing listening
engineAdvURL: "http://127.0.0.1:0",
}
w.refreshEngine(context.Background())
if w.engine == nil || w.engine.Status != "unreachable" {
t.Fatalf("engine = %+v, want status unreachable", w.engine)
}
}
func TestBuildRegistrationCarriesEngine(t *testing.T) {
srv := stubEngine(t, "default")
defer srv.Close()
w := &worker{
identity: "gb10",
hostname: "gb10",
jobsNS: "gpu-jobs",
gpus: []gpuInfo{{Name: "NVIDIA GB10", MemoryTotal: "122880 MiB"}},
serveEngine: true,
engineURL: srv.URL,
engineAdvURL: "http://node.example:1234",
}
w.refreshEngine(context.Background())
reg := w.buildRegistration()
if !contains(reg.Capabilities, studioCap) || !contains(reg.Capabilities, engineCap) {
t.Fatalf("capabilities = %v, want both %q and %q", reg.Capabilities, studioCap, engineCap)
}
if reg.Engine == nil || reg.Engine.URL != "http://node.example:1234" {
t.Fatalf("registration engine = %+v, want the advertised endpoint", reg.Engine)
}
// The presence record's Input must carry the endpoint so GET /v1/fleet/workers
// (which decodes this exact JSON) can advertise it.
raw, err := json.Marshal(reg)
if err != nil {
t.Fatalf("marshal registration: %v", err)
}
for _, want := range []string{`"engine.serve"`, `"http://node.example:1234"`, `"openai"`, `"anthropic"`} {
if !strings.Contains(string(raw), want) {
t.Fatalf("registration JSON missing %s:\n%s", want, raw)
}
}
}
func TestCapabilitiesWithoutEngine(t *testing.T) {
w := &worker{serveEngine: false}
caps := w.capabilities()
if len(caps) != 1 || caps[0] != studioCap {
t.Fatalf("capabilities = %v, want just [%q] when not serving an engine", caps, studioCap)
}
}
func TestProviderBodyIsOpenAICompatible(t *testing.T) {
w := &worker{
identity: "gb10",
engine: &engineAdvertisement{URL: "http://node.example:1234", Status: "ready", Models: []string{"zen-omni-30b"}},
}
body := w.providerBody()
if body["type"] != "Local" {
t.Fatalf("type = %v, want Local (OpenAI-compatible; gateway auto-appends /v1)", body["type"])
}
if body["providerUrl"] != "http://node.example:1234" {
t.Fatalf("providerUrl = %v", body["providerUrl"])
}
if body["name"] != "gpu-gb10" {
t.Fatalf("name = %v, want gpu-gb10", body["name"])
}
if body["subType"] != "zen-omni-30b" {
t.Fatalf("subType = %v, want the served model", body["subType"])
}
}
// TestConnectServeEngineRoundTrip closes the loop end-to-end on this box, no model
// and no production: a stub hanzo-engine (GET /v1/models) + a stub cloud that stores
// the presence Input and serves it back on GET /v1/fleet/workers. It exercises the
// real chain — probe → build registration → POST the fleet activity → GET
// /v1/fleet/workers → the engine endpoint is advertised.
func TestConnectServeEngineRoundTrip(t *testing.T) {
engine := stubEngine(t, "default", "zen-omni-30b")
defer engine.Close()
var storedInput registration // what the CLI POSTed as the presence record's Input
cloud := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/fleet/activities"):
var body struct {
Input registration `json:"input"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
storedInput = body.Input
w.WriteHeader(http.StatusOK)
case r.Method == http.MethodGet && r.URL.Path == "/v1/fleet/workers":
// Fold the stored registration into the fleet worker shape, exactly as
// clients/visor/fleet.go byoWorkers does.
_ = json.NewEncoder(w).Encode(map[string]any{"workers": []fleetWorker{{
ID: "gb10", Hostname: storedInput.Hostname, Provider: "byo", Status: "online",
GPUs: storedInput.GPUs, Capabilities: storedInput.Capabilities, Engine: storedInput.Engine,
}}})
default: // namespace ensure + anything else
w.WriteHeader(http.StatusOK)
}
}))
defer cloud.Close()
t.Setenv("HANZO_TOKEN", "test-token") // ensureToken honors this; no `hanzo login` needed
w := &worker{
env: &Env{CloudURL: cloud.URL},
http: &http.Client{Timeout: 5 * time.Second},
baseURL: cloud.URL,
identity: "gb10",
hostname: "gb10",
jobsNS: "gpu-jobs",
gpus: []gpuInfo{{Name: "NVIDIA GB10", MemoryTotal: "122880 MiB"}},
handlers: map[string]jobHandler{},
serveEngine: true,
engineURL: engine.URL,
engineAdvURL: "http://node.example:1234",
}
ctx := context.Background()
w.refreshEngine(ctx)
if err := w.register(ctx); err != nil {
t.Fatalf("register: %v", err)
}
var resp struct {
Workers []fleetWorker `json:"workers"`
}
if _, err := w.call(ctx, http.MethodGet, "/v1/fleet/workers", nil, &resp); err != nil {
t.Fatalf("GET /v1/fleet/workers: %v", err)
}
if len(resp.Workers) != 1 {
t.Fatalf("workers = %d, want 1", len(resp.Workers))
}
fw := resp.Workers[0]
if !contains(fw.Capabilities, engineCap) {
t.Fatalf("fleet worker capabilities = %v, want engine.serve", fw.Capabilities)
}
if fw.Engine == nil || fw.Engine.URL != "http://node.example:1234" || fw.Engine.Status != "ready" {
t.Fatalf("fleet worker engine = %+v, want the advertised ready endpoint", fw.Engine)
}
if len(fw.Engine.Models) != 2 {
t.Fatalf("fleet worker engine models = %v, want 2", fw.Engine.Models)
}
}
func contains(xs []string, v string) bool {
for _, x := range xs {
if x == v {
return true
}
}
return false
}
+92
View File
@@ -0,0 +1,92 @@
package cli
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
// TestMirrorRenders verifies the render mirror: it scans the local studio output
// tree and POSTs every image (new or changed) to /v1/library/upload with the node's
// identity + subfolder + bearer, skips unchanged files across scans, and re-uploads
// a changed file. This is the path that lands EVERY render in studio.hanzo.ai even
// when it was produced outside the job/claim path.
func TestMirrorRenders(t *testing.T) {
t.Setenv("HANZO_TOKEN", "test-bearer")
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "renders"), 0o755); err != nil {
t.Fatal(err)
}
write := func(rel, body string) {
if err := os.WriteFile(filepath.Join(dir, filepath.FromSlash(rel)), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
write("renders/a.png", "\x89PNG-a")
write("top.jpg", "jpg-top")
write("notes.txt", "not an image")
type up struct{ name, node, subpath, auth string }
var got []up
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/library/upload" {
http.Error(w, "not found", http.StatusNotFound)
return
}
_ = r.ParseMultipartForm(1 << 20)
name := ""
if r.MultipartForm != nil {
for _, fh := range r.MultipartForm.File["image"] {
name = fh.Filename
}
}
got = append(got, up{
name: name,
node: r.URL.Query().Get("node"),
subpath: r.URL.Query().Get("subpath"),
auth: r.Header.Get("Authorization"),
})
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true,"path":"x"}`))
}))
defer srv.Close()
w := &worker{env: &Env{}, http: &http.Client{Timeout: 10 * time.Second}, identity: "spark"}
seen := map[string]int64{}
var buf bytes.Buffer
w.mirrorRenders(context.Background(), &buf, dir, srv.URL, seen)
if len(got) != 2 {
t.Fatalf("uploaded %d files, want 2 images (the .txt is skipped): %+v", len(got), got)
}
var a *up
for i := range got {
if got[i].name == "a.png" {
a = &got[i]
}
}
if a == nil || a.subpath != "renders" || a.node != "spark" || a.auth != "Bearer test-bearer" {
t.Fatalf("renders/a.png upload = %+v, want subpath=renders node=spark bearer set", a)
}
// A second scan re-uploads nothing (seen matches every size).
got = nil
w.mirrorRenders(context.Background(), &buf, dir, srv.URL, seen)
if len(got) != 0 {
t.Fatalf("second scan uploaded %d files, want 0 (all unchanged): %+v", len(got), got)
}
// A changed file is re-uploaded on the next scan.
write("renders/a.png", "\x89PNG-a-grew")
got = nil
w.mirrorRenders(context.Background(), &buf, dir, srv.URL, seen)
if len(got) != 1 || got[0].name != "a.png" {
t.Fatalf("after change, uploaded %+v, want just renders/a.png", got)
}
}
+109
View File
@@ -0,0 +1,109 @@
package cli
import (
"encoding/json"
"testing"
)
func TestSharePolicyReject(t *testing.T) {
studioInput := json.RawMessage(`{"prompt":{},"org":"karma","project":"swimwear"}`)
engineInput := json.RawMessage(`{"model":"Qwen/Qwen3-4B","org":"hanzo"}`)
cases := []struct {
name string
policy *SharePolicy
jobType string
input json.RawMessage
allow bool // true == reject() returns ""
}{
{"nil policy is permissive", nil, "studio.render", studioInput, true},
{"empty policy is permissive", &SharePolicy{}, "studio.render", studioInput, true},
{
"job type allowed",
&SharePolicy{AllowedJobTypes: []string{"studio.render"}},
"studio.render", studioInput, true,
},
{
"job type not allowed",
&SharePolicy{AllowedJobTypes: []string{"engine.serve"}},
"studio.render", studioInput, false,
},
{
"org allowed",
&SharePolicy{AllowedOrgs: []string{"karma", "hanzo"}},
"studio.render", studioInput, true,
},
{
"org not allowed",
&SharePolicy{AllowedOrgs: []string{"hanzo"}},
"studio.render", studioInput, false,
},
{
"project not allowed",
&SharePolicy{AllowedProjects: []string{"lifestyle"}},
"studio.render", studioInput, false,
},
{
"model allowed",
&SharePolicy{AllowedModels: []string{"Qwen/Qwen3-4B"}},
"engine.serve", engineInput, true,
},
{
"model not allowed",
&SharePolicy{AllowedModels: []string{"meta/llama-3"}},
"engine.serve", engineInput, false,
},
{
"absent field skips its gate (input has no project)",
&SharePolicy{AllowedProjects: []string{"lifestyle"}},
"engine.serve", engineInput, true,
},
{
"combined: all gates pass",
&SharePolicy{
AllowedJobTypes: []string{"studio.render"},
AllowedOrgs: []string{"karma"},
AllowedProjects: []string{"swimwear"},
},
"studio.render", studioInput, true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
reason := tc.policy.reject(tc.jobType, tc.input)
if got := reason == ""; got != tc.allow {
t.Fatalf("reject()=%q; want allow=%v", reason, tc.allow)
}
})
}
}
func TestLoadSharePolicyInline(t *testing.T) {
t.Setenv("HANZO_GPU_POLICY", `{"allowedJobTypes":["studio.render"],"allowedOrgs":["karma"],"maxConcurrent":2}`)
p, err := loadSharePolicy()
if err != nil {
t.Fatalf("loadSharePolicy: %v", err)
}
if p == nil {
t.Fatal("expected a policy, got nil")
}
if len(p.AllowedJobTypes) != 1 || p.AllowedJobTypes[0] != "studio.render" {
t.Fatalf("AllowedJobTypes=%v", p.AllowedJobTypes)
}
if p.MaxConcurrent != 2 {
t.Fatalf("MaxConcurrent=%d", p.MaxConcurrent)
}
if p.reject("engine.serve", json.RawMessage(`{}`)) == "" {
t.Fatal("expected engine.serve to be rejected by studio.render-only policy")
}
}
func TestLoadSharePolicyUnset(t *testing.T) {
t.Setenv("HANZO_GPU_POLICY", "")
t.Setenv("HANZO_GPU_POLICY_FILE", "")
p, err := loadSharePolicy()
if err != nil || p != nil {
t.Fatalf("unset policy: got (%v, %v), want (nil, nil)", p, err)
}
}
+55
View File
@@ -0,0 +1,55 @@
package cli
import (
"context"
"net/http"
"os"
"testing"
"time"
)
// TestUploadOutputsIntegration exercises the real BYO-GPU result-upload path:
// fetchLocalOutput pulls a finished render from the LOCAL studio's /view and
// postGalleryOutput POSTs it to the org studio's /upload/output with the user's
// IAM token, landing it in orgs/{org}/output (the gallery, S3-mirrored).
//
// It is a live integration test, skipped unless the box is wired for it:
//
// HANZO_TOKEN=<iam bearer> \
// HANZO_UPLOAD_IT_FILE=<name of a file the local studio serves at /view?type=output> \
// HANZO_STUDIO_UPLOAD_URL=<org studio base, e.g. https://studio.hanzo.ai> \
// go test ./cli -run TestUploadOutputsIntegration -v
//
// The local studio is assumed at localComfyUI (127.0.0.1:8188).
func TestUploadOutputsIntegration(t *testing.T) {
tok := os.Getenv("HANZO_TOKEN")
file := os.Getenv("HANZO_UPLOAD_IT_FILE")
if tok == "" || file == "" {
t.Skip("set HANZO_TOKEN and HANZO_UPLOAD_IT_FILE to run the live upload integration test")
}
uploadURL := firstNonEmpty(os.Getenv("HANZO_STUDIO_UPLOAD_URL"), defaultStudioUploadURL)
w := &worker{
env: &Env{}, // ensureToken reads HANZO_TOKEN first, so no creds needed
http: &http.Client{Timeout: 60 * time.Second},
studioUploadURL: uploadURL,
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
subfolder := os.Getenv("HANZO_UPLOAD_IT_SUBFOLDER") // "" == top of output
out := file
if subfolder != "" {
out = subfolder + "/" + file
}
gallery, err := w.uploadOutputs(ctx, []string{out}, uploadURL, "karma")
if err != nil {
t.Fatalf("uploadOutputs(%q -> %s): %v", out, uploadURL, err)
}
if len(gallery) != 1 {
t.Fatalf("expected 1 gallery path, got %d: %v", len(gallery), gallery)
}
t.Logf("uploaded %q -> %s gallery path %q", out, uploadURL, gallery[0])
}
+2 -2
View File
@@ -310,7 +310,7 @@ func (p *Platform) Redeploy(ctx context.Context, org, project, env, container st
}
// ---------------------------------------------------------------------------
// Build — POST /v1/arcd/enqueue (platform-native CI, no GitHub builders).
// Build — POST /v1/runner (platform-native CI, no GitHub builders).
// ---------------------------------------------------------------------------
// BuildReq is the direct-enqueue body. Repo/SHA/Image are required.
@@ -344,5 +344,5 @@ func (p *Platform) EnqueueBuild(ctx context.Context, req BuildReq, buildToken st
return nil, fmt.Errorf("no build token: set HANZO_BUILD_TOKEN / PLATFORM_BUILD_CALLBACK_TOKEN or `hanzo login --build-token <tok>`")
}
out := &BuildJob{}
return out, p.do(ctx, http.MethodPost, "/v1/arcd/enqueue", buildToken, req, out)
return out, p.do(ctx, http.MethodPost, "/v1/runner", buildToken, req, out)
}
+1 -1
View File
@@ -177,7 +177,7 @@ func TestPlatformEnqueueBuild(t *testing.T) {
if got := r.Header.Get("Authorization"); got != "Bearer build-tok" {
t.Errorf("build auth header = %q (must use build token)", got)
}
if r.URL.Path != "/v1/arcd/enqueue" {
if r.URL.Path != "/v1/runner" {
t.Errorf("path = %s", r.URL.Path)
}
body, _ := io.ReadAll(r.Body)
+185
View File
@@ -0,0 +1,185 @@
package cli
// run.go — `hanzo run`: launch a workload on Hanzo compute through one verb.
//
// A "run" is a workload value = {artifact, shape}, dispatched by kind onto the
// one API host (api.hanzo.ai/v1) and the one binary (cloud):
//
// hanzo run <image> → POST /v1/run container service (autoscaled)
// hanzo run fn <src> → POST /v1/fn source function (scale-to-zero)
//
// `run` launches YOUR artifact (container/source/site) on Hanzo compute. Invoking
// a managed agent with a task is a peer verb, `hanzo agent` (see agent.go), not a
// run kind. It is a THIN client: kind-dispatch + one authenticated HTTP call each,
// over the IAM access token and env.CloudURL, exactly like the fleet worker
// (gpu.go) — it invents no parallel API. See docs/architecture/compute-ladder.md.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/spf13/cobra"
)
// cloudCall performs one authenticated JSON request against env.CloudURL
// (api.hanzo.ai), decoding a 2xx body into out. It is the api.hanzo.ai analog of
// Platform.do (which targets platform.hanzo.ai); the two converge as the platform
// control plane folds into cloud. Mirrors the fleet worker's call idiom.
func cloudCall(ctx context.Context, env *Env, method, path string, body, out any) error {
tok, err := env.ensureToken(ctx)
if err != nil {
return err
}
var rdr io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return err
}
rdr = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, env.CloudURL+path, rdr)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "hanzo-cli/"+Version)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := (&http.Client{}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if resp.StatusCode/100 != 2 {
return fmt.Errorf("cloud %s %s: HTTP %d: %s", method, path, resp.StatusCode, serverMessage(raw))
}
if out != nil && len(raw) > 0 {
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("cloud %s: decode response: %w", path, err)
}
}
return nil
}
// RunSpec is the POST /v1/run (container) / /v1/fn (source) body. Shape selects
// the execution model: "service" (autoscaled, long-lived), "function"
// (per-request, scale-to-zero), or "task" (run-to-completion).
type RunSpec struct {
Name string `json:"name,omitempty"`
Image string `json:"image,omitempty"` // container artifact (run)
Source string `json:"source,omitempty"` // source ref/path (fn)
Runtime string `json:"runtime,omitempty"`
Port int `json:"port,omitempty"`
Shape string `json:"shape"` // service | function | task
Min int `json:"minScale"`
Max int `json:"maxScale"`
GPU bool `json:"gpu,omitempty"`
Env map[string]string `json:"env,omitempty"`
}
// RunResult is the enqueue/creation acceptance.
type RunResult struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Status string `json:"status"`
Shape string `json:"shape"`
}
func newRunCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "run",
Short: "Launch a workload on Hanzo compute (container, function, or agent task)",
Long: "One verb, dispatched by kind, all on api.hanzo.ai/v1 — k8s is abstracted away:\n" +
" hanzo run <image> a container service (autoscaled)\n" +
" hanzo run fn <src> a source function (scale-to-zero)\n" +
"To invoke a managed agent use `hanzo agent`; a computer-using one, `hanzo bot`.\n" +
"For a declared, long-running or stateful service use `hanzo deploy`; for raw\n" +
"cluster access use `hanzo k8s`.",
}
cmd.AddCommand(newRunContainerCmd(envOf), newRunFnCmd(envOf))
return cmd
}
// newRunContainerCmd is `hanzo run <image>` (default) AND `hanzo run container <image>`.
func newRunContainerCmd(envOf func() *Env) *cobra.Command {
var spec RunSpec
var envKV []string
c := &cobra.Command{
Use: "container <image>",
Short: "Run a container as an autoscaled service (POST /v1/run)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
env := envOf()
spec.Image = args[0]
spec.Shape = firstNonEmpty(spec.Shape, "service")
spec.Env = parseEnvKV(envKV)
out := &RunResult{}
if err := cloudCall(cmd.Context(), env, http.MethodPost, "/v1/run", &spec, out); err != nil {
return err
}
return env.emit(out, func(w io.Writer) {
fmt.Fprintf(w, "%s\t%s\t%s\n", out.Name, out.Status, out.URL)
})
},
}
c.Flags().StringVar(&spec.Name, "name", "", "workload name (default: derived from image)")
c.Flags().IntVar(&spec.Port, "port", 8080, "container port to route traffic to")
c.Flags().StringVar(&spec.Shape, "shape", "service", "service | task (run-to-completion)")
c.Flags().IntVar(&spec.Min, "min", 0, "min replicas (0 = scale-to-zero when supported)")
c.Flags().IntVar(&spec.Max, "max", 20, "max replicas (autoscale ceiling)")
c.Flags().BoolVar(&spec.GPU, "gpu", false, "schedule on a GPU node")
c.Flags().StringArrayVarP(&envKV, "env", "e", nil, "environment variable KEY=VALUE (repeatable)")
return c
}
func newRunFnCmd(envOf func() *Env) *cobra.Command {
var spec RunSpec
var envKV []string
c := &cobra.Command{
Use: "fn <source>",
Short: "Run a source function, scale-to-zero (POST /v1/functions)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
env := envOf()
spec.Source = args[0]
spec.Shape = "function"
spec.Env = parseEnvKV(envKV)
out := &RunResult{}
if err := cloudCall(cmd.Context(), env, http.MethodPost, "/v1/functions", &spec, out); err != nil {
return err
}
return env.emit(out, func(w io.Writer) {
fmt.Fprintf(w, "%s\t%s\t%s\n", out.Name, out.Status, out.URL)
})
},
}
c.Flags().StringVar(&spec.Name, "name", "", "function name")
c.Flags().StringVar(&spec.Runtime, "runtime", "", "runtime env (e.g. python312, node20, rust)")
c.Flags().BoolVar(&spec.GPU, "gpu", false, "use a GPU function environment")
c.Flags().StringArrayVarP(&envKV, "env", "e", nil, "environment variable KEY=VALUE (repeatable)")
return c
}
// parseEnvKV turns []{"K=V"} into a map, ignoring malformed entries.
func parseEnvKV(kv []string) map[string]string {
if len(kv) == 0 {
return nil
}
m := make(map[string]string, len(kv))
for _, e := range kv {
if i := strings.IndexByte(e, '='); i > 0 {
m[e[:i]] = e[i+1:]
}
}
return m
}
+43
View File
@@ -0,0 +1,43 @@
package cli
// runner.go — `hanzo runner`: turn THIS machine into a JIT CI runner for your
// org's GitHub Actions. The host role of the arc daemon, migrated from
// arc-runner/arc (cmd/arcd) into cloud/runner: a GitHub App polls each configured
// org for queued workflow jobs and spawns ephemeral, auto-exiting actions-runner
// subprocesses tagged with this box's labels (GPU / vulkan aware). Outbound only —
// nothing listens for inbound. Completes the trifecta: `engine` serves models,
// `gpu connect` shares compute, `runner` claims CI — one binary, one org login.
import (
"os/signal"
"syscall"
"github.com/hanzoai/cloud/runner"
"github.com/spf13/cobra"
)
func newRunnerCmd(_ func() *Env, _ *globalFlags) *cobra.Command {
runner.Version = Version // propagate the cloud build version into the daemon
var configPath string
cmd := &cobra.Command{
Use: "runner",
Short: "Run this machine as a JIT CI runner for your org (GitHub Actions)",
Long: "Turn this box into an ephemeral, GPU-aware GitHub Actions runner for your\n" +
"org(s). A GitHub App polls for queued jobs and spawns auto-exiting runner\n" +
"subprocesses labelled with this machine's tags. Outbound-only; nothing\n" +
"listens for inbound. Config defaults to ~/.arcd/config.yaml (app_id, orgs,\n" +
"labels, runner_dir).",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := runner.LoadConfig(configPath)
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(cmd.Context(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
return runner.RunHost(ctx, cfg)
},
}
cmd.Flags().StringVar(&configPath, "config", "", "runner config.yaml (default: ~/.arcd/config.yaml)")
return cmd
}
+176
View File
@@ -0,0 +1,176 @@
// studio.go — local Hanzo Studio render-backend supervision for `hanzo gpu
// connect --studio-dir <checkout>`. The gpu-jobs claim loop renders on the
// LOCAL studio server (127.0.0.1:8188); this keeps that server alive so the
// box needs no separate watchdog script or hand-rolled systemd unit — the
// hanzo CLI is the one way a BYO box joins the fleet, render backend included.
//
// Semantics (ported from the GB10 watchdog it replaces): health-probe
// /system_stats; on failure, one grace re-check, then free the port (a stale
// main.py holding :8188 makes the new one crash on EADDRINUSE) and relaunch
// from the checkout's venv. Emits a line only on restart events.
package cli
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
"time"
)
const (
studioAddr = "127.0.0.1:8188"
studioHealthURL = "http://" + studioAddr + "/system_stats"
studioProbeEvery = 45 * time.Second
studioGraceWait = 8 * time.Second
studioStartWindow = 180 * time.Second
)
func studioHealthy(ctx context.Context) bool {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, studioHealthURL, nil)
if err != nil {
return false
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// studioPython picks the checkout's venv interpreter, falling back to python3.
func studioPython(dir string) string {
venv := filepath.Join(dir, ".venv", "bin", "python")
if _, err := os.Stat(venv); err == nil {
return venv
}
return "python3"
}
// launchStudio starts the render backend from dir, logging to
// <dir>/studio-local.log. The process gets its own group so a restart can
// kill stragglers (torch dataloader workers and the like) in one signal.
func launchStudio(dir string) (*exec.Cmd, error) {
logf, err := os.OpenFile(filepath.Join(dir, "studio-local.log"),
os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return nil, err
}
cmd := exec.Command(studioPython(dir), "main.py",
"--listen", "0.0.0.0", "--port", "8188",
"--normalvram", "--disable-auto-launch",
"--output-directory", filepath.Join(dir, "output"))
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"STUDIO_PERSIST_QUEUE=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
)
cmd.Stdout = logf
cmd.Stderr = logf
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
logf.Close()
return nil, err
}
logf.Close() // the child holds its own descriptor
// Shield the render backend from the OOM killer ahead of pack/model RAM
// spikes. Negative adj needs privilege; best-effort.
_ = os.WriteFile("/proc/"+strconv.Itoa(cmd.Process.Pid)+"/oom_score_adj",
[]byte("-700"), 0o644)
go func() { _ = cmd.Wait() }() // reap; the probe loop decides on restarts
return cmd, nil
}
// stopStudio kills the supervised process group (if any) and any foreign
// main.py still holding the port, then waits for the listener to clear.
func stopStudio(cmd *exec.Cmd) {
if cmd != nil && cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
}
_ = exec.Command("pkill", "-f", "main.py --listen").Run()
for i := 0; i < 15; i++ {
conn, err := net.DialTimeout("tcp", studioAddr, time.Second)
if err != nil {
return
}
conn.Close()
time.Sleep(time.Second)
}
}
// studioRecycle carries at most one pending recycle request; the render
// handler signals it after each completed render (see gpu.go).
var studioRecycle = make(chan struct{}, 1)
func requestStudioRecycle() {
select {
case studioRecycle <- struct{}{}:
default:
}
}
// superviseStudio keeps the local render backend on :8188 alive until ctx
// ends. Quiet by design: one line per restart event, not a probe firehose.
func superviseStudio(ctx context.Context, dir string, out io.Writer) {
var cmd *exec.Cmd
restart := func(reason string) {
stopStudio(cmd)
c, err := launchStudio(dir)
if err != nil {
fmt.Fprintf(out, "studio: launch failed (%s): %v\n", reason, err)
return
}
cmd = c
deadline := time.Now().Add(studioStartWindow)
for time.Now().Before(deadline) && ctx.Err() == nil {
if studioHealthy(ctx) {
fmt.Fprintf(out, "studio: serving on %s (pid %d, %s)\n", studioAddr, c.Process.Pid, reason)
return
}
time.Sleep(4 * time.Second)
}
fmt.Fprintf(out, "studio: started pid %d (%s) but %s not healthy yet\n", c.Process.Pid, reason, studioAddr)
}
if !studioHealthy(ctx) {
restart("boot")
} else {
fmt.Fprintf(out, "studio: already serving on %s\n", studioAddr)
}
tick := time.NewTicker(studioProbeEvery)
defer tick.Stop()
for {
select {
case <-ctx.Done():
if cmd != nil && cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
}
return
case <-studioRecycle:
restart("recycle")
case <-tick.C:
if studioHealthy(ctx) {
continue
}
// Grace re-check: it may be momentarily busy mid-render.
select {
case <-ctx.Done():
continue
case <-time.After(studioGraceWait):
}
if !studioHealthy(ctx) {
restart("unresponsive")
}
}
}
}
+524
View File
@@ -0,0 +1,524 @@
// Package account mounts the signed-in caller's OWN account self-service surface
// natively in the unified cloud binary — the Go port of the console's two NON-proxy
// Next server routes (app/keys + app/onboard) plus the money/store data bridges the
// statically-exported console needs (task #41, "True 1-binary FE"). It replaces the
// retired /v1/console/* namespace: "console" is just the cloud FE name, so there is NO
// /v1/console API domain — every route lives on its REAL domain.
//
// WHY THESE ROUTES (and not the pure passthrough proxies). The console's PURE BFF
// reverse-proxies — app/cloud, app/ai — vanish in the one-binary model: the SPA calls
// the canonical /v1/* on its own origin and the already-mounted subsystems answer. The
// routes ported HERE do REAL server work a static SPA cannot: keys/onboard run
// privileged IAM logic as the confidential `hanzo-console` client; embed-status/topup
// do server-side verification; and the billing/commerce bridges inject the commerce
// SERVICE token and pin the caller's own subject SERVER-SIDE (a passthrough would leak
// cross-tenant ledgers). Each has no pure-proxy equivalent, so it must be ported.
//
// SURFACE — each route on its REAL domain (every one requires a VALIDATED principal — a
// gateway-minted, IAM-verified X-User-Id; a client-forged X-Org-Id on the bearer-less
// path is refused):
//
// GET /v1/iam/keys — whether the caller has an `hk-` key (+ prefix/mtime); no secret.
// POST /v1/iam/keys — mint/rotate the key; returns { accessKey } ONCE.
// DELETE /v1/iam/keys — revoke the key.
// POST /v1/iam/onboard — create the caller's org (+ move them in on first run).
// GET /v1/csrf — mint the anti-CSRF token the SPA echoes on money writes (csrf.go).
// GET /v1/embed-status — brand-app embed entitlement + reachability probe (embed.go).
// POST /v1/commerce/topup/wallet — HUSD on-chain verify → commerce credit (topup.go).
// GET /v1/billing/* — per-tenant billing read, SCOPED to the validated caller (billing.go).
// … /v1/commerce/* — per-tenant STORE CRUD, SCOPED to the validated caller's org (commerce.go).
//
// TWO SUBSYSTEM REGISTRATIONS FROM ONE PACKAGE. A route-ordering constraint forces the
// split (Fiber matches by registration order — the earliest-mounted route wins):
// - `account` (order 48) mounts the SPECIFIC self-service routes. keys/onboard MUST
// win over clients/iam's /v1/iam/* WILDCARD (order 50), and topup MUST win over the
// commerce embed (order 100) + the /v1/commerce/* bridge — so they mount EARLY.
// - `account-bridge` (order 122) mounts the CATCH-ALL data bridges. /v1/billing/* must
// sit AFTER clients/billing's specific routes (order 121) and /v1/commerce/* after
// the commerce embed (order 100) — so they mount LATE.
//
// Both share one state shape + the process-wide CSRF key (csrf.go), so a token minted at
// /v1/csrf verifies on the /v1/billing|commerce writes.
//
// TENANCY. The caller is resolved from the VALIDATED identity headers ONLY
// (principal.Validated / c.Org() / c.User()), the same trust boundary every mutating
// subsystem uses. The IAM id targeted is DERIVED as `<owner>/<name>` from those
// validated claims — never taken from the request body/query — so a caller can only ever
// mint/revoke their OWN key and onboard THEMSELVES; there is no path to name a
// third-party subject. When the confidential client is unwired the surface is honestly
// "not configured" (501), never a fabricated key or org.
package account
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"strings"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients/principal"
"github.com/zap-proto/zip"
)
// adminOrg is THE SuperAdmin / IAM-system org that owns every customer org row —
// standardized as "admin" across the whole stack (IAM, commerce, ai, gateway all
// gate cross-tenant on owner=="admin"). A created customer org is owned by it.
const adminOrg = "admin"
// errNotConfigured is returned by the IAM client when the confidential
// `hanzo-console` credential is unset; handlers map it to a 501 (honest "not
// configured on this deployment", mirroring identity.ts's mintConfigured() gate).
var errNotConfigured = errors.New("iam confidential client not configured")
// errNotFound is a not-present sentinel (e.g. the user row IAM cannot return).
var errNotFound = errors.New("not found")
// state is account's own data; shared deps live in the embedded cloud.Base. Both
// subsystem registrations (account @48, account-bridge @122) build their own value;
// the CSRF key is the process-wide singleton (csrf.go) so a token minted by one
// verifies on the other.
type state struct {
iam *iamClient
csrfKey []byte // keyed-BLAKE3 MAC key for the money-write CSRF token (csrf.go)
writesRL *rateLimiter // per-IP abuse cap on the money-write routes (ratelimit.go)
}
// keysWriteRatePerMin caps money-write frequency per client IP (mint/rotate/revoke
// key, wallet top-up). Generous enough for real UI bursts, tight enough to blunt
// brute-force / enumeration when a caller reaches cloud directly (gateway bypassed).
const keysWriteRatePerMin = 30
// newService builds the shared subsystem value. Both subsystem Mounts construct one;
// the CSRF key is the process-wide singleton (csrf.go) so account (order 48) and
// account-bridge (order 122) verify each other's tokens.
func newService(deps cloud.Deps) *cloud.Service[state] {
b := cloud.NewBase(deps, "account")
st := state{iam: newIAMClient()}
st.csrfKey = sharedCSRFKey(b.Log)
st.writesRL = newRateLimiter(keysWriteRatePerMin)
return &cloud.Service[state]{Base: b, State: st}
}
// MountAccount wires the SPECIFIC self-service routes (order 48) — the ones that must
// win over the IAM /v1/iam/* wildcard (50) and the commerce embed (100).
func MountAccount(app *zip.App, deps cloud.Deps) error {
if app == nil {
return fmt.Errorf("account.MountAccount: nil zip.App")
}
if deps.Logger == nil {
return fmt.Errorf("account.MountAccount: nil deps.Logger")
}
s := newService(deps)
routesAccount(s, app)
s.Log.Info("account self-service surface mounted",
"iam", s.State.iam.base, "configured", s.State.iam.configured(), "brand", s.Brand)
return nil
}
// MountBridge wires the CATCH-ALL data bridges (order 122) — the /v1/billing/* and
// /v1/commerce/* proxies that must sit AFTER clients/billing (121) + the commerce embed.
func MountBridge(app *zip.App, deps cloud.Deps) error {
if app == nil {
return fmt.Errorf("account.MountBridge: nil zip.App")
}
if deps.Logger == nil {
return fmt.Errorf("account.MountBridge: nil deps.Logger")
}
s := newService(deps)
routesBridge(s, app)
s.Log.Info("account data bridges mounted", "prefixes", "/v1/billing/*,/v1/commerce/*", "brand", s.Brand)
return nil
}
// routesAccount wires the specific self-service routes (order 48).
func routesAccount(s *cloud.Service[state], app *zip.App) {
// GET /v1/csrf issues the anti-CSRF token the embedded SPA echoes as X-CSRF-Token on
// every money write (csrf.go). Safe (read-only), same-origin.
app.Get("/v1/csrf", cloud.Handle(s, issueCSRFToken))
// The caller's own `hk-` Cloud API key — IAM self-service. These SPECIFIC routes MUST
// register before clients/iam's /v1/iam/* wildcard (order 50 > 48) so Fiber's
// first-match scan hits the native handler, not the wildcard (TestIAMKeysBeatsWildcard).
// Reads are open; every state-changing WRITE is wrapped: requireCSRF blocks a
// cross-site ambient-cookie forgery, and rateLimit caps per-IP frequency (cloud is
// reachable off-gateway).
app.Get("/v1/iam/keys", cloud.Handle(s, getKey))
app.Post("/v1/iam/keys", rateLimit(s, s.State.writesRL, requireCSRF(s, cloud.Handle(s, mintKey))))
app.Delete("/v1/iam/keys", rateLimit(s, s.State.writesRL, requireCSRF(s, cloud.Handle(s, revokeKey))))
app.Post("/v1/iam/onboard", requireCSRF(s, cloud.Handle(s, onboard)))
// Console module embed-entitlement + reachability probe (embed.go).
app.Get("/v1/embed-status", cloud.Handle(s, embedStatus))
// HUSD wallet top-up (on-chain verify → commerce credit). A SPECIFIC commerce route
// that must beat the /v1/commerce/* bridge (122) AND the commerce embed (100) — so it
// mounts here at 48, ahead of both.
app.Post("/v1/commerce/topup/wallet", rateLimit(s, s.State.writesRL, requireCSRF(s, cloud.Handle(s, walletTopup))))
}
// routesBridge wires the per-tenant catch-all data bridges (order 122).
func routesBridge(s *cloud.Service[state], app *zip.App) {
// Per-tenant billing DATA bridge — the canonical /v1/billing/* the statically-exported
// console calls, forwarded to commerce with the admin service token and SCOPED to the
// validated caller's own subject (billing.go). Registered AFTER clients/billing's
// specific routes (121 < 122) so those win and this catches the rest. GET+POST only.
// The wildcard is what the ROUTER matches; it is NOT the forwardable set — billing.go's
// billingForwardable allowlist decides that, per method, and 404s everything else
// BEFORE the admin service token is attached. Widening this pattern grants nothing on
// its own; adding a line to that table is the only way to expose an endpoint.
app.Get("/v1/billing/*", cloud.Handle(s, billingData))
app.Post("/v1/billing/*", requireCSRF(s, cloud.Handle(s, billingData)))
// Per-tenant STORE DATA bridge — the canonical /v1/commerce/* the console calls,
// forwarded to commerce's bare store surface /v1/<kind> with the admin service token
// and SCOPED to the validated caller's own org (commerce.go). Registered AFTER the
// commerce embed (100 < 122) so the embed wins when enabled. Full CRUD.
app.Get("/v1/commerce/*", cloud.Handle(s, commerceData))
app.Post("/v1/commerce/*", requireCSRF(s, cloud.Handle(s, commerceData)))
app.Put("/v1/commerce/*", requireCSRF(s, cloud.Handle(s, commerceData)))
app.Patch("/v1/commerce/*", requireCSRF(s, cloud.Handle(s, commerceData)))
app.Delete("/v1/commerce/*", requireCSRF(s, cloud.Handle(s, commerceData)))
}
// ── caller resolution (the tenancy boundary) ─────────────────────────────────
// caller is the signed-in user resolved from the VALIDATED identity headers. id is
// the `<owner>/<name>` composite IAM's privileged ops parse (GetOwnerAndNameFromId
// requires it — a bare token count of 1 throws "wrong token count"); owner is the
// org (X-Org-Id).
type caller struct {
id string // <owner>/<name> (or the bare user id when owner-less)
owner string // validated org (may be "" for a zero-org, first-run user)
name string // == X-User-Id: the stable user id (a UUID on the direct path)
username string // IAM username (X-User-Name); the `name` half IAM's user-key ops parse
}
// keyID is the `<owner>/<username>` composite IAM's user-key ops (mint/get/revoke
// user AccessKey) parse via GetOwnerAndNameFromId. It uses the IAM USERNAME, not
// name (== X-User-Id): on the in-binary direct-Bearer path X-User-Id is the UUID
// subject and `<owner>/<uuid>` fails IAM's user lookup ("password or code is
// incorrect"). On the gateway path username==name so keyID()==id — no change.
// Owner-less (first-run) callers can't own a key, so this is only reached with a
// validated owner; it falls back to id defensively.
func (cr caller) keyID() string {
if cr.owner != "" && cr.username != "" {
return cr.owner + "/" + cr.username
}
return cr.id
}
// resolveCaller derives the caller from the validated identity, or (zero,false)
// when there is no validated principal. requireOwner=true refuses a user with no
// org yet (used by the key ops, which must act scoped); onboarding passes
// requireOwner=false so a first-run zero-org user can create their first org. The id
// is ALWAYS derived from the validated claims, never a request value.
func resolveCaller(c *zip.Ctx, requireOwner bool) (caller, bool) {
if !principal.Validated(c) {
return caller{}, false // no gateway-minted, IAM-verified principal — refuse
}
name := strings.TrimSpace(c.User())
if name == "" {
return caller{}, false
}
owner := strings.TrimSpace(c.Org())
if requireOwner && owner == "" {
return caller{}, false
}
// IAM parses `<owner>/<name>`; prefer it, fall back to the bare id for an
// owner-less (first-run) user. Same id semantics as identity.ts.
id := name
if owner != "" {
id = owner + "/" + name
}
// username is the IAM USERNAME, kept DISTINCT from name (== X-User-Id) so the
// billing/topup subjects (which key on name) are byte-identical to today — this
// value narrows the blast radius to the IAM user-key ops alone (keyID()). It
// prefers X-User-Name (stamped from the validated `name` claim by
// SanitizeIdentity), because on the in-binary direct-Bearer path X-User-Id is the
// UUID subject and <owner>/<uuid> fails IAM's mint-user-keys/get-user lookup.
// Falls back to name for the gateway path (which mints X-User-Id==username). Both
// inputs are gateway/SanitizeIdentity-minted from a verified principal.
username := strings.TrimSpace(c.Header("X-User-Name"))
if username == "" {
username = name
}
return caller{id: id, owner: owner, name: name, username: username}, true
}
// ── keys (the per-user `hk-` Cloud API key) ──────────────────────────────────
type keyStatus struct {
HasKey bool `json:"hasKey"`
KeyPrefix string `json:"keyPrefix,omitempty"`
CreatedAt string `json:"createdAt,omitempty"`
}
// getKey reports whether the caller has an `hk-` key, its public prefix, and when
// the key row last changed — NO secret material. Reads IAM authoritatively (not the
// session claim, which lags a fresh key). Mirrors GET app/keys/route.ts.
func getKey(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, true)
if !ok {
return zip.ErrForbidden("sign in to manage API keys")
}
if !s.State.iam.configured() {
return notConfigured("API key management")
}
uk, err := s.State.iam.getUserKey(c.Context(), cr.keyID())
if err != nil {
// Fail-soft on a transient IAM read: report "no key" rather than 5xx, so the
// page shows the honest empty state (never a fabricated key). The mint path
// still 502s loudly on a real failure — reads degrade, writes do not.
s.Log.Warn("get key: iam read failed (reporting no key)", "err", err)
return c.JSON(http.StatusOK, keyStatus{HasKey: false})
}
if uk.AccessKey == "" {
return c.JSON(http.StatusOK, keyStatus{HasKey: false})
}
prefix := uk.AccessKey
if len(prefix) > 11 {
prefix = prefix[:11]
}
return c.JSON(http.StatusOK, keyStatus{HasKey: true, KeyPrefix: prefix, CreatedAt: uk.UpdatedTime})
}
// mintKey (re)generates the caller's `hk-` key and returns it ONCE (show-once). A
// real IAM failure surfaces as 502 (never a fabricated key). Mirrors POST app/keys.
func mintKey(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, true)
if !ok {
return zip.ErrForbidden("sign in to manage API keys")
}
if !s.State.iam.configured() {
return notConfigured("API key management")
}
key, err := s.State.iam.mintUserKey(c.Context(), cr.keyID())
if err != nil {
return zip.Errorf(http.StatusBadGateway, "could not mint an API key: %v", err)
}
return c.JSON(http.StatusOK, map[string]string{"accessKey": key})
}
// revokeKey clears the caller's `hk-` key. Mirrors DELETE app/keys.
func revokeKey(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, true)
if !ok {
return zip.ErrForbidden("sign in to manage API keys")
}
if !s.State.iam.configured() {
return notConfigured("API key management")
}
if err := s.State.iam.revokeUserKey(c.Context(), cr.keyID()); err != nil {
return zip.Errorf(http.StatusBadGateway, "could not revoke the API key: %v", err)
}
return c.JSON(http.StatusOK, map[string]bool{"ok": true})
}
// ── onboard (create the caller's org) ────────────────────────────────────────
type onboardReq struct {
Name string `json:"name"`
Personal bool `json:"personal"`
}
type onboardResp struct {
Org string `json:"org"`
DisplayName string `json:"displayName"`
Additional bool `json:"additional"`
}
// onboard creates the caller's organization. Two flows, keyed on whether the caller
// already has a home org (mirrors app/onboard/route.ts):
//
// - FIRST-RUN (no owner): create + MOVE the user in as admin, so their next JWT
// carries the new owner and the cloud scopes everything to it.
// - ADDITIONAL (owner set): create the org but do NOT move the user — a move
// changes their IAM owner (stripping a SuperAdmin's status + orphaning their
// current org). They reach the new org via the OrgSwitcher, which re-scopes
// X-Org-Id without touching IAM membership. A personal-org request from someone
// who already has an org is meaningless → 409.
func onboard(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, false) // first-run onboarding allows a zero-org user
if !ok {
return zip.ErrForbidden("sign in to create an organization")
}
if !s.State.iam.configured() {
return notConfigured("organization creation")
}
var body onboardReq
if len(c.Body()) > 0 {
if err := c.Bind(&body); err != nil {
return err
}
}
additional := cr.owner != ""
if additional && body.Personal {
return zip.ErrConflict("you already have an organization; name the new one explicitly")
}
baseSlug, displayName, herr := resolveOnboardName(s, body, cr)
if herr != nil {
return herr
}
// Resolve a unique slug. Personal orgs auto-suffix to stay unique; an explicit
// name that's taken is an honest conflict the user resolves by renaming.
slug, herr := uniqueSlug(s, c, baseSlug, body.Personal)
if herr != nil {
return herr
}
// Create the org (cloning the caller's current org for password/locale
// compatibility), then — first-run only — move the zero-org user in as admin.
org := buildOrg(s, c, slug, displayName, body.Personal, cr.owner)
if err := s.State.iam.createOrganization(c.Context(), org); err != nil {
return zip.Errorf(http.StatusBadGateway, "could not create the organization: %v", err)
}
if !additional {
if err := s.State.iam.moveUserToOrg(c.Context(), cr.id, slug); err != nil {
return zip.Errorf(http.StatusBadGateway, "org created but could not assign you to it: %v", err)
}
}
return c.JSON(http.StatusOK, onboardResp{Org: slug, DisplayName: displayName, Additional: additional})
}
// resolveOnboardName derives the base slug + display name from the request, or a
// mapped HTTP error. Personal orgs derive from the username; a named org validates
// through the shared policy (onboarding.go).
func resolveOnboardName(s *cloud.Service[state], body onboardReq, cr caller) (baseSlug, displayName string, err error) {
if body.Personal {
baseSlug = personalOrgSlug(cr.name)
if len(baseSlug) < minOrgSlug || isReservedOrg(baseSlug) {
baseSlug = "org-" + firstNonEmpty(slugifyOrg(cr.name), "workspace")
}
return baseSlug, humanize(cr.name), nil
}
v := validateOrgName(body.Name)
if !v.ok {
return "", "", zip.ErrBadRequest(v.error)
}
return v.slug, strings.TrimSpace(body.Name), nil
}
// uniqueSlug returns a free slug at/after base. A named org that's taken is a 409;
// a personal org auto-suffixes (base, base-2, …) up to a small bound.
func uniqueSlug(s *cloud.Service[state], c *zip.Ctx, base string, personal bool) (string, error) {
existing, err := s.State.iam.getOrganization(c.Context(), base)
if err != nil {
return "", zip.Errorf(http.StatusBadGateway, "could not check organization availability: %v", err)
}
if existing == nil {
return base, nil
}
if !personal {
return "", zip.Errorf(http.StatusConflict, "“%s” is taken; choose a different name", base)
}
free, err := freeSlug(s, c, base)
if err != nil {
return "", err
}
if free == "" {
return "", zip.Errorf(http.StatusConflict, "could not find an available name")
}
return free, nil
}
// freeSlug finds the first free slug at/after base (base, base-2, … base-20), or ""
// if all are taken. Mirrors identity.ts's freeSlug bound of 20.
func freeSlug(s *cloud.Service[state], c *zip.Ctx, base string) (string, error) {
for i := 2; i <= 20; i++ {
trimmed := base
if len(trimmed) > maxOrgSlug-3 {
trimmed = trimmed[:maxOrgSlug-3]
}
candidate := strings.Trim(fmt.Sprintf("%s-%d", strings.TrimRight(trimmed, "-"), i), "-")
if len(candidate) < minOrgSlug || isReservedOrg(candidate) {
continue
}
existing, err := s.State.iam.getOrganization(c.Context(), candidate)
if err != nil {
return "", zip.Errorf(http.StatusBadGateway, "could not check organization availability: %v", err)
}
if existing == nil {
return candidate, nil
}
}
return "", nil
}
// buildOrg assembles the new customer org owned by the `admin` org, cloning
// password/locale settings from the caller's current org (best-effort; a nil source
// just yields a minimal org IAM completes with its defaults) and clearing all
// instance-specific material. Mirrors identity.ts's createOrganization body.
func buildOrg(s *cloud.Service[state], c *zip.Ctx, slug, displayName string, personal bool, sourceOwner string) iamOrg {
org := iamOrg{Owner: adminOrg, Name: slug, DisplayName: displayName, IsPersonal: personal}
if sourceOwner == "" {
return org
}
src, err := s.State.iam.getOrganization(c.Context(), sourceOwner)
if err != nil || src == nil {
return org // clone is best-effort; IAM applies its org defaults otherwise
}
org.PasswordType = src.PasswordType
org.PasswordSalt = src.PasswordSalt
org.PasswordObfuscatorType = src.PasswordObfuscatorType
org.PasswordObfuscatorKey = src.PasswordObfuscatorKey
org.PasswordOptions = src.PasswordOptions
org.CountryCodes = src.CountryCodes
org.Languages = src.Languages
org.DefaultAvatar = src.DefaultAvatar
return org
}
// ── shared helpers ────────────────────────────────────────────────────────────
// notConfigured is the honest 501 for a surface whose confidential client is
// unwired — the deployment simply lacks the `hanzo-console` credential.
func notConfigured(surface string) error {
return zip.Errorf(http.StatusNotImplemented, "%s is not configured on this deployment (IAM client unset)", surface)
}
// humanize title-cases the base of a username for a personal org's display name
// (dave.smith@x.com → "Dave Smith"). Mirrors identity/onboard humanize().
func humanize(username string) string {
base := username
// Split on '@' anywhere (mirrors identity.ts humanize's `includes('@')`), so a
// bare "@" collapses to "" → "Personal". (personalOrgSlug intentionally uses
// `> 0` instead, matching its own TS source.)
if at := strings.IndexByte(base, '@'); at >= 0 {
base = base[:at]
}
base = strings.TrimSpace(strings.Map(func(r rune) rune {
if r == '.' || r == '_' || r == '-' {
return ' '
}
return r
}, base))
if base == "" {
return "Personal"
}
parts := strings.Fields(base)
for i, p := range parts {
parts[i] = strings.ToUpper(p[:1]) + p[1:]
}
return strings.Join(parts, " ")
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
func getenv(key, dflt string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return dflt
}
func basicToken(id, secret string) string {
return base64.StdEncoding.EncodeToString([]byte(id + ":" + secret))
}
@@ -1,4 +1,4 @@
package console
package account
import (
"encoding/base64"
@@ -24,18 +24,18 @@ type fakeIAM struct {
mu sync.Mutex
// state
keys map[string]string // id → current hk- key ("" = none)
orgs map[string]map[string]any // slug → org row (nil map = absent)
user map[string]map[string]any // id → full user row (for the move)
keys map[string]string // id → current hk- key ("" = none)
orgs map[string]map[string]any // slug → org row (nil map = absent)
user map[string]map[string]any // id → full user row (for the move)
// captured
gotAuth string // Authorization header on the last request
mintedFor []string // ids mint-user-keys was called with
revokedFor []string
movedTo map[string]string // id → new owner (from update-user)
createdOrgs []map[string]any
failAddOrg bool // when true, add-organization answers status!=ok
failMintKey bool
gotAuth string // Authorization header on the last request
mintedFor []string // ids mint-user-keys was called with
revokedFor []string
movedTo map[string]string // id → new owner (from update-user)
createdOrgs []map[string]any
failAddOrg bool // when true, add-organization answers status!=ok
failMintKey bool
}
func newFakeIAM() *fakeIAM {
@@ -165,20 +165,60 @@ func (f *fakeIAM) capture(r *http.Request) {
f.mu.Unlock()
}
// mountApp mounts the console surface against the fake IAM at base, with the
// mountApp mounts the account surface against the fake IAM at base, with the
// confidential client wired (unless creds are ""). Returns the app.
func mountApp(t *testing.T, base, clientID, clientSecret string) *zip.App {
t.Helper()
t.Setenv("IAM_URL", base)
t.Setenv("IAM_MINT_CLIENT_ID", clientID)
t.Setenv("IAM_MINT_CLIENT_SECRET", clientSecret)
return mountBoth(t, "hanzo")
}
// mountBoth mounts BOTH account subsystems (self-service + data bridges) on one app —
// exactly what production registers (account@48 then account-bridge@122), so a test
// exercises the full surface with the shared CSRF key. The caller sets the IAM env
// (IAM_URL / IAM_MINT_CLIENT_*) before calling.
func mountBoth(t *testing.T, brand string) *zip.App {
t.Helper()
app := zip.New(zip.Config{Logger: luxlog.New("test")})
if err := Mount(app, cloud.Deps{Logger: luxlog.New("test"), Brand: "hanzo"}); err != nil {
t.Fatalf("Mount: %v", err)
deps := cloud.Deps{Logger: luxlog.New("test"), Brand: brand}
if err := MountAccount(app, deps); err != nil {
t.Fatalf("MountAccount: %v", err)
}
if err := MountBridge(app, deps); err != nil {
t.Fatalf("MountBridge: %v", err)
}
return app
}
// callH drives a request with arbitrary VALIDATED-identity headers (the gateway sets
// these only from a verified credential). Mirrors `call` but lets a test inject
// X-User-Email / X-User-IsAdmin, which the ported routes read.
func callH(t *testing.T, app *zip.App, method, path string, headers map[string]string, body string) (int, []byte) {
t.Helper()
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, rdr)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
for k, v := range headers {
if v != "" {
req.Header.Set(k, v)
}
}
resp, err := app.Fiber().Test(req)
if err != nil {
t.Fatalf("Test %s %s: %v", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
// call drives a request through the mounted app. When user is non-empty it injects
// a VALIDATED principal (X-User-Id set — the gateway sets this ONLY from a verified
// credential) with org as X-Org-Id. body is an optional JSON string.
@@ -216,7 +256,7 @@ func TestKeys_RequireValidatedPrincipal(t *testing.T) {
// No X-User-Id → no validated principal → 403, and IAM is never touched, even if
// a forged X-Org-Id is present (the bearer-less data path must not mint a key).
for _, m := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
code, _ := call(t, app, m, "/v1/console/keys", "", "victim", "")
code, _ := call(t, app, m, "/v1/iam/keys", "", "victim", "")
if code != http.StatusForbidden {
t.Fatalf("%s /keys with forged org but no principal: want 403, got %d", m, code)
}
@@ -231,7 +271,7 @@ func TestKeys_MintGetRevoke_ScopedToCaller(t *testing.T) {
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
// GET before mint → hasKey:false (authoritative IAM read, not the claim).
code, body := call(t, app, http.MethodGet, "/v1/console/keys", "alice", "acme", "")
code, body := call(t, app, http.MethodGet, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusOK {
t.Fatalf("get pre-mint: want 200, got %d (%s)", code, body)
}
@@ -243,7 +283,7 @@ func TestKeys_MintGetRevoke_ScopedToCaller(t *testing.T) {
// POST → mint; the key is returned ONCE, and IAM was targeted with the DERIVED
// `<owner>/<name>` id — never a request value.
code, body = call(t, app, http.MethodPost, "/v1/console/keys", "alice", "acme", "")
code, body = call(t, app, http.MethodPost, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusOK {
t.Fatalf("mint: want 200, got %d (%s)", code, body)
}
@@ -266,7 +306,7 @@ func TestKeys_MintGetRevoke_ScopedToCaller(t *testing.T) {
}
// GET after mint → hasKey:true with the public prefix only (no secret material).
code, body = call(t, app, http.MethodGet, "/v1/console/keys", "alice", "acme", "")
code, body = call(t, app, http.MethodGet, "/v1/iam/keys", "alice", "acme", "")
mustJSON(t, body, &st)
if code != http.StatusOK || !st.HasKey || st.KeyPrefix != "hk-acme-ali" {
t.Fatalf("get post-mint: want hasKey + 11-char prefix, got %d %s", code, body)
@@ -276,16 +316,53 @@ func TestKeys_MintGetRevoke_ScopedToCaller(t *testing.T) {
}
// DELETE → revoke, targeting the same derived id.
code, _ = call(t, app, http.MethodDelete, "/v1/console/keys", "alice", "acme", "")
code, _ = call(t, app, http.MethodDelete, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusOK || len(f.revokedFor) != 1 || f.revokedFor[0] != "acme/alice" {
t.Fatalf("revoke: want 200 targeting acme/alice, got %d %v", code, f.revokedFor)
}
}
// TestKeys_DirectBearerPath_MintsByUsernameNotUUID is the regression guard for the
// cloud-direct hk- mint 502. On the in-binary direct-Bearer path SanitizeIdentity
// stamps X-User-Id = the JWT subject (a UUID) and, distinctly, X-User-Name = the IAM
// username. The user-key ops must target <owner>/<username> ("hanzo/z"), NOT
// <owner>/<uuid> — which failed IAM's GetOwnerAndNameFromId user lookup ("password
// or code is incorrect", surfaced as 502). The gateway path (no X-User-Name;
// X-User-Id == username) must be UNCHANGED (keyID falls back to owner/name).
func TestKeys_DirectBearerPath_MintsByUsernameNotUUID(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
const uuid = "2d4d67ab-30f1-474e-b81f-f60461852259"
req := httptest.NewRequest(http.MethodPost, "/v1/iam/keys", nil)
req.Header.Set("X-User-Id", uuid) // direct-path stamp: the subject UUID
req.Header.Set("X-User-Name", "z") // direct-path stamp: the IAM username
req.Header.Set("X-Org-Id", "hanzo")
resp, err := app.Fiber().Test(req)
if err != nil {
t.Fatalf("Test: %v", err)
}
defer func() { _ = resp.Body.Close() }()
b, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("direct-path mint: want 200, got %d (%s)", resp.StatusCode, b)
}
if len(f.mintedFor) != 1 || f.mintedFor[0] != "hanzo/z" {
t.Fatalf("direct-path mint must target hanzo/z (username), never hanzo/<uuid>: got %v", f.mintedFor)
}
var minted struct {
AccessKey string `json:"accessKey"`
}
mustJSON(t, b, &minted)
if minted.AccessKey != "hk-hanzo-z-SECRET" {
t.Fatalf("direct-path mint returned wrong key: %q", minted.AccessKey)
}
}
func TestKeys_NotConfigured_501(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "", "") // confidential client unwired
code, body := call(t, app, http.MethodPost, "/v1/console/keys", "alice", "acme", "")
code, body := call(t, app, http.MethodPost, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusNotImplemented {
t.Fatalf("unconfigured mint: want 501, got %d (%s)", code, body)
}
@@ -295,7 +372,7 @@ func TestKeys_MintUpstreamFailure_502(t *testing.T) {
f := newFakeIAM()
f.failMintKey = true
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
code, body := call(t, app, http.MethodPost, "/v1/console/keys", "alice", "acme", "")
code, body := call(t, app, http.MethodPost, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusBadGateway {
t.Fatalf("mint upstream failure: want 502, got %d (%s)", code, body)
}
@@ -312,7 +389,7 @@ func TestOnboard_FirstRun_CreatesAndMoves(t *testing.T) {
// First-run: the caller has NO org (empty X-Org-Id) but IS validated. onboard
// must allow it (requireOwner=false), create the org, and MOVE the user in.
code, body := call(t, app, http.MethodPost, "/v1/console/onboard", "dave", "", `{"name":"Acme Rockets"}`)
code, body := call(t, app, http.MethodPost, "/v1/iam/onboard", "dave", "", `{"name":"Acme Rockets"}`)
if code != http.StatusOK {
t.Fatalf("first-run onboard: want 200, got %d (%s)", code, body)
}
@@ -338,7 +415,7 @@ func TestOnboard_Additional_CreatesWithoutMoving(t *testing.T) {
// The caller ALREADY has an org. onboard must create the new org but NOT move
// them (a move would strip their owner + orphan their current org).
code, body := call(t, app, http.MethodPost, "/v1/console/onboard", "alice", "acme", `{"name":"Side Project"}`)
code, body := call(t, app, http.MethodPost, "/v1/iam/onboard", "alice", "acme", `{"name":"Side Project"}`)
if code != http.StatusOK {
t.Fatalf("additional onboard: want 200, got %d (%s)", code, body)
}
@@ -358,12 +435,12 @@ func TestOnboard_ReservedAndTaken(t *testing.T) {
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
// A reserved brand/system name is a 400 (policy), before any IAM create.
code, _ := call(t, app, http.MethodPost, "/v1/console/onboard", "alice", "acme", `{"name":"Hanzo"}`)
code, _ := call(t, app, http.MethodPost, "/v1/iam/onboard", "alice", "acme", `{"name":"Hanzo"}`)
if code != http.StatusBadRequest {
t.Fatalf("reserved name: want 400, got %d", code)
}
// An explicit name that's taken is an honest 409.
code, _ = call(t, app, http.MethodPost, "/v1/console/onboard", "alice", "acme", `{"name":"Taken"}`)
code, _ = call(t, app, http.MethodPost, "/v1/iam/onboard", "alice", "acme", `{"name":"Taken"}`)
if code != http.StatusConflict {
t.Fatalf("taken name: want 409, got %d", code)
}
@@ -380,7 +457,7 @@ func TestOnboard_Personal_AutoSuffixesOnCollision(t *testing.T) {
// personal:true (zero-org user) with the base slug taken → auto-suffix to dave-2,
// first-run move.
code, body := call(t, app, http.MethodPost, "/v1/console/onboard", "dave", "", `{"personal":true}`)
code, body := call(t, app, http.MethodPost, "/v1/iam/onboard", "dave", "", `{"personal":true}`)
if code != http.StatusOK {
t.Fatalf("personal onboard: want 200, got %d (%s)", code, body)
}
@@ -395,7 +472,7 @@ func TestOnboard_PersonalWhenAlreadyOrged_409(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
// A user WITH an org asking for a personal org is meaningless → 409.
code, _ := call(t, app, http.MethodPost, "/v1/console/onboard", "alice", "acme", `{"personal":true}`)
code, _ := call(t, app, http.MethodPost, "/v1/iam/onboard", "alice", "acme", `{"personal":true}`)
if code != http.StatusConflict {
t.Fatalf("personal-while-orged: want 409, got %d", code)
}
@@ -404,25 +481,69 @@ func TestOnboard_PersonalWhenAlreadyOrged_409(t *testing.T) {
func TestOnboard_Unauthenticated_403(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
code, _ := call(t, app, http.MethodPost, "/v1/console/onboard", "", "", `{"name":"x"}`)
code, _ := call(t, app, http.MethodPost, "/v1/iam/onboard", "", "", `{"name":"x"}`)
if code != http.StatusForbidden {
t.Fatalf("unauth onboard: want 403, got %d", code)
}
}
// ── health ─────────────────────────────────────────────────────────────────
// ── route ordering: the native /v1/iam surface beats clients/iam's wildcard ───
func TestHealth_ReflectsConfiguration(t *testing.T) {
// TestIAMKeysBeatsWildcard proves the ACTUAL route-match precedence: with the account
// self-service routes mounted FIRST (order 48) and clients/iam's /v1/iam/* WILDCARD
// mounted AFTER (order 50) — the exact production mount order — a request to /v1/iam/keys
// reaches the NATIVE handler, not the wildcard. A path the native surface does NOT own
// still falls through to the wildcard, proving it is really mounted and only the specific
// route shadows it.
func TestIAMKeysBeatsWildcard(t *testing.T) {
f := newFakeIAM()
t.Setenv("IAM_URL", f.server(t).URL)
t.Setenv("IAM_MINT_CLIENT_ID", "hanzo-console")
t.Setenv("IAM_MINT_CLIENT_SECRET", "s3cr3t")
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
if code, _ := call(t, app, http.MethodGet, "/v1/console/health", "", "", ""); code != http.StatusOK {
t.Fatalf("configured health: want 200, got %d", code)
app := zip.New(zip.Config{Logger: luxlog.New("test")})
deps := cloud.Deps{Logger: luxlog.New("test"), Brand: "hanzo"}
// account (order 48) mounts its SPECIFIC /v1/iam/keys + /v1/iam/onboard FIRST.
if err := MountAccount(app, deps); err != nil {
t.Fatalf("MountAccount: %v", err)
}
// clients/iam (order 50) mounts its /v1/iam/* WILDCARD AFTER — the exact prod order.
const sentinel = 599
app.All("/v1/iam/*", func(c *zip.Ctx) error {
return c.JSON(sentinel, map[string]string{"handler": "iam-wildcard"})
})
// GET /v1/iam/keys must hit the NATIVE handler (keyStatus 200), never the wildcard.
code, body := call(t, app, http.MethodGet, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusOK {
t.Fatalf("/v1/iam/keys must hit the native handler (200), got %d (%s) — wildcard shadowed it", code, body)
}
if strings.Contains(string(body), "iam-wildcard") {
t.Fatalf("/v1/iam/keys reached the wildcard, not the native handler: %s", body)
}
var st keyStatus
mustJSON(t, body, &st) // native response shape
// POST /v1/iam/keys (mint) must ALSO hit the native handler and target the derived id.
code, body = call(t, app, http.MethodPost, "/v1/iam/keys", "alice", "acme", "")
if code != http.StatusOK || strings.Contains(string(body), "iam-wildcard") {
t.Fatalf("POST /v1/iam/keys must mint via the native handler, got %d (%s)", code, body)
}
if len(f.mintedFor) != 1 || f.mintedFor[0] != "acme/alice" {
t.Fatalf("native mint must target acme/alice, got %v", f.mintedFor)
}
app2 := mountApp(t, f.server(t).URL, "", "")
if code, _ := call(t, app2, http.MethodGet, "/v1/console/health", "", "", ""); code != http.StatusServiceUnavailable {
t.Fatalf("unconfigured health: want 503, got %d", code)
// /v1/iam/onboard is likewise native (not the wildcard).
code, _ = call(t, app, http.MethodPost, "/v1/iam/onboard", "dave", "", `{"name":"Acme Rockets"}`)
if code == sentinel {
t.Fatalf("/v1/iam/onboard reached the wildcard (%d) — the native handler must win", sentinel)
}
// A path the native surface does NOT own falls through to the wildcard (proof it IS
// mounted and only the specific /v1/iam/keys + /v1/iam/onboard routes shadow it).
code, _ = call(t, app, http.MethodGet, "/v1/iam/oauth/token", "alice", "acme", "")
if code != sentinel {
t.Fatalf("/v1/iam/oauth/token must reach the /v1/iam/* wildcard (%d), got %d", sentinel, code)
}
}
+302
View File
@@ -0,0 +1,302 @@
// billing.go — the per-tenant billing DATA bridge, the Go port of console's
// app/billing/v1/[...path]/route.ts (task #41, the BFF catch-all sweep). It lets the
// statically-exported console reach its own money surface at the CANONICAL same-origin
// /v1/billing/* (nothing before /v1/): GET|POST /v1/billing/<path> forwards to
// commerce's /v1/billing/<path> with the admin COMMERCE_SERVICE_TOKEN, SCOPING every
// request to the VALIDATED caller's own billing subject — so a tenant can only ever
// read/act on its OWN ledger (balance / usage / invoices / subscriptions /
// payment-methods / spend-alerts / …), never another's.
//
// TWO INDEPENDENT BOUNDS, because the token makes this a privileged forwarder:
// 1. WHICH ENDPOINT — billingForwardable, the per-method allowlist below. It is the
// authorization gate: an unlisted path is 404'd before the token is ever attached, so
// no money-MINT route (deposit/credit/refund/…) can be reached through this bridge.
// 2. WHOSE DATA — the subject-pinning below. It aims a permitted call at the caller's own
// ledger. It is an IDOR control and NOT an authority control: on a mint route it would
// have pinned the CREDIT to the attacker's own account. (1) is what stops that.
//
// WHY A SERVER HANDLER (not a same-origin passthrough). Commerce's billing surface is
// service-token-gated and filters DIFFERENT endpoints on DIFFERENT subject params —
// subscriptions on ?userId, payment-methods on ?customerId, usage on ?user. Pinning
// only ONE leaves the others UNFILTERED, so a request with no (or a forged) param
// returns every subject's rows in the namespace. This handler pins ALL of them to the
// server-resolved subject (and drops ?org), on the query AND the write body — exactly
// mirroring console's billing-scope.ts and commerce's own edge-auth billingSubjectKeys.
//
// IDOR-safe: the subject is derived from the VALIDATED identity (resolveCaller →
// principal.Validated / c.Org() / c.User()), NEVER a client-supplied userId/org. A
// bearer-less request with a forged X-Org-Id has no validated principal and is refused.
package account
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"strings"
"unicode"
"github.com/hanzoai/account"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
)
// billingForwardable — THE allowlist of billing endpoints this bridge may forward, keyed
// by method. It is the whole authorization story of the bridge, because forwarding IS
// authorization here: every forwarded request carries the admin COMMERCE_SERVICE_TOKEN,
// and commerce's money gate is MayMintMoney(c) = IsServiceToken(c) || IsSuperAdmin(c)
// (middleware/platformonly.go). The token satisfies IsServiceToken, so ANY subpath that
// reaches commerce is executed with PLATFORM authority — not the caller's. Commerce 403s
// an org admin who calls POST /v1/billing/deposit directly; without this table the bridge
// handed that same person the platform's own credential and minted it for them, scoped —
// by the subject-pinning below — to their OWN account. That is the escalation, and
// subject-pinning is what AIMS it, not what stops it. Only a path gate stops it.
//
// It is an ALLOWLIST, never a denylist: a denylist must enumerate every mint route
// (deposit/credit/refund/credit-grants/payouts/husd/allotment…) and stays correct only
// until commerce adds the next one — a route this file has never heard of is then
// forwarded by default. Here the default is REFUSE, so a new commerce mint route is
// unreachable the day it lands, with no change on this side. One table, one place; a path
// not in it cannot reach commerce, by construction.
//
// GET and POST are SEPARATE sets because a read bridge and a write bridge are different
// concerns: `payouts` is a legitimate read and a money-MINT write (api/billing/handlers.go
// `api.Get("/payouts", ListPayouts)` vs `api.Post("/payouts", mintRequired, CreatePayout)`),
// so one method-blind set would hand the mint to every reader. The POST set is therefore
// deliberately tiny and holds NOTHING that creates spendable balance from a client-named
// amount: cancel/reactivate a subscription, vault a card, create a budget, and a top-up
// that CHARGES a real card (money in, not minted). Every entry is a call the console
// actually makes; `{}` matches exactly one opaque id segment.
//
// EVIDENCE — each entry is a live console call (repo hanzoai/console):
//
// GET balance src/lib/api/billing.ts:397 sidebar wallet + billing overview
// GET usage src/lib/api/billing.ts:415 cost reports / AI metrics
// GET invoices src/lib/api/billing.ts:419 invoice history table
// GET invoices/{}/pdf src/components/products/billing/BillingInvoices.tsx:31
// GET subscriptions src/lib/api/billing.ts:423 subscriptions list
// GET payment-methods src/lib/api/billing.ts:450 saved cards (masked)
// GET spend-alerts src/lib/api/billing.ts:482 budgets / spend caps
// GET payment-config src/lib/api/billing.ts:552 public Square app/location id
// GET plans src/lib/api/plans.ts:126 published tiers
// GET payouts src/components/products/SettlementModule.tsx:61 settlement view
// POST subscriptions/{}/cancel src/lib/api/billing.ts:434
// POST subscriptions/{}/reactivate src/lib/api/billing.ts:444
// POST payment-methods src/lib/api/billing.ts:461 vault a Square nonce (no PAN)
// POST spend-alerts src/lib/api/billing.ts:500 create a budget
// POST topup/token src/lib/api/billing.ts:565 charge a card → credit
//
// balance/usage/payment-methods are ALSO served natively by clients/billing (order 121),
// which wins over this catch-all (122), so those entries are reached only on a deploy
// where that subsystem is disabled. They are listed because they are legitimate reads of
// the caller's own ledger, not because this bridge is their primary route.
//
// NOT LISTED, deliberately: `me/welcome` and `grant-starter` (console calls the first at
// billing.ts:407 and the second server-side at src/lib/server/billing-grant.ts:35) exist
// in NEITHER the pinned commerce (v1.48.5) route table — both 404 today whether or not
// this bridge forwards them, and grant-starter is mint-gated and browser-unreachable by
// design. The console's PATCH/DELETE calls (spend-alerts/{}, payment-methods/{}) are absent
// because routesBridge mounts GET+POST only, so they never reached this handler.
var billingForwardable = map[string][]string{
http.MethodGet: {
"balance",
"usage",
"invoices",
"invoices/{}/pdf",
"subscriptions",
"payment-methods",
"spend-alerts",
"payment-config",
"plans",
"payouts",
},
http.MethodPost: {
"subscriptions/{}/cancel",
"subscriptions/{}/reactivate",
"payment-methods",
"spend-alerts",
"topup/token",
},
}
// isForwardableBilling reports whether method+sub is in billingForwardable. sub has
// already passed isSafeSegment, so no segment can contain a slash, a percent-escape, or a
// traversal — a pattern segment therefore matches exactly one real segment and `{}` cannot
// swallow a path. Fail-closed: an unknown method or an unlisted path is false.
func isForwardableBilling(method, sub string) bool {
got := strings.Split(sub, "/")
for _, pattern := range billingForwardable[method] {
want := strings.Split(pattern, "/")
if len(want) != len(got) {
continue
}
match := true
for i, seg := range want {
if seg != "{}" && seg != got[i] {
match = false
break
}
}
if match {
return true
}
}
return false
}
// billingSubjectKeys — every query/body param through which a commerce billing endpoint
// identifies its subject. Kept identical to commerce's edge-auth billingSubjectKeys
// {user,userId,customerId} AND console's billing-scope.ts BILLING_SUBJECT_KEYS. Change
// all three together — pinning ALL of them is what scopes EVERY endpoint no matter which
// param it filters on.
var billingSubjectKeys = []string{"user", "userId", "customerId"}
func isSubjectKey(k string) bool {
for _, s := range billingSubjectKeys {
if s == k {
return true
}
}
return false
}
// scopedBillingSearch — pin every billingSubjectKey to subject (OVERWRITING any client
// value — the browser cannot widen scope) and DROP org. Every OTHER param (currency,
// status, date range) passes through untouched. Mirrors billing-scope.ts.
func scopedBillingSearch(in url.Values, subject string) url.Values {
out := url.Values{}
for k, v := range in {
if k == "org" || isSubjectKey(k) {
continue // org dropped; subject keys set authoritatively below
}
out[k] = v
}
for _, k := range billingSubjectKeys {
out.Set(k, subject)
}
return out
}
// scopedBillingBody — pin every billingSubjectKey on a top-level JSON object to subject
// (commerce reads the subject from the JSON body on writes like create-spend-alert). A
// non-JSON / non-object / empty body is returned UNCHANGED — this only ever narrows a
// JSON object to the caller; it never invents a body. Mirrors billing-scope.ts.
func scopedBillingBody(raw []byte, subject string) []byte {
if len(bytes.TrimSpace(raw)) == 0 {
return raw
}
var obj map[string]json.RawMessage
if err := json.Unmarshal(raw, &obj); err != nil {
return raw // JSON array / scalar / form / binary — leave untouched
}
subj, err := json.Marshal(subject)
if err != nil {
return raw
}
for _, k := range billingSubjectKeys {
obj[k] = subj
}
out, err := json.Marshal(obj)
if err != nil {
return raw
}
return out
}
// isSafeSegment reports whether a path segment is safe to forward. It is the ONE segment
// guard for this package (the billing AND commerce bridges): a segment is safe only if
// it is non-empty, not "." / "..", and free of any character a downstream router could
// re-split or re-decode into traversal — slash, backslash, percent-escape (`%2f`/`%2e`,
// single- or N-encoded), matrix param (`;`), or a control char (incl. null). The router
// leaves `%2f`/`%2e` UNdecoded in the wildcard param, but the Go http client — and
// commerce's own router — WILL decode+normalize them downstream, turning
// `x/..%2fbilling` into `/v1/billing`: a tunnel PAST the allow-list into the money
// surface. Rejecting `%`/`;` at the segment makes single-, double-, and N-encoded
// traversal impossible. Billing endpoints / commerce ids are opaque + escape-free, so
// this never over-blocks. Mirrors console's bearer-proxy pathIsClean.
func isSafeSegment(s string) bool {
if s == "" || s == "." || s == ".." {
return false
}
for _, r := range s {
if r == '/' || r == '\\' || r == '%' || r == ';' || unicode.IsControl(r) {
return false
}
}
return true
}
// commerceCreds resolves the commerce base + admin S2S token from server-only env
// (COMMERCE_URL default the public gateway; COMMERCE_SERVICE_TOKEN sourced from KMS —
// never a browser value). Same wiring as clients/admin + topup.go's HUSD credit.
func commerceCreds() (base, token string) {
base = strings.TrimRight(getenv("COMMERCE_URL", "https://api.hanzo.ai"), "/")
token = getenv("COMMERCE_SERVICE_TOKEN", "")
return
}
// billingData forwards GET|POST /v1/billing/<path> to commerce's /v1/billing/<path>,
// scoped to the caller's OWN subject. Mirrors GET/POST app/billing/v1/[...path]/route.ts.
func billingData(s *cloud.Service[state], c *zip.Ctx) error {
// IDOR boundary: the subject is the VALIDATED caller's own org/user, never a client
// value. requireOwner=true — billing is always org-scoped (a zero-org user has none).
cr, ok := resolveCaller(c, true)
if !ok {
return zip.ErrForbidden("sign in to view billing")
}
method := c.Method()
if method != http.MethodGet && method != http.MethodPost {
return zip.Errorf(http.StatusMethodNotAllowed, "method not allowed")
}
base, token := commerceCreds()
if token == "" {
// Honest "not configured" (mirrors the Node route's 501 when COMMERCE_TOKEN
// is unset) — the console shows a truthful state, never a fabricated balance.
return zip.Errorf(http.StatusNotImplemented, "billing is not configured on this deployment (COMMERCE_SERVICE_TOKEN unset)")
}
sub := strings.Trim(strings.TrimPrefix(c.Fiber().Params("*"), "/"), "/")
if sub == "" {
return zip.Errorf(http.StatusNotFound, "billing endpoint required")
}
for _, seg := range strings.Split(sub, "/") {
if !isSafeSegment(seg) {
return zip.ErrBadRequest("invalid billing path")
}
}
// THE authorization gate. Forwarding is authorization: the request below carries the
// admin service token, which satisfies commerce's MayMintMoney. So refuse anything the
// console does not actually call — BEFORE the token is attached. Fail closed (404, the
// same answer an unrouted path gives, so this leaks no map of the money surface).
if !isForwardableBilling(method, sub) {
return zip.Errorf(http.StatusNotFound, "not a forwardable billing endpoint")
}
// Scope EVERY request to the caller's OWN subject — query AND write body — so
// commerce's per-tenant isolation can never be crossed from the browser. The
// subject comes from the ONE rule (ai/object.Payer), keyed on the IAM username
// (cr.username = X-User-Name) the gate also keys on — so a top-up credits the
// SAME account the gate debits. Keying on cr.name (X-User-Id, a UUID on the
// direct-bearer path) would fund an account the gate never reads: the split.
subject := account.Payer(account.Credential{Owner: cr.owner, Name: cr.username}).Subject()
inQuery, _ := url.ParseQuery(string(c.Fiber().Request().URI().QueryString()))
q := scopedBillingSearch(inQuery, subject)
var body []byte
if method == http.MethodPost {
body = scopedBillingBody(c.Body(), subject)
}
raw, status, err := commerceDo(c.Context(), base, token, method, "/v1/billing/"+sub, q, cr.owner, body)
if err != nil {
return zip.Errorf(http.StatusBadGateway, "billing upstream unreachable: %v", err)
}
// A per-tenant money response must NEVER be cached (a stale balance after a
// completion/top-up); commerce answers JSON, so pin JSON + no-store.
c.SetHeader("Content-Type", "application/json")
c.SetHeader("Cache-Control", "no-store, must-revalidate")
return c.Bytes(status, raw)
}
@@ -1,7 +1,8 @@
package console
package account
import (
"encoding/json"
"github.com/hanzoai/account"
"io"
"net/http"
"net/http/httptest"
@@ -11,22 +12,49 @@ import (
)
// billing_test.go — the per-tenant billing bridge (billing.go). Proves the tenant
// scoping that prevents cross-tenant billing reads (the Go port of console2's
// scoping that prevents cross-tenant billing reads (the Go port of console's
// billing-scope.test.ts) AND the IDOR-safe handler forwarding.
// ── pure scoping ─────────────────────────────────────────────────────────────
// TestBillingSubject proves the top-up subject is resolved through the ONE rule
// (ai/object.Payer) — so a top-up credits the SAME account the ai gate debits and
// the console reads. The signup org bills per-person (matching the gate), which is
// the whole fix: money and gate land on one account.
func TestBillingSubject(t *testing.T) {
t.Setenv("PERSONAL_BILLING_ORGS", "hanzo")
cases := []struct{ org, name, want string }{
{"acme", "alice", "acme"}, // dedicated org bills per-ORG
{"hanzo", "Dave", "hanzo/dave"}, // personal-billing org bills per-USER (lowercased)
{"hanzo", "", "hanzo"}, // personal org, no name → org
{"", "x", ""}, // no org → empty subject
{"acme", "alice", "acme"}, // real org: any member bills the ONE org account
{"hanzo", "Dave", "hanzo/dave"}, // signup org: each person bills their OWN account
{"hanzo", "z", "hanzo/z"}, // another signup person — their own account
{"hanzo", "", "hanzo"}, // no name (org-owned principal) → org pool
{"Hanzo", "Z", "hanzo/z"}, // folded
{"", "x", ""}, // no org → empty subject (cannot bill)
}
for _, c := range cases {
if got := billingSubject(c.org, c.name); got != c.want {
t.Fatalf("billingSubject(%q,%q): want %q, got %q", c.org, c.name, c.want, got)
got := account.Payer(account.Credential{Owner: c.org, Name: c.name}).Subject()
if got != c.want {
t.Fatalf("Payer(%q,%q).Subject(): want %q, got %q", c.org, c.name, c.want, got)
}
}
}
// TestBillingSubject_IgnoresLegacyEnv locks that the killed allowlist envs have NO
// effect: nothing reads them. Set to values that WOULD have flipped every
// resolution — the subject is unchanged. This is the console/top-up half of the
// same proof ai carries (one rule, no config), so the view and the gate can never
// disagree, and the deleted CR env is a genuine no-op.
func TestBillingSubject_IgnoresLegacyEnv(t *testing.T) {
t.Setenv("PERSONAL_BILLING_ORGS", "hanzo,acme") // would have split acme per-user
t.Setenv("ORG_BILLING_ORGS", "hanzo") // would have pooled the signup org
cases := []struct{ org, name, want string }{
{"hanzo", "z", "hanzo/z"}, // env cannot pool the signup org
{"acme", "alice", "acme"}, // env cannot split a real org per-user
{"maxpower", "dave", "maxpower"}, // untouched
}
for _, c := range cases {
got := account.Payer(account.Credential{Owner: c.org, Name: c.name}).Subject()
if got != c.want {
t.Fatalf("legacy env must be ignored: Payer(%q,%q).Subject() want %q, got %q", c.org, c.name, c.want, got)
}
}
}
@@ -132,7 +160,6 @@ func TestBilling_ScopesQueryToCallerAndForwards(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
t.Setenv("PERSONAL_BILLING_ORGS", "hanzo") // acme is a DEDICATED org → subject "acme"
app := mountApp(t, "http://iam.invalid", "", "")
// alice/acme with a FORGED ?userId=victim & ?org=othercorp: the handler must pin
@@ -165,7 +192,6 @@ func TestBilling_ScopesWriteBodyToCaller(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
t.Setenv("PERSONAL_BILLING_ORGS", "hanzo")
app := mountApp(t, "http://iam.invalid", "", "")
// a POST with a forged userId in the body must be overwritten to acme.
+257
View File
@@ -0,0 +1,257 @@
package account
import (
"net/http"
"strings"
"testing"
commercebilling "github.com/hanzoai/commerce/api/billing"
commercemid "github.com/hanzoai/commerce/middleware"
"github.com/zap-proto/zip"
)
// bridge_mint_test.go — the privilege-escalation boundary of the /v1/billing/*
// bridge: an ordinary signed-in ORG user must never reach commerce's money-MINT
// surface.
//
// THE ESCALATION THIS LOCKS OUT. The bridge forwards to commerce with the admin
// COMMERCE_SERVICE_TOKEN. Commerce gates every mint on
// MayMintMoney(c) = IsServiceToken(c) || IsSuperAdmin(c) (middleware/platformonly.go)
// — and the bridge's service token satisfies IsServiceToken. So ANY subpath the
// bridge forwards is executed by commerce as the PLATFORM, not as the caller.
// billingData scopes the SUBJECT to the caller's own account, which is exactly the
// attack rather than a defense: an org user mints to THEMSELVES. Commerce's own
// gate comment names this: "let ANY org owner self-credit unlimited balance (POST
// /v1/billing/deposit &c.) → unlimited free inference."
//
// Commerce 403s that same org admin when they call it DIRECTLY
// (TestC1_OrgAdminDeniedOnEveryMintRoute) and mints 201 for the service token
// (TestC1_ServiceTokenMintsDeposit). The bridge is what converts the former into
// the latter. The gate therefore has to live HERE, at the point that hands out the
// token: forwardable subpaths are an ALLOWLIST, and a mint path is not on it.
//
// alice is an ordinary org user — X-Org-Id "acme", owner != "admin", NOT a
// SuperAdmin — i.e. precisely the principal commerce refuses at the front door.
// TestBridge_OrgUserCannotReachMint is the reproduction. Each of these commerce
// subpaths is PlatformOnly-gated (api/billing/handlers.go: `mintRequired`), meaning
// possession of the service token IS authority to create spendable balance. None
// may leave cloud. A request that never reaches commerce cannot mint, so the
// assertion is twofold: the caller is refused AND upstream saw nothing.
// mintSurface asks COMMERCE which routes it gates, rather than keeping a copy.
//
// The list used to live here by hand under "kept in lockstep with
// api/billing/handlers.go" — and it had already drifted: 10 paths here against
// 16 commerce actually gates. A comment cannot hold two lists together. Now
// commerce DECLARES its gated surface (middleware.Mint records what it gates)
// and we read that declaration, so a mint route added there is covered here with
// nobody remembering to do anything.
//
// Registration is what populates the registry, so register first, then read.
func mintSurface(t *testing.T) []commercemid.MintRoute {
t.Helper()
commercebilling.Route(zip.New(zip.Config{DisableStartupMessage: true}).Group("/v1"))
var out []commercemid.MintRoute
for _, r := range commercemid.MintRoutes() {
// Only what THIS bridge can address: it forwards /v1/billing/* alone.
if !strings.HasPrefix(r.Path, "/v1/billing/") {
continue
}
// A wildcard segment needs some concrete value to be requestable; which
// one is irrelevant, since a refused call never reaches an id.
parts := strings.Split(r.Path, "/")
for i, seg := range parts {
if strings.HasPrefix(seg, ":") || seg == "{}" {
parts[i] = "probe"
}
}
r.Path = strings.Join(parts, "/")
out = append(out, r)
}
if len(out) == 0 {
t.Fatal("commerce declared no /v1/billing mint routes — the registry is not being populated")
}
return out
}
func TestBridge_OrgUserCannotReachMint(t *testing.T) {
mintPaths := mintSurface(t)
t.Logf("commerce declares %d gated /v1/billing mint routes", len(mintPaths))
for _, m := range mintPaths {
t.Run(m.Method+" "+m.Path, func(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
app := mountApp(t, "http://iam.invalid", "", "")
code, body := callH(t, app, m.Method, m.Path, alice, `{}`)
// The mint request must NEVER reach commerce: arriving there at all means
// it arrived bearing the admin service token, which IS the authority to
// mint (MayMintMoney → AuthorizeMint → the ledger write).
if f.path != "" {
t.Fatalf("ESCALATION: an ordinary org user's %s %s reached commerce at %q "+
"carrying %q — the service token that satisfies MayMintMoney. "+
"Minted subject=%v amount=%v in org=%q.",
m.Method, m.Path, f.path, f.auth, f.body["user"], f.body["amount"], f.org)
}
if code != http.StatusNotFound {
t.Fatalf("%s %s: want 404 (not a forwardable billing endpoint), got %d (%s)",
m.Method, m.Path, code, body)
}
})
}
}
// TestBridge_ConsoleCallsStillForward is the other half of the allowlist: the calls the
// console ACTUALLY makes must still reach commerce. An allowlist that blocks the product
// is not a fix, so each entry here is a live console call (cited in billing.go), and this
// test fails if a future edit narrows the table below the console's real needs.
func TestBridge_ConsoleCallsStillForward(t *testing.T) {
calls := []struct{ method, path, want string }{
{http.MethodGet, "/v1/billing/invoices", "/v1/billing/invoices"},
{http.MethodGet, "/v1/billing/invoices/inv_123/pdf", "/v1/billing/invoices/inv_123/pdf"},
{http.MethodGet, "/v1/billing/subscriptions", "/v1/billing/subscriptions"},
{http.MethodGet, "/v1/billing/spend-alerts", "/v1/billing/spend-alerts"},
{http.MethodGet, "/v1/billing/payment-config", "/v1/billing/payment-config"},
{http.MethodGet, "/v1/billing/plans", "/v1/billing/plans"},
{http.MethodGet, "/v1/billing/payouts", "/v1/billing/payouts"},
{http.MethodPost, "/v1/billing/subscriptions/sub_1/cancel", "/v1/billing/subscriptions/sub_1/cancel"},
{http.MethodPost, "/v1/billing/subscriptions/sub_1/reactivate", "/v1/billing/subscriptions/sub_1/reactivate"},
{http.MethodPost, "/v1/billing/payment-methods", "/v1/billing/payment-methods"},
{http.MethodPost, "/v1/billing/spend-alerts", "/v1/billing/spend-alerts"},
{http.MethodPost, "/v1/billing/topup/token", "/v1/billing/topup/token"},
}
for _, call := range calls {
t.Run(call.method+" "+call.path, func(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
app := mountApp(t, "http://iam.invalid", "", "")
code, body := callH(t, app, call.method, call.path, alice, "{}")
if code != http.StatusOK {
t.Fatalf("%s %s: want 200 (the console needs this), got %d (%s)",
call.method, call.path, code, body)
}
if f.path != call.want {
t.Fatalf("%s %s must forward to %q, got %q", call.method, call.path, call.want, f.path)
}
})
}
}
// TestBridge_UnlistedPathsAreRefused covers the rest of the money surface — routes that
// are NOT mint-gated but that the console never calls. The bridge is not a general
// commerce proxy; least privilege means "only what the product needs", so these 404
// even though commerce would have served them to a service token.
func TestBridge_UnlistedPathsAreRefused(t *testing.T) {
unlisted := []struct{ method, path string }{
{http.MethodPost, "/v1/billing/invoices"}, // CreateInvoice (admin group)
{http.MethodPost, "/v1/billing/invoices/i1/pay"}, // PayInvoice
{http.MethodPost, "/v1/billing/invoices/i1/void"}, // VoidInvoice
{http.MethodPost, "/v1/billing/meters"}, // CreateMeter
{http.MethodPost, "/v1/billing/pricing-rules"}, // CreatePricingRule
{http.MethodPost, "/v1/billing/withdraw"}, // money OUT
{http.MethodPost, "/v1/billing/usage"}, // RecordUsage — the meter itself
{http.MethodGet, "/v1/billing/balance/all"}, // every subject's balance
{http.MethodGet, "/v1/billing/sbom"}, // OSS payout surface
{http.MethodGet, "/v1/billing/oss-payout/summary"}, // OSS payout rollup
{http.MethodPost, "/v1/billing/subscriptions"}, // CreateBillingSubscription
}
for _, u := range unlisted {
t.Run(u.method+" "+u.path, func(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
app := mountApp(t, "http://iam.invalid", "", "")
code, _ := callH(t, app, u.method, u.path, alice, "{}")
if f.path != "" {
t.Fatalf("%s %s is not a console call and must not reach commerce, but upstream saw %q",
u.method, u.path, f.path)
}
if code != http.StatusNotFound {
t.Fatalf("%s %s: want 404, got %d", u.method, u.path, code)
}
})
}
}
// TestBridge_ReadAllowlistIsNotAWriteAllowlist pins the method split. `payouts` is the
// proof that one method-blind set would be a hole: GET /payouts is a plain read, POST
// /payouts is `mintRequired` (api/billing/handlers.go). The same string must resolve
// differently by method, or reading the settlement view would grant minting a payout.
func TestBridge_ReadAllowlistIsNotAWriteAllowlist(t *testing.T) {
if !isForwardableBilling(http.MethodGet, "payouts") {
t.Fatal("GET payouts is a live console read and must be forwardable")
}
if isForwardableBilling(http.MethodPost, "payouts") {
t.Fatal("POST payouts is mint-gated in commerce and must NEVER be forwardable")
}
// A GET-only entry must not leak into POST, and vice-versa.
if isForwardableBilling(http.MethodPost, "invoices") {
t.Fatal("POST invoices must not inherit the GET entry")
}
if isForwardableBilling(http.MethodGet, "topup/token") {
t.Fatal("GET topup/token must not inherit the POST entry")
}
// An unknown method fails closed (the router mounts GET+POST only; defense in depth).
for _, m := range []string{http.MethodPut, http.MethodPatch, http.MethodDelete, ""} {
if isForwardableBilling(m, "balance") {
t.Fatalf("method %q must fail closed", m)
}
}
// `{}` matches exactly ONE segment — it can never swallow a path into a mint route.
if isForwardableBilling(http.MethodPost, "subscriptions/a/b/cancel") {
t.Fatal("{} must match exactly one segment")
}
}
// TestBridge_StoreBridgeCannotReachBilling is the sibling lock. /v1/commerce/* carries the
// SAME admin token with FULL CRUD, and its own allowlist (commerceStoreHeads) is what keeps
// it a store proxy. Prove it cannot tunnel into the money surface — a store head that
// resolved to `billing` would reopen this hole from the other bridge.
func TestBridge_StoreBridgeCannotReachBilling(t *testing.T) {
for _, p := range []string{
"/v1/commerce/billing/deposit",
"/v1/commerce/billing",
"/v1/commerce/checkout",
"/v1/commerce/_/commerce/tenants",
} {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
app := mountApp(t, "http://iam.invalid", "", "")
code, _ := callH(t, app, http.MethodPost, p, alice, `{"amount":100000000}`)
if f.path != "" {
t.Fatalf("store bridge %q must never reach commerce, but upstream saw %q", p, f.path)
}
if code != http.StatusNotFound {
t.Fatalf("store bridge %q: want 404, got %d", p, code)
}
}
}
// TestBridge_MintIsRefusedEvenWithForgedSubject proves the refusal does not depend
// on the subject-pinning. Pinning is an IDOR control, not an authority control: it
// makes the mint land on the CALLER's own account, which is the attack, not a
// defense. The path gate must refuse before any of that logic runs.
func TestBridge_MintIsRefusedEvenWithForgedSubject(t *testing.T) {
f := &fakeBilling{}
t.Setenv("COMMERCE_URL", f.server(t).URL)
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
app := mountApp(t, "http://iam.invalid", "", "")
code, _ := callH(t, app, http.MethodPost, "/v1/billing/deposit", alice,
`{"user":"victim","userId":"victim","amount":100000000}`)
if f.path != "" {
t.Fatalf("ESCALATION: deposit reached commerce at %q with the service token", f.path)
}
if code != http.StatusNotFound {
t.Fatalf("forged-subject deposit: want 404, got %d", code)
}
}
@@ -1,4 +1,4 @@
// commerce.go — the per-tenant STORE data bridge, the Go port of console2's
// commerce.go — the per-tenant STORE data bridge, the Go port of console's
// app/commerce/[...path]/route.ts (task #41, the BFF catch-all sweep; the store twin
// of billing.go). It lets the statically-exported console reach its merchant store at
// the CANONICAL same-origin /v1/commerce/* (nothing before /v1/): GET|POST|PUT|PATCH|
@@ -15,7 +15,7 @@
// console namespaces the store under /v1/commerce/* only to keep the generic store
// heads (product/order/user/store) from colliding with the rest of the /v1 surface;
// this bridge strips that console-side namespace and forwards to commerce's real bare
// head — EXACTLY the mapping console2's next.config rewrite already proved live
// head — EXACTLY the mapping console's next.config rewrite already proved live
// (`/v1/commerce/:path*` → `/commerce/v1/:path*` → commerce.svc/v1/:path*).
//
// WHY A SERVER HANDLER (not a same-origin passthrough). Commerce's store is
@@ -32,20 +32,21 @@
// (403) BEFORE any commerce call — the exact off-gateway forge principal.Validated
// closes. Least privilege on the path: only the merchant store heads are reachable, so
// this bridge can NOT tunnel to /v1/billing (its own subject-scoped bridge), /v1/checkout
// (the money path), or /v1/_/commerce/tenants (tenant admin) — mirroring console2's
// (the money path), or /v1/_/commerce/tenants (tenant admin) — mirroring console's
// proxy-allow.ts allowCommerceSurface.
package console
package account
import (
"net/http"
"net/url"
"strings"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
)
// commerceStoreHeads — the merchant store REST heads reachable through /v1/commerce/*.
// Kept IDENTICAL to console2's proxy-allow.ts COMMERCE_HEADS (the same defense-in-depth
// Kept IDENTICAL to console's proxy-allow.ts COMMERCE_HEADS (the same defense-in-depth
// allow-list the Node /commerce proxy enforced), matching commerce's `rest.New(<kind>{})`
// route names. Change both together. This is what keeps the bridge a STORE proxy: a head
// not in this set (billing, checkout, namespace, _) is 404'd before any upstream call, so
@@ -79,7 +80,7 @@ func isCommerceStoreHead(sub string) bool {
// store surface /v1/<path>, scoped to the caller's OWN org. Mirrors the five method
// exports of app/commerce/[...path]/route.ts (the store dashboard reads AND writes:
// create/delete a product, etc. — full CRUD, unlike billing's read-mostly GET|POST).
func (s *svc) commerceData(c *zip.Ctx) error {
func commerceData(s *cloud.Service[state], c *zip.Ctx) error {
// IDOR boundary: the org is the VALIDATED caller's own, never a client value.
// requireOwner=true — the store is always org-scoped (a zero-org user has none).
cr, ok := resolveCaller(c, true)
@@ -1,4 +1,4 @@
package console
package account
import (
"encoding/json"
+188
View File
@@ -0,0 +1,188 @@
package account
// CSRF protection for the console money-WRITE surface (mint/revoke key, topup,
// onboard, and the billing/commerce write verbs).
//
// THREAT. The forward-perfect money path is the embed same-origin session bridge
// (middleware_identity.sessionAccessToken): a browser write is authenticated from its
// httpOnly session COOKIE, which is AMBIENT — a cross-site page's request to our
// origin carries it too. The bridge's Sec-Fetch-Site check is a NEGATIVE heuristic
// that passes VACUOUSLY when Origin/Referer/Sec-Fetch-Site are all absent (RED). So a
// state-changing write gets a POSITIVE control: a token the caller can obtain ONLY by
// reading a same-origin response (the Same-Origin Policy blocks a cross-site page from
// reading GET /v1/csrf) and MUST echo in a CUSTOM header (a cross-site simple/
// form request cannot set X-CSRF-Token without a CORS preflight the server never
// grants).
//
// SCOPE — only the AMBIENT path. A Bearer/Basic-authenticated request is immune to
// CSRF (a cross-site attacker cannot set the Authorization header), and the gateway
// path forwards minted identity HEADERS with no browser cookie. requireCSRF therefore
// enforces ONLY when the request carries NO explicit Authorization/X-Authorization AND
// a Cookie is present — i.e. exactly the ambient-cookie/embed browser write. Every
// other caller (API/machine Bearer, gateway-fronted, the header-injected tests) is
// unaffected. Fail-secure: an ambient write with a missing/invalid token is refused.
//
// TOKEN — base64url( ts_be64(8) || mac(16) ), where
// mac = KeyedBLAKE3(csrfKey, domain \x00 uid \x00 org \x00 ts)[:16] (luxfi/crypto).
// It is BOUND to the validated principal (X-User-Id + X-Org-Id) so a token minted for
// one identity cannot authorize a write as another, and it EXPIRES after csrfTTL. The
// key is server-only (KMS-sourced env CONSOLE_CSRF_KEY); no key ⇒ a per-process random
// key (tokens then reset on restart — the SPA re-fetches on a 403).
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/hanzoai/cloud"
"github.com/luxfi/crypto/blake3"
luxlog "github.com/luxfi/log"
"github.com/zap-proto/zip"
)
const (
csrfDomain = "hanzo-console-csrf-v1"
csrfMACLen = 16 // 128-bit truncated BLAKE3 MAC — ample for a bound, expiring token
csrfTTL = 12 * time.Hour // token lifetime; SPA re-fetches on expiry/403
csrfClockSkew = 120 // seconds of future tolerance
csrfTokenLen = 8 + csrfMACLen // ts || mac
)
// csrfKeyOnce guards the process-wide CSRF MAC key. It is shared across BOTH account
// subsystems (account@48 issues GET /v1/csrf; account-bridge@122 verifies the token on
// the /v1/billing|commerce writes), so a token minted by one verifies on the other —
// even in the ephemeral (no CONSOLE_CSRF_KEY) case where each Mount would otherwise
// generate its own random key. Deterministic from CONSOLE_CSRF_KEY (KMS) in prod.
var (
csrfKeyOnce sync.Once
csrfKeyVal []byte
)
// sharedCSRFKey returns the process-wide keyed-BLAKE3 MAC key, loaded ONCE.
func sharedCSRFKey(log luxlog.Logger) []byte {
csrfKeyOnce.Do(func() { csrfKeyVal = loadCSRFKey(log) })
return csrfKeyVal
}
// loadCSRFKey returns the 32-byte keyed-BLAKE3 MAC key. Prefers the server-only env
// CONSOLE_CSRF_KEY (KMS-sourced; hex or base64-std, must decode to exactly 32 bytes);
// otherwise a per-process random key with a WARN (single-replica tolerable — tokens
// reset on restart, the SPA transparently re-fetches on a 403).
func loadCSRFKey(log luxlog.Logger) []byte {
if raw := strings.TrimSpace(os.Getenv("CONSOLE_CSRF_KEY")); raw != "" {
if b, err := hex.DecodeString(raw); err == nil && len(b) == 32 {
return b
}
if b, err := base64.StdEncoding.DecodeString(raw); err == nil && len(b) == 32 {
return b
}
if log != nil {
log.Warn("CONSOLE_CSRF_KEY set but not a 32-byte hex/base64 value; using an ephemeral per-process key")
}
} else if log != nil {
log.Warn("CONSOLE_CSRF_KEY unset; using an ephemeral per-process CSRF key (set it from KMS for multi-replica/restart-stable tokens)")
}
k := make([]byte, 32)
if _, err := rand.Read(k); err != nil {
// crypto/rand failure is catastrophic; a zero key would be forgeable, so panic.
panic("console: cannot generate CSRF key: " + err.Error())
}
return k
}
// csrfMAC computes the bound, truncated keyed-BLAKE3 MAC for (uid, org, ts).
func csrfMAC(s *cloud.Service[state], uid, org string, ts int64) []byte {
var msg []byte
msg = append(msg, csrfDomain...)
msg = append(msg, 0)
msg = append(msg, uid...)
msg = append(msg, 0)
msg = append(msg, org...)
msg = append(msg, 0)
var t [8]byte
binary.BigEndian.PutUint64(t[:], uint64(ts))
msg = append(msg, t[:]...)
sum, err := blake3.KeyedHash(s.State.csrfKey, msg)
if err != nil {
// Only errors on a bad key length; loadCSRFKey guarantees 32 bytes.
panic("console: CSRF MAC: " + err.Error())
}
return sum[:csrfMACLen]
}
// issueCSRF mints a token bound to (uid, org) valid for csrfTTL. Returns the token and
// its lifetime in seconds.
func issueCSRF(s *cloud.Service[state], uid, org string) (string, int64) {
ts := time.Now().Unix()
var out [csrfTokenLen]byte
binary.BigEndian.PutUint64(out[:8], uint64(ts))
copy(out[8:], csrfMAC(s, uid, org, ts))
return base64.RawURLEncoding.EncodeToString(out[:]), int64(csrfTTL / time.Second)
}
// verifyCSRF checks a token against the CURRENT request's validated (uid, org) and its
// expiry, in constant time.
func verifyCSRF(s *cloud.Service[state], token, uid, org string) bool {
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(token))
if err != nil || len(raw) != csrfTokenLen {
return false
}
ts := int64(binary.BigEndian.Uint64(raw[:8]))
now := time.Now().Unix()
if ts > now+csrfClockSkew || now-ts > int64(csrfTTL/time.Second) {
return false
}
return subtle.ConstantTimeCompare(raw[8:], csrfMAC(s, uid, org, ts)) == 1
}
// ambientCookieAuth reports whether the request is authenticated by an AMBIENT
// credential (a browser cookie) rather than an explicit one. Only such requests are
// CSRF-able. Explicit Authorization/X-Authorization (Bearer/Basic) ⇒ not ambient; no
// Cookie at all (gateway header-injection, the tests) ⇒ not ambient.
func ambientCookieAuth(c *zip.Ctx) bool {
if strings.TrimSpace(c.Header("Authorization")) != "" || strings.TrimSpace(c.Header("X-Authorization")) != "" {
return false
}
return len(c.Fiber().Request().Header.Peek("Cookie")) > 0
}
// requireCSRF wraps a state-changing handler, enforcing a valid X-CSRF-Token on the
// ambient-cookie path only (see package note). A validated principal is required for
// the ambient path to mean anything; the wrapped handler still does its own
// resolveCaller, so this only ADDS the anti-CSRF gate.
func requireCSRF(s *cloud.Service[state], next zip.Handler) zip.Handler {
return func(c *zip.Ctx) error {
if !ambientCookieAuth(c) {
return next(c) // Bearer/Basic/gateway/API — not CSRF-able
}
tok := strings.TrimSpace(c.Header("X-CSRF-Token"))
if tok == "" {
return zip.ErrForbidden("missing CSRF token (GET /v1/csrf and echo it in X-CSRF-Token)")
}
if !verifyCSRF(s, tok, strings.TrimSpace(c.User()), strings.TrimSpace(c.Org())) {
return zip.ErrForbidden("invalid or expired CSRF token")
}
return next(c)
}
}
// issueCSRFToken serves GET /v1/csrf: for a VALIDATED caller, a fresh token
// bound to their identity. no-store so it is never cached by a shared proxy. This is
// the same-origin endpoint the embedded SPA reads (its response body is unreadable to
// a cross-site page), then echoes on every money write.
func issueCSRFToken(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, false) // a zero-org (first-run) user may still need a token
if !ok {
return zip.ErrForbidden("sign in to obtain a CSRF token")
}
token, ttl := issueCSRF(s, cr.name, cr.owner)
c.Fiber().Set("Cache-Control", "no-store")
return c.JSON(http.StatusOK, map[string]any{"csrfToken": token, "expiresIn": ttl})
}
+167
View File
@@ -0,0 +1,167 @@
package account
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/zap-proto/zip"
)
// req drives one request with arbitrary headers through the mounted app.
func req(t *testing.T, app *zip.App, method, path string, hdr map[string]string, body string) (int, []byte) {
t.Helper()
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
r := httptest.NewRequest(method, path, rdr)
if body != "" {
r.Header.Set("Content-Type", "application/json")
}
for k, v := range hdr {
r.Header.Set(k, v)
}
resp, err := app.Fiber().Test(r)
if err != nil {
t.Fatalf("Test %s %s: %v", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
// csrfToken fetches a CSRF token for (user, org) from the issue endpoint.
func csrfToken(t *testing.T, app *zip.App, user, org string) string {
t.Helper()
code, body := req(t, app, http.MethodGet, "/v1/csrf",
map[string]string{"X-User-Id": user, "X-Org-Id": org}, "")
if code != http.StatusOK {
t.Fatalf("GET /v1/csrf: want 200, got %d (%s)", code, body)
}
var r struct {
CsrfToken string `json:"csrfToken"`
}
mustJSON(t, body, &r)
if r.CsrfToken == "" {
t.Fatalf("empty csrfToken: %s", body)
}
return r.CsrfToken
}
// TestCSRF_AmbientWriteWithoutTokenIsRefused: a cookie-authenticated (ambient) write
// with no X-CSRF-Token is 403, and IAM is never touched.
func TestCSRF_AmbientWriteWithoutTokenIsRefused(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
code, _ := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "alice", "X-Org-Id": "acme",
"Cookie": "iam_access_token=opaque-sid", // ambient credential
}, "")
if code != http.StatusForbidden {
t.Fatalf("ambient write w/o CSRF token: want 403, got %d", code)
}
if len(f.mintedFor) != 0 {
t.Fatalf("IAM mint reached without a CSRF token: %v", f.mintedFor)
}
}
// TestCSRF_AmbientWriteWithValidTokenAllows: same request WITH a valid token mints.
func TestCSRF_AmbientWriteWithValidTokenAllows(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
tok := csrfToken(t, app, "alice", "acme")
code, body := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "alice", "X-Org-Id": "acme",
"Cookie": "iam_access_token=opaque-sid",
"X-CSRF-Token": tok,
}, "")
if code != http.StatusOK {
t.Fatalf("ambient write with valid CSRF token: want 200, got %d (%s)", code, body)
}
if len(f.mintedFor) != 1 || f.mintedFor[0] != "acme/alice" {
t.Fatalf("mint should target acme/alice: %v", f.mintedFor)
}
}
// TestCSRF_TokenBoundToIdentity: a token minted for alice cannot authorize a write as
// mallory — the MAC binds (X-User-Id, X-Org-Id).
func TestCSRF_TokenBoundToIdentity(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
aliceTok := csrfToken(t, app, "alice", "acme")
code, _ := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "mallory", "X-Org-Id": "acme", // different principal
"Cookie": "iam_access_token=opaque-sid",
"X-CSRF-Token": aliceTok, // stolen/replayed token bound to alice
}, "")
if code != http.StatusForbidden {
t.Fatalf("cross-identity CSRF token replay: want 403, got %d", code)
}
if len(f.mintedFor) != 0 {
t.Fatalf("mint reached on a cross-identity token: %v", f.mintedFor)
}
}
// TestCSRF_BearerAuthSkipsCSRF: an explicit Bearer credential is not CSRF-able, so no
// token is required (API/machine callers unaffected).
func TestCSRF_BearerAuthSkipsCSRF(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
code, body := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "alice", "X-Org-Id": "acme",
"Authorization": "Bearer some.jwt.token", // explicit (non-ambient) credential
"Cookie": "iam_access_token=opaque-sid",
}, "")
if code != http.StatusOK {
t.Fatalf("Bearer write should skip CSRF and mint: want 200, got %d (%s)", code, body)
}
if len(f.mintedFor) != 1 {
t.Fatalf("Bearer write should have minted: %v", f.mintedFor)
}
}
// TestRateLimit_PerPrincipalBurstThen429: the money-write cap keys on the VALIDATED
// principal (un-spoofable), returns 429 past the burst, and a DIFFERENT principal is
// NOT throttled by the first's flood — and a forged X-Forwarded-For does not reset it.
func TestRateLimit_PerPrincipalBurstThen429(t *testing.T) {
f := newFakeIAM()
app := mountApp(t, f.server(t).URL, "hanzo-console", "s3cr3t")
// alice floods, sending a FRESH X-Forwarded-For each request (the old XFF keying
// would have reset the bucket every time — it must NOT now).
var got429 bool
for i := 0; i < keysWriteRatePerMin+5; i++ {
code, _ := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "alice", "X-Org-Id": "acme",
"Authorization": "Bearer j.w.t", // skip CSRF, isolate the limiter
"X-Forwarded-For": fmt.Sprintf("203.0.113.%d", i%250), // attacker rotates XFF
}, "")
if code == 429 {
got429 = true
break
}
if code != http.StatusOK {
t.Fatalf("req %d: unexpected %d", i, code)
}
}
if !got429 {
t.Fatalf("expected 429 after alice's per-principal burst of %d (XFF rotation must not reset it)", keysWriteRatePerMin)
}
// bob (a different validated principal) is unaffected by alice's exhausted bucket.
code, body := req(t, app, http.MethodPost, "/v1/iam/keys", map[string]string{
"X-User-Id": "bob", "X-Org-Id": "acme",
"Authorization": "Bearer j.w.t",
}, "")
if code != http.StatusOK {
t.Fatalf("bob must have his own bucket, not alice's: want 200, got %d (%s)", code, body)
}
}
@@ -1,5 +1,5 @@
// embed.go ports console2's app/embed-status/route.ts into the unified binary at
// GET /v1/console/embed-status (task #41). It answers ONE question for the console's
// embed.go ports console's app/embed-status/route.ts into the unified binary at
// GET /v1/embed-status (task #41). It answers ONE question for the console's
// data-product modules (Content Studio / ERP / Help Center): is this brand's shared
// embedded app provisioned and reachable, so the module can decide embed-vs-provision
// panel? A cross-origin browser can't read another origin's status (SOP + CORS), so
@@ -8,8 +8,8 @@
// TWO real jobs (why it is a handler, not a vanishing proxy):
//
// - ENTITLEMENT (server-authoritative). cms/erp/help are each a SINGLE shared
// per-BRAND instance, so only a member of the owning brand org — or a global
// admin — may frame them; a customer org gets the honest provision panel, never
// per-BRAND instance, so only a member of the owning brand org — or a
// SuperAdmin — may frame them; a customer org gets the honest provision panel, never
// a cross-tenant frame. The caller's org is the VALIDATED X-Org-Id (never a
// browser claim); the owning org is the deployment brand.
//
@@ -18,7 +18,7 @@
// {cms,erp,help}. There is NO client-controlled host in the target at all — a
// forged Host header can never steer this into probing an arbitrary origin
// (strictly tighter than route.ts, which clamped a client Host).
package console
package account
import (
"context"
@@ -26,6 +26,7 @@ import (
"strings"
"time"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
)
@@ -85,9 +86,9 @@ type embedStatusResp struct {
// Mount uses the real, time-boxed probe.
var reachProbe = liveReachProbe
// embedStatus is GET /v1/console/embed-status?app=cms|erp|help. Mirrors
// embedStatus is GET /v1/embed-status?app=cms|erp|help. Mirrors
// GET app/embed-status/route.ts.
func (s *svc) embedStatus(c *zip.Ctx) error {
func embedStatus(s *cloud.Service[state], c *zip.Ctx) error {
cr, ok := resolveCaller(c, false) // validated; a customer org (owner set) is fine
if !ok {
return zip.ErrForbidden("sign in to continue")
@@ -98,15 +99,15 @@ func (s *svc) embedStatus(c *zip.Ctx) error {
return zip.ErrBadRequest("unknown embed app")
}
origin := "https://" + app + "." + embedBrandDomain(s.brand)
origin := "https://" + app + "." + embedBrandDomain(s.Brand)
embedURL := origin + landing
// SERVER-SIDE entitlement gate: a brand-owned app frames only for a member of the
// owning brand org (cr.owner == deps.Brand) or a global admin. A non-entitled
// owning brand org (cr.owner == deps.Brand) or a SuperAdmin. A non-entitled
// caller NEVER receives the embed URL and we don't even probe — the module shows
// the provision panel. This is the authoritative gate (the client check only
// avoids a flash).
entitled := (cr.owner != "" && cr.owner == strings.ToLower(strings.TrimSpace(s.brand))) || c.IsAdmin()
entitled := (cr.owner != "" && cr.owner == strings.ToLower(strings.TrimSpace(s.Brand))) || c.IsAdmin()
if !entitled {
return c.JSON(http.StatusOK, embedStatusResp{App: app, Origin: origin, EmbedURL: "", Reachable: false, Entitled: false, Phase: "not-entitled"})
}
@@ -1,27 +1,21 @@
package console
package account
import (
"context"
"net/http"
"testing"
"github.com/hanzoai/cloud"
luxlog "github.com/luxfi/log"
"github.com/zap-proto/zip"
)
// mountBrand mounts the console surface for a given deployment brand (the embed
// mountBrand mounts the account surface for a given deployment brand (the embed
// entitlement + app-domain derivation are brand-scoped). IAM is unwired — embed-status
// does not use the confidential client.
func mountBrand(t *testing.T, brand string) *zip.App {
t.Helper()
t.Setenv("IAM_MINT_CLIENT_ID", "")
t.Setenv("IAM_MINT_CLIENT_SECRET", "")
app := zip.New(zip.Config{Logger: luxlog.New("test")})
if err := Mount(app, cloud.Deps{Logger: luxlog.New("test"), Brand: brand}); err != nil {
t.Fatalf("Mount(%s): %v", brand, err)
}
return app
return mountBoth(t, brand)
}
// stubProbe swaps the reachability probe for the duration of a test, recording how
@@ -38,7 +32,7 @@ func stubProbe(t *testing.T, up bool) *int {
func TestEmbedStatus_RequiresValidatedPrincipal(t *testing.T) {
stubProbe(t, true)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=cms", nil, "")
code, _ := callH(t, app, http.MethodGet, "/v1/embed-status?app=cms", nil, "")
if code != http.StatusForbidden {
t.Fatalf("no principal: want 403, got %d", code)
}
@@ -47,7 +41,7 @@ func TestEmbedStatus_RequiresValidatedPrincipal(t *testing.T) {
func TestEmbedStatus_UnknownApp_400(t *testing.T) {
stubProbe(t, true)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=nope",
code, _ := callH(t, app, http.MethodGet, "/v1/embed-status?app=nope",
map[string]string{"X-User-Id": "alice", "X-Org-Id": "hanzo"}, "")
if code != http.StatusBadRequest {
t.Fatalf("unknown app: want 400, got %d", code)
@@ -58,7 +52,7 @@ func TestEmbedStatus_BrandMemberEntitled_Reachable(t *testing.T) {
calls := stubProbe(t, true)
app := mountBrand(t, "hanzo")
// A member of the owning brand org (hanzo) is entitled; the probe says up.
code, body := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=cms",
code, body := callH(t, app, http.MethodGet, "/v1/embed-status?app=cms",
map[string]string{"X-User-Id": "z", "X-Org-Id": "hanzo"}, "")
if code != http.StatusOK {
t.Fatalf("brand member: want 200, got %d (%s)", code, body)
@@ -76,12 +70,12 @@ func TestEmbedStatus_BrandMemberEntitled_Reachable(t *testing.T) {
}
}
func TestEmbedStatus_GlobalAdminEntitled(t *testing.T) {
func TestEmbedStatus_SuperAdminEntitled(t *testing.T) {
stubProbe(t, false)
app := mountBrand(t, "hanzo")
// A global admin from a DIFFERENT org is still entitled (isGlobalAdmin bypass);
// A SuperAdmin from a DIFFERENT org is still entitled (isSuperAdmin bypass);
// the probe says down → not-provisioned but entitled with the embed URL.
code, body := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=erp",
code, body := callH(t, app, http.MethodGet, "/v1/embed-status?app=erp",
map[string]string{"X-User-Id": "root", "X-Org-Id": "acme", "X-User-IsAdmin": "true"}, "")
if code != http.StatusOK {
t.Fatalf("admin: want 200, got %d", code)
@@ -98,7 +92,7 @@ func TestEmbedStatus_CustomerOrgNotEntitled_NotProbed(t *testing.T) {
app := mountBrand(t, "hanzo")
// A customer org (not the brand, not admin) is NOT entitled: no embed URL, no
// probe, honest not-entitled phase — never a cross-tenant frame.
code, body := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=help",
code, body := callH(t, app, http.MethodGet, "/v1/embed-status?app=help",
map[string]string{"X-User-Id": "alice", "X-Org-Id": "acme"}, "")
if code != http.StatusOK {
t.Fatalf("customer: want 200, got %d", code)
@@ -117,7 +111,7 @@ func TestEmbedStatus_BrandDomainPerBrand(t *testing.T) {
stubProbe(t, true)
// lux apps live on lux.cloud (the app-hosting domain), NOT lux.network.
app := mountBrand(t, "lux")
code, body := callH(t, app, http.MethodGet, "/v1/console/embed-status?app=cms",
code, body := callH(t, app, http.MethodGet, "/v1/embed-status?app=cms",
map[string]string{"X-User-Id": "z", "X-Org-Id": "lux"}, "")
if code != http.StatusOK {
t.Fatalf("lux brand member: want 200, got %d", code)
@@ -1,9 +1,9 @@
// iam.go is the ONE HTTP path from the console subsystem to Hanzo IAM, acting as
// the confidential first-party `hanzo-console` client (client_secret_basic). It
// ports the privileged IAM primitives that console2's server-only
// ports the privileged IAM primitives that console's server-only
// src/lib/server/identity.ts drove — mint/revoke/get the per-user `hk-` key and
// create/read/update an organization — so those standalone Next server routes can
// be retired and console2 statically exported (task #41, "True 1-binary FE").
// be retired and console statically exported (task #41, "True 1-binary FE").
//
// WHY A CONFIDENTIAL CLIENT (and not the caller's own token). These ops are
// privileged: `mint-user-keys` writes a user's AccessKey, `add-organization`
@@ -19,7 +19,7 @@
// sourced from KMS by the deployment), never a NEXT_PUBLIC value and never the
// browser. When they are unset the subsystem is honestly "not configured" (501),
// exactly as identity.ts's mintConfigured() gate behaved — no fabricated key/org.
package console
package account
import (
"context"
@@ -140,7 +140,7 @@ type userKey struct {
}
// getUserKey reads a user's CURRENT `hk-` key AUTHORITATIVELY from IAM (get-user).
// The session claim can lag a freshly-minted key (it returns '') — so GET /keys
// The session claim can lag a freshly-minted key (it returns ) — so GET /keys
// must read IAM, not the claim (the "key never listed" bug identity.ts documents).
// `id` is the `<owner>/<name>` composite IAM parses.
func (c *iamClient) getUserKey(ctx context.Context, id string) (userKey, error) {
@@ -1,5 +1,5 @@
// onboarding.go — PURE org-naming + reserved-name policy, no transport/IAM. A
// faithful Go port of console2's src/lib/server/onboarding.ts, decomplected from
// faithful Go port of console's src/lib/server/onboarding.ts, decomplected from
// the handler so the naming rules are one testable thing (the route does the IAM
// calls; this decides the slug). Two concerns:
//
@@ -9,7 +9,7 @@
// owners (admin/built-in/app) and the brand/staff orgs (hanzo/lux/zoo/pars),
// which the OrgGate routes to the admin host. Creating one would collide with
// a staff tenant or a system principal.
package console
package account
import "strings"
@@ -1,16 +1,16 @@
package console
package account
import "testing"
func TestSlugifyOrg(t *testing.T) {
cases := map[string]string{
"Acme Rockets": "acme-rockets",
"Acme Rockets": "acme-rockets",
" Hello, World! ": "hello-world",
"UPPER_case-123": "upper-case-123",
"多 bytes 混": "bytes", // non-ASCII runes act as separators (slug is ASCII)
"---": "",
"": "",
"a.b.c": "a-b-c",
"UPPER_case-123": "upper-case-123",
"多 bytes 混": "bytes", // non-ASCII runes act as separators (slug is ASCII)
"---": "",
"": "",
"a.b.c": "a-b-c",
}
for in, want := range cases {
if got := slugifyOrg(in); got != want {
+115
View File
@@ -0,0 +1,115 @@
package account
// Per-IP rate limiting for the abuse-sensitive console write routes (hk- key
// mint/rotate/revoke, HUSD wallet top-up). This is DISTINCT from commerce's spend-cap
// (ScopeRateLimit): it caps request FREQUENCY per client IP to blunt brute-force /
// enumeration / resource-exhaustion, restoring the edge protection cloud loses when a
// caller reaches it DIRECTLY (bypassing the gateway/ingress limiter) on the money path.
//
// A token bucket per IP: `perMin` tokens refilled continuously, burst == perMin. In
// memory (cloud is single-replica for this surface); multi-replica would be a per-
// replica soft limit — acceptable defense-in-depth, not a hard global quota. Idle
// buckets are evicted lazily so the map cannot grow without bound.
import (
"net"
"strings"
"sync"
"time"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
)
type tokenBucket struct {
tokens float64
last time.Time
}
type rateLimiter struct {
mu sync.Mutex
buckets map[string]*tokenBucket
perSec float64
burst float64
ttl time.Duration // evict buckets idle longer than this
lastGC time.Time
}
// newRateLimiter builds a limiter allowing `perMin` requests/minute per IP (burst ==
// perMin). perMin<=0 disables limiting (allow always).
func newRateLimiter(perMin int) *rateLimiter {
return &rateLimiter{
buckets: map[string]*tokenBucket{},
perSec: float64(perMin) / 60.0,
burst: float64(perMin),
ttl: 10 * time.Minute,
lastGC: time.Now(),
}
}
// allow reports whether a request from key (IP) may proceed, consuming one token.
func (r *rateLimiter) allow(key string) bool {
if r.perSec <= 0 {
return true
}
now := time.Now()
r.mu.Lock()
defer r.mu.Unlock()
if now.Sub(r.lastGC) > r.ttl {
for k, b := range r.buckets {
if now.Sub(b.last) > r.ttl {
delete(r.buckets, k)
}
}
r.lastGC = now
}
b := r.buckets[key]
if b == nil {
b = &tokenBucket{tokens: r.burst, last: now}
r.buckets[key] = b
}
// Refill.
b.tokens += now.Sub(b.last).Seconds() * r.perSec
if b.tokens > r.burst {
b.tokens = r.burst
}
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
// rateKey resolves the un-spoofable key to limit on. These are all POST-AUTH money-
// write routes, so the primary key is the VALIDATED principal (X-Org-Id/X-User-Id,
// minted by SanitizeIdentity from a verified JWT — a caller cannot forge it). This is
// deliberately NOT X-Forwarded-For: the limiter exists for the OFF-GATEWAY path where
// nothing trusted stamps XFF, so keying on a client-settable XFF would let an attacker
// send a fresh value per request and reset the bucket at will (RED). An unauthenticated
// request (which the handler 403s anyway) has no principal, so it falls back to the
// SOCKET peer address (c.Fiber().IP() — the L4 RemoteAddr, the real attacker on the
// direct-to-pod path), never a header.
func rateKey(c *zip.Ctx) string {
if uid := strings.TrimSpace(c.User()); uid != "" {
return "p:" + strings.TrimSpace(c.Org()) + "/" + uid
}
ip := c.Fiber().IP()
if host, _, err := net.SplitHostPort(ip); err == nil {
ip = host
}
return "a:" + ip
}
// rateLimit wraps a handler, refusing 429 when the caller (validated principal, else
// socket peer) exceeds rl.
func rateLimit(s *cloud.Service[state], rl *rateLimiter, next zip.Handler) zip.Handler {
return func(c *zip.Ctx) error {
if !rl.allow(rateKey(c)) {
return zip.Errorf(429, "rate limit exceeded; retry shortly")
}
return next(c)
}
}
@@ -1,5 +1,5 @@
// topup.go ports console2's app/billing/v1/topup/wallet/route.ts into the unified
// binary at POST /v1/console/topup/wallet (task #41). It is the verify-and-record
// topup.go ports console's app/billing/v1/topup/wallet/route.ts into the unified
// binary at POST /v1/commerce/topup/wallet (task #41). It is the verify-and-record
// seam for an HUSD wallet top-up: the browser sends an HUSD ERC-20 transfer to the
// treasury and posts the tx hash here; this handler reads the receipt from the Hanzo
// EVM, confirms it is a mined, successful HUSD Transfer(from → treasury, value),
@@ -23,7 +23,7 @@
// Honest failure (no fabricated credit, ever): HUSD/treasury unconfigured
// (greenfield — HUSD not yet deployed) → 501; a missing/failed/non-HUSD-to-treasury
// tx → 400; the chain or commerce unreachable → 502.
package console
package account
import (
"bytes"
@@ -37,10 +37,27 @@ import (
"os"
"regexp"
"strings"
"time"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients/commerceinproc"
"github.com/zap-proto/zip"
)
// httpClient is the shared outbound client for the account subsystem's plain-HTTP seams
// (EVM JSON-RPC, commerce billing/store S2S). Small JSON envelopes, bounded reads; 15s
// is generous for an in-cluster / same-region hop. (Owned here — the S2S transport home
// — since the former waitlist.go was retired with the /v1/console namespace.)
var httpClient = &http.Client{Timeout: 15 * time.Second}
// commerceHTTP is the client for the commerce S2S seam ONLY (commerceDo). Separate
// from httpClient (which also dials EVM JSON-RPC) so that — when commerce is folded
// in-process (task #111) — commerce calls dispatch to the in-process handler via
// commerceinproc's self-routing transport (no socket to the standalone), while the
// HUSD chain RPC keeps going over the real network. Off the co-resident path it is a
// plain HTTP client, exactly like before.
var commerceHTTP = commerceinproc.Client(15 * time.Second)
// transferTopic is keccak256("Transfer(address,address,uint256)") — the ERC-20
// Transfer event signature, topics[0] of every transfer log. A universally-fixed
// constant (no need to hash at runtime).
@@ -69,7 +86,7 @@ type topupConfig struct {
}
func loadTopupConfig() topupConfig {
chainID := int64(36900)
chainID := int64(36963)
if v := strings.TrimSpace(os.Getenv("HANZO_CHAIN_ID")); v != "" {
if n, ok := new(big.Int).SetString(v, 10); ok {
chainID = n.Int64()
@@ -105,7 +122,7 @@ type walletTopupResp struct {
// walletTopup verifies a sent HUSD transfer on-chain and credits the caller's org.
// Mirrors POST app/billing/v1/topup/wallet/route.ts.
func (s *svc) walletTopup(c *zip.Ctx) error {
func walletTopup(s *cloud.Service[state], c *zip.Ctx) error {
cfg := loadTopupConfig()
// Greenfield gate: no HUSD contract / treasury ⇒ honest "not configured yet".
if !cfg.configured() {
@@ -343,7 +360,7 @@ func commerceDo(ctx context.Context, base, token, method, path string, q url.Val
if org != "" {
req.Header.Set("X-Org-Id", org)
}
resp, err := httpClient.Do(req)
resp, err := commerceHTTP.Do(req)
if err != nil {
return nil, 0, fmt.Errorf("commerce unreachable: %w", err)
}
@@ -1,4 +1,4 @@
package console
package account
import (
"encoding/json"
@@ -109,7 +109,7 @@ var alice = map[string]string{"X-User-Id": "alice", "X-Org-Id": "acme"}
func TestTopup_NotConfigured_501(t *testing.T) {
setTopupEnv(t, "", "", "http://rpc.invalid", "http://commerce.invalid")
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
if code != http.StatusNotImplemented {
t.Fatalf("HUSD unconfigured: want 501, got %d", code)
}
@@ -120,7 +120,7 @@ func TestTopup_RequiresValidatedPrincipal(t *testing.T) {
com := &fakeCommerce{}
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", nil, `{"txHash":"`+tTxHash+`"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", nil, `{"txHash":"`+tTxHash+`"}`)
if code != http.StatusForbidden {
t.Fatalf("no principal: want 403, got %d", code)
}
@@ -131,7 +131,7 @@ func TestTopup_BadTxHash_400(t *testing.T) {
com := &fakeCommerce{}
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice, `{"txHash":"0xnothex"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice, `{"txHash":"0xnothex"}`)
if code != http.StatusBadRequest {
t.Fatalf("bad txHash: want 400, got %d", code)
}
@@ -143,7 +143,7 @@ func TestTopup_HappyPath_VerifiesAndCredits(t *testing.T) {
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, body := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice,
code, body := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice,
`{"txHash":"`+tTxHash+`","fromAddress":"`+tSender+`"}`)
if code != http.StatusOK {
t.Fatalf("topup: want 200, got %d (%s)", code, body)
@@ -180,7 +180,7 @@ func TestTopup_IDOR_CreditsCallerNotBodyUserId(t *testing.T) {
// The body tries to credit "victim/root"; the handler MUST ignore it and credit
// the validated caller (acme/alice).
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice,
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice,
`{"txHash":"`+tTxHash+`","userId":"victim/root"}`)
if code != http.StatusOK {
t.Fatalf("topup: want 200, got %d", code)
@@ -195,7 +195,7 @@ func TestTopup_NotMined_400(t *testing.T) {
com := &fakeCommerce{}
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
if code != http.StatusBadRequest {
t.Fatalf("not mined: want 400, got %d", code)
}
@@ -209,7 +209,7 @@ func TestTopup_FailedTx_400(t *testing.T) {
com := &fakeCommerce{}
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
if code != http.StatusBadRequest {
t.Fatalf("failed tx: want 400, got %d", code)
}
@@ -221,7 +221,7 @@ func TestTopup_NoTransferToTreasury_400(t *testing.T) {
com := &fakeCommerce{}
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice, `{"txHash":"`+tTxHash+`"}`)
if code != http.StatusBadRequest {
t.Fatalf("non-treasury transfer: want 400, got %d", code)
}
@@ -233,7 +233,7 @@ func TestTopup_SenderMismatch_400(t *testing.T) {
setTopupEnv(t, tHusd, tTreasury, rpc.server(t).URL, com.server(t).URL)
app := mountBrand(t, "hanzo")
// Claims a different fromAddress than the on-chain sender → rejected.
code, _ := callH(t, app, http.MethodPost, "/v1/console/topup/wallet", alice,
code, _ := callH(t, app, http.MethodPost, "/v1/commerce/topup/wallet", alice,
`{"txHash":"`+tTxHash+`","fromAddress":"`+tOther+`"}`)
if code != http.StatusBadRequest {
t.Fatalf("sender mismatch: want 400, got %d", code)
+230 -334
View File
@@ -1,28 +1,22 @@
// Package admin mounts the god-mode admin surface (/v1/admin/*) the Hanzo
// Admin Console (admin.hanzo.ai, apps/operator) calls, per the api.ts contract.
// Package admin mounts the god-mode admin surface (/v1/admin/*) the Hanzo Admin Console
// (admin.hanzo.ai, apps/operator) calls, per the api.ts contract.
//
// It is an AGGREGATOR, not a new store: identity (orgs/users/roles/applications/
// audit/me) is read from IAM, the money panels (spend/tokens/credits) from
// commerce, and System Health from o11y — every one a real upstream, none fused
// into this binary (see subsystems.go). The facade fans out over HTTP exactly
// like o11ysvc / productsvc: it holds no business logic, it shapes the reads into
// the /v1 envelope { status, msg, data, data2 } the operator's transport
// decodes (get<T> reads data; getList<T> reads data + data2 total).
// It is an AGGREGATOR, not a new store: identity (orgs/users/roles/applications/audit/me)
// is read from IAM, the money panels (spend/tokens/credits) from commerce, and System
// Health from o11y — every one a real upstream. The facade fans out over HTTP, shaping
// the reads into the /v1 envelope { status, msg, data, data2 } the operator's transport
// decodes.
//
// SECURITY — every route is GLOBAL-ADMIN ONLY, fail-closed. The gate is the
// SAME predicate the rest of cloud uses: c.IsAdmin(), which after SanitizeIdentity
// (serve.go) is true ONLY for a JWT-validated principal whose org is the admin org
// (owner == AdminOrg — IAM's IsGlobalAdmin), matching the gateway's admin-guard.
// No principal → 403; a tenant-admin (owner != AdminOrg) → 403; a forged
// X-User-IsAdmin never survives ingress. admin adds no service credential to
// the IAM fan-out — it replays the caller's own cookie/bearer, so it can never
// read more than the caller already could, and IAM re-checks IsGlobalAdmin too.
// The subsystem is decomposed into a shared kernel (clients/admin/core) plus one package
// per handler domain (audit/customer/revenue/finance). This file is the Mount: it builds
// the ONE core.State from Deps, then registers each domain's routes alongside the
// top-level reads (me/overview/orgs/users/usage/roles/applications/products/compute/o11y/
// analytics/bases + the flags/waitlist control plane).
//
// Panels with no in-binary feed yet (the Usage & Costs timeseries + per-product
// breakdown live in insights/datastore; the product/workload registry + infra
// tiles live in platform.hanzo.ai / the operator inventory) return the real,
// honest empty state — never a fabricated number. The operator UI renders those
// as an em-dash / empty table by design.
// SECURITY — TWO tiers off ONE identity predicate, both fail-closed. PLATFORM routes are
// SuperAdmin ONLY (core.Guard). ORG-SCOPED routes (me/overview/orgs/users/usage/analytics/
// bases) are core.GuardScoped: a SuperAdmin sees EVERY tenant; any other validated admin
// caller is HARD-limited to their OWN org subtree by core.ResolveScope/ScopedOrgs.
package admin
import (
@@ -36,166 +30,141 @@ import (
"time"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/audit"
"github.com/hanzoai/cloud/clients/admin/audit"
"github.com/hanzoai/cloud/clients/admin/commerce"
"github.com/hanzoai/cloud/clients/admin/core"
"github.com/hanzoai/cloud/clients/admin/customer"
"github.com/hanzoai/cloud/clients/admin/digitalocean"
"github.com/hanzoai/cloud/clients/admin/finance"
"github.com/hanzoai/cloud/clients/admin/health"
"github.com/hanzoai/cloud/clients/admin/iam"
"github.com/hanzoai/cloud/clients/admin/revenue"
"github.com/hanzoai/cloud/clients/commerceinproc"
"github.com/hanzoai/cloud/clients/principal"
"github.com/zap-proto/zip"
)
// svc holds the resolved upstream clients + the admin org for this deployment.
type svc struct {
iam *iamClient
commerce *commerceClient
health *healthClient
do *doClient
adminOrg string
// auditStore is cloud's OWN tamper-evident audit store (nil when unconfigured,
// in which case /v1/admin/audit falls back to the IAM get-records proxy). Serve
// builds it and hands it over via deps.Audit. See audit.go.
auditStore *audit.Recorder
}
// Mount registers the /v1/admin/* surface on app. Every handler gates on
// c.IsAdmin() first (global-admin only), then aggregates real upstream data.
// Mount registers the /v1/admin/* surface on app. Every handler gates on c.IsAdmin()
// first (via core.Guard/GuardScoped), then aggregates real upstream data.
//
// The state is built from Deps fields NOT on cloud.Base (deps.Audit, deps.IAMIssuer), so
// it constructs the cloud.Service value directly (cloud.NewBase + &cloud.Service[core.State]{…})
// rather than via cloud.Mount.
func Mount(app *zip.App, deps cloud.Deps) error {
if app == nil {
return fmt.Errorf("admin.Mount: nil zip.App")
}
logger := deps.Logger
if logger == nil {
if deps.Logger == nil {
return fmt.Errorf("admin.Mount: nil deps.Logger")
}
logger = logger.New("subsystem", "admin")
s := &svc{
iam: newIAMClient(iamBase(deps)),
commerce: newCommerceClient(os.Getenv("CLOUD_COMMERCE_HTTP_URL"), os.Getenv("COMMERCE_SERVICE_TOKEN")),
health: newHealthClient(o11yHealthURL()),
do: newDOClient(doTokenFromEnv()),
adminOrg: adminOrgOf(deps),
auditStore: deps.Audit,
b := cloud.NewBase(deps, "admin")
s := &cloud.Service[core.State]{
Base: b,
State: core.State{
IAM: iam.New(iamBase(deps)),
Commerce: commerce.New(commerceinproc.BaseURL(os.Getenv("CLOUD_COMMERCE_HTTP_URL")), os.Getenv("COMMERCE_SERVICE_TOKEN")),
Health: health.New(o11yHealthURL()),
DO: digitalocean.New(doTokenFromEnv()),
AdminOrg: adminOrgOf(deps),
AuditStore: deps.Audit,
},
}
app.Get("/v1/admin/me", s.guard(s.me))
app.Get("/v1/admin/overview", s.guard(s.overview))
app.Get("/v1/admin/orgs", s.guard(s.orgs))
app.Get("/v1/admin/users", s.guard(s.users))
app.Get("/v1/admin/roles", s.guard(s.roles))
app.Get("/v1/admin/applications", s.guard(s.applications))
app.Get("/v1/admin/audit", s.guard(s.audit))
app.Get("/v1/admin/audit/verify", s.guard(s.auditVerify))
app.Get("/v1/admin/usage", s.guard(s.usage))
app.Get("/v1/admin/products", s.guard(s.products))
app.Get("/v1/admin/finance", s.guard(s.finance))
app.Get("/v1/admin/compute", s.guard(s.compute))
app.Post("/v1/admin/sync", s.guard(s.sync))
routes(app, s)
// Customer management — the operator cockpit. List (static) precedes the :org
// param route; the write actions are POST (distinct method), so none collide.
app.Get("/v1/admin/customers", s.guard(s.customers))
app.Get("/v1/admin/customers/:org", s.guard(s.customerDetail))
app.Post("/v1/admin/customers/:org/credit", s.guard(s.grantCredit))
app.Post("/v1/admin/customers/:org/suspend", s.guard(s.suspendCustomer))
app.Post("/v1/admin/customers/:org/reactivate", s.guard(s.reactivateCustomer))
// Fleet revenue aggregate + native SaaS analytics (retention/growth/churn).
app.Get("/v1/admin/revenue", s.guard(s.revenue))
app.Get("/v1/admin/analytics", s.guard(s.analytics))
logger.Info("admin surface mounted",
b.Log.Info("admin surface mounted",
"prefix", "/v1/admin",
"iam", s.iam.configured(),
"commerce", s.commerce.configured(),
"digitalocean", s.do.configured(),
"adminOrg", s.adminOrg,
"iam", s.State.IAM.Ready(),
"commerce", s.State.Commerce.Ready(),
"digitalocean", s.State.DO.Ready(),
"adminOrg", s.State.AdminOrg,
)
return nil
}
// guard wraps a handler with the global-admin gate. Fail-closed: any request
// whose validated identity is not a global admin (X-User-IsAdmin != "true",
// which SanitizeIdentity sets only for owner == AdminOrg) is refused 403 before
// the handler — no upstream is touched, no data leaks.
func (s *svc) guard(h func(*zip.Ctx) error) zip.Handler {
return func(c *zip.Ctx) error {
if !c.IsAdmin() {
return zip.ErrForbidden("global admin required")
}
return h(c)
}
}
// routes registers the /v1/admin/* surface on app, threading the ONE service value
// through the two-tier gate: org-scoped panels behind core.GuardScoped, the platform
// control plane behind core.Guard. Each carved-out domain (audit/customer/revenue/finance)
// owns its own route registration.
func routes(app *zip.App, s *cloud.Service[core.State]) {
// Org-scoped panels — GuardScoped. Cross-tenant reads are impossible for a non-super
// caller.
app.Get("/v1/admin/me", core.GuardScoped(s, me))
app.Get("/v1/admin/overview", core.GuardScoped(s, overview))
app.Get("/v1/admin/orgs", core.GuardScoped(s, orgs))
app.Get("/v1/admin/users", core.GuardScoped(s, users))
app.Get("/v1/admin/usage", core.GuardScoped(s, usage))
// Platform reads — SuperAdmin only (cross-tenant by nature).
app.Get("/v1/admin/roles", core.Guard(s, roles))
app.Get("/v1/admin/applications", core.Guard(s, applications))
app.Get("/v1/admin/products", core.Guard(s, products))
app.Get("/v1/admin/compute", core.Guard(s, compute))
app.Get("/v1/admin/o11y", core.Guard(s, o11y))
app.Post("/v1/admin/sync", core.Guard(s, syncNow))
// callerCreds captures the caller's replayed authorization context for the IAM
// fan-out: the raw Cookie header (session model) and the Authorization bearer.
func callerCreds(c *zip.Ctx) creds {
return creds{
cookie: string(c.Fiber().Request().Header.Peek("Cookie")),
auth: c.Header("Authorization"),
}
}
// Product analytics — org-scoped (SuperAdmin: all-orgs; org admin: their own org).
app.Get("/v1/admin/analytics", core.GuardScoped(s, analytics))
// Bases — the tenant Base-instance panel, org-scoped (bases.go).
app.Get("/v1/admin/bases", core.GuardScoped(s, bases))
// ── /v1 envelope writers ────────────────────────────────────────────────
// ── Platform control plane — SuperAdmin ONLY (launch/release/flags + access). ──
app.Get("/v1/admin/flags", core.Guard(s, flagsBoard))
app.Put("/v1/admin/flags/:key", core.Guard(s, setFlag))
// Launch-control services board — the waitlist-mode lens on the flag engine (twin
// of /v1/admin/flags), folded in from the former featuregate control plane.
app.Get("/v1/admin/services", core.Guard(s, services))
app.Post("/v1/admin/services", core.Guard(s, upsertService))
app.Post("/v1/admin/services/:service/mode", core.Guard(s, setServiceMode))
app.Get("/v1/admin/waitlist", core.Guard(s, waitlist))
app.Post("/v1/admin/waitlist/boost", core.Guard(s, waitlistBoost))
// ok writes a { status:"ok", data } envelope (the get<T> shape).
func ok(c *zip.Ctx, data any) error {
return c.JSON(200, map[string]any{"status": "ok", "msg": "", "data": data})
}
// okList writes a { status:"ok", data:[...], data2:total } envelope (getList<T>).
func okList(c *zip.Ctx, rows any, total int) error {
return c.JSON(200, map[string]any{"status": "ok", "msg": "", "data": rows, "data2": total})
}
// okRaw writes a { status:"ok", data:<raw>, data2:total } envelope, forwarding an
// IAM payload verbatim so its exact wire shape (Role, Application, Record, User)
// reaches the operator field-for-field.
func okRaw(c *zip.Ctx, rows json.RawMessage, total int) error {
if len(rows) == 0 {
rows = json.RawMessage("[]")
}
return c.JSON(200, map[string]any{"status": "ok", "msg": "", "data": rows, "data2": total})
}
// fail writes a { status:"error", msg } envelope. The operator's transport maps
// a non-ok envelope to a surfaced error (never a fabricated value).
func fail(c *zip.Ctx, msg string) error {
return c.JSON(200, map[string]any{"status": "error", "msg": msg, "data": nil})
// ── Carved-out domains own their routes (audit/customer/revenue/finance). ──
audit.Routes(app, s)
customer.Routes(app, s)
revenue.Routes(app, s)
finance.Routes(app, s)
}
// ── /v1/admin/me — operator identity (AdminMe) ───────────────────────────────
// me answers with the validated operator identity. The gate already proved this
// is a global admin, so the fields come from the sanitized identity headers —
// authoritative and never client-forgeable.
func (s *svc) me(c *zip.Ctx) error {
owner := s.adminOrg
if o := strings.TrimSpace(c.Org()); o != "" {
owner = o
// me answers with the validated operator identity. The gate already proved this is an
// admin, so the fields come from the sanitized identity headers — authoritative and never
// client-forgeable.
func me(s *cloud.Service[core.State], c *zip.Ctx) error {
sc := core.ResolveScope(s, c)
owner, _ := principal.Org(c)
if owner == "" && sc.Super {
owner = s.State.AdminOrg
}
name := strings.TrimSpace(c.User())
return ok(c, adminMe{
Owner: owner,
Name: name,
Email: strings.TrimSpace(c.UserEmail()),
DisplayName: name,
IsGlobalAdmin: true,
return core.OK(c, adminMe{
Owner: owner,
Name: name,
Email: strings.TrimSpace(c.UserEmail()),
DisplayName: name,
IsSuperAdmin: sc.Super,
})
}
// ── /v1/admin/orgs — tenant directory (OrgRow[]) ─────────────────────────────
func (s *svc) orgs(c *zip.Ctx) error {
func orgs(s *cloud.Service[core.State], c *zip.Ctx) error {
ctx := c.Context()
cr := callerCreds(c)
orgs, err := s.listOrgs(ctx, cr)
cr := core.CallerCreds(c)
orgs, err := core.ScopedOrgs(s, ctx, c, cr)
if err != nil {
return fail(c, err.Error())
return core.Fail(c, err.Error())
}
rows := make([]orgRow, 0, len(orgs))
for _, o := range orgs {
users := s.orgUserCount(ctx, cr, o.Name)
spend, credits := s.orgMoney(ctx, o.Name)
users := orgUserCount(s, ctx, cr, o.Name)
// orgs is a per-ROW panel (OrgRow[] via OKList; it carries NO sources[] channel):
// a failed read degrades THAT org's row to an honest zero, never a fleet total that
// falsely reads healthy. The aggregate-freshness signal lives on /overview.
spend, credits, _ := core.OrgMoney(s, ctx, o.Name)
rows = append(rows, orgRow{
Org: o.Name,
Display: display(o.DisplayName, o.Name),
Display: core.Display(o.DisplayName, o.Name),
Users: users,
Products: 0, // workload registry feed pending (platform apps table)
SpendCents: spend,
@@ -205,16 +174,23 @@ func (s *svc) orgs(c *zip.Ctx) error {
})
}
sort.Slice(rows, func(i, j int) bool { return rows[i].Org < rows[j].Org })
return okList(c, rows, len(rows))
return core.OKList(c, rows, len(rows))
}
// ── /v1/admin/users — cross-org directory (OperatorUser[]) ───────────────────
func (s *svc) users(c *zip.Ctx) error {
func users(s *cloud.Service[core.State], c *zip.Ctx) error {
ctx := c.Context()
cr := callerCreds(c)
cr := core.CallerCreds(c)
sc := core.ResolveScope(s, c)
q := url.Values{}
if owner := strings.TrimSpace(c.Query("org")); owner != "" {
if !sc.Super {
// A scoped caller lists ONLY their own org's users — the client ?org= is ignored,
// the owner hard-pinned to the sanitized org subtree.
if len(sc.Orgs) > 0 {
q.Set("owner", sc.Orgs[0])
}
} else if owner := strings.TrimSpace(c.Query("org")); owner != "" {
q.Set("owner", owner)
}
if p := strings.TrimSpace(c.Query("p")); p != "" {
@@ -228,56 +204,56 @@ func (s *svc) users(c *zip.Ctx) error {
q.Set("field", "name")
q.Set("value", term)
}
res, err := s.iam.getList(ctx, cr, "/v1/iam/get-users", q)
res, err := s.State.IAM.Users(ctx, cr, q)
if err != nil {
return fail(c, err.Error())
return core.Fail(c, err.Error())
}
var raw []iamUser
if len(res.rows) > 0 {
if err := json.Unmarshal(res.rows, &raw); err != nil {
return fail(c, "users decode: "+err.Error())
var raw []iam.User
if len(res.Rows) > 0 {
if err := json.Unmarshal(res.Rows, &raw); err != nil {
return core.Fail(c, "users decode: "+err.Error())
}
}
rows := make([]operatorUser, 0, len(raw))
for _, u := range raw {
rows = append(rows, operatorUser{
Owner: u.Owner,
Name: u.Name,
Email: u.Email,
DisplayName: u.DisplayName,
IsAdmin: u.IsAdmin,
IsGlobalAdmin: u.Owner == s.adminOrg,
Tag: u.Tag,
Created: u.CreatedTime,
LastSignin: u.LastSigninTime,
Forbidden: u.IsForbidden,
Owner: u.Owner,
Name: u.Name,
Email: u.Email,
DisplayName: u.DisplayName,
IsAdmin: u.IsAdmin,
IsSuperAdmin: u.Owner == s.State.AdminOrg,
Tag: u.Tag,
Created: u.CreatedTime,
LastSignin: u.LastSigninTime,
Forbidden: u.IsForbidden,
})
}
total := res.total
total := res.Total
if total < len(rows) {
total = len(rows)
}
return okList(c, rows, total)
return core.OKList(c, rows, total)
}
// ── /v1/admin/roles and /applications — verbatim IAM passthrough ─────────────
func (s *svc) roles(c *zip.Ctx) error {
return s.iamPassthrough(c, "/v1/iam/get-roles")
func roles(s *cloud.Service[core.State], c *zip.Ctx) error {
return iamPassthrough(s, c, "/v1/iam/get-roles")
}
func (s *svc) applications(c *zip.Ctx) error {
return s.iamPassthrough(c, "/v1/iam/get-applications")
func applications(s *cloud.Service[core.State], c *zip.Ctx) error {
return iamPassthrough(s, c, "/v1/iam/get-applications")
}
// iamPassthrough forwards a paginated IAM read verbatim (the operator decodes
// Role / Application as the raw IAM wire shape). `owner` defaults to the admin
// org, which owns the platform applications.
func (s *svc) iamPassthrough(c *zip.Ctx, path string) error {
// iamPassthrough forwards a paginated IAM read verbatim (the operator decodes Role /
// Application as the raw IAM wire shape). `owner` defaults to the admin org, which owns
// the platform applications.
func iamPassthrough(s *cloud.Service[core.State], c *zip.Ctx, path string) error {
q := url.Values{}
owner := strings.TrimSpace(c.Query("owner"))
if owner == "" {
owner = s.adminOrg
owner = s.State.AdminOrg
}
q.Set("owner", owner)
if p := strings.TrimSpace(c.Query("p")); p != "" {
@@ -286,66 +262,52 @@ func (s *svc) iamPassthrough(c *zip.Ctx, path string) error {
if ps := strings.TrimSpace(c.Query("pageSize")); ps != "" {
q.Set("pageSize", ps)
}
res, err := s.iam.getList(c.Context(), callerCreds(c), path, q)
res, err := s.State.IAM.List(c.Context(), core.CallerCreds(c), path, q)
if err != nil {
return fail(c, err.Error())
return core.Fail(c, err.Error())
}
return okRaw(c, res.rows, res.total)
}
// ── /v1/admin/audit — records directory (AuditRow[]) ─────────────────────────
//
// The handler lives in audit.go (it reads cloud's OWN tamper-evident store).
// iamAuditQuery builds the IAM get-records query for the federated fallback
// auditFromIAM uses when no local store is configured.
func iamAuditQuery(c *zip.Ctx) url.Values {
q := url.Values{}
if org := strings.TrimSpace(c.Query("org")); org != "" {
q.Set("organizationName", org)
}
q.Set("p", "1")
ps := strings.TrimSpace(c.Query("pageSize"))
if ps == "" {
ps = "100"
}
q.Set("pageSize", ps)
q.Set("sortField", "createdTime")
q.Set("sortOrder", "descend")
return q
return core.OKRaw(c, res.Rows, res.Total)
}
// ── /v1/admin/usage — fleet usage roll-up (UsageData) ────────────────────────
// usage returns the real fleet money totals from commerce. The daily series and
// the per-product breakdown are NOT derivable from the commerce billing API
// (they live in insights/datastore, owned separately); admin returns the
// honest empty series/byProduct rather than fabricating a trend — the operator
// renders that as an empty chart, never a fake line.
func (s *svc) usage(c *zip.Ctx) error {
// usage returns the real fleet money totals from commerce. The daily series and the
// per-product breakdown are NOT derivable from the commerce billing API (they live in
// insights/datastore); admin returns the honest empty series/byProduct rather than
// fabricating a trend.
func usage(s *cloud.Service[core.State], c *zip.Ctx) error {
ctx := c.Context()
cr := callerCreds(c)
cr := core.CallerCreds(c)
sc := core.ResolveScope(s, c)
org := strings.TrimSpace(c.Query("org"))
if !sc.Super {
// A scoped caller reads ONLY their own org's usage — the client ?org= is ignored,
// the org hard-pinned to the sanitized subtree.
org = ""
if len(sc.Orgs) > 0 {
org = sc.Orgs[0]
}
}
var spend int64
if org != "" {
r, err := s.commerce.usageRollup(ctx, org, orgSubject(org))
if err == nil {
spend = r.ConsumedCents
switch {
case org != "":
if sp, err := s.State.Commerce.Spend(ctx, org); err == nil {
spend = int64(sp.Consumed)
}
} else {
case sc.Super:
// Fleet: sum month-to-date consumption across every org.
orgs, err := s.listOrgs(ctx, cr)
orgs, err := core.ListOrgs(s, ctx, cr)
if err == nil {
for _, o := range orgs {
if r, e := s.commerce.usageRollup(ctx, o.Name, orgSubject(o.Name)); e == nil {
spend += r.ConsumedCents
if sp, e := s.State.Commerce.Spend(ctx, o.Name); e == nil {
spend += int64(sp.Consumed)
}
}
}
}
return ok(c, usageData{
return core.OK(c, usageData{
Totals: usageTotals{SpendCents: spend, Tokens: 0, Requests: 0},
Series: []usagePoint{},
ByProduct: []usageByProduct{},
@@ -354,64 +316,67 @@ func (s *svc) usage(c *zip.Ctx) error {
// ── /v1/admin/products — workload registry (ProductRow[]) ────────────────────
// products is the workload/drift registry (declared vs running tag, health).
// That inventory is the platform.hanzo.ai apps table / operator reconcile state,
// NOT an in-binary source. admin exposes the gated endpoint and returns the
// real empty registry until that feed is wired — it never fabricates workload
// rows. The operator renders an empty table, not fake products.
func (s *svc) products(c *zip.Ctx) error {
return okList(c, []productRow{}, 0)
// products is the workload/drift registry. That inventory is the platform.hanzo.ai apps
// table / operator reconcile state, NOT an in-binary source. admin exposes the gated
// endpoint and returns the real empty registry until that feed is wired.
func products(s *cloud.Service[core.State], c *zip.Ctx) error {
return core.OKList(c, []productRow{}, 0)
}
// ── /v1/admin/overview — Platform Overview tiles (OverviewData) ───────────────
func (s *svc) overview(c *zip.Ctx) error {
func overview(s *cloud.Service[core.State], c *zip.Ctx) error {
ctx := c.Context()
cr := callerCreds(c)
cr := core.CallerCreds(c)
now := time.Now().UTC().Format(time.RFC3339)
var sources []sourceStatus
var sources []core.SourceStatus
orgCount, userCount, spend, credits := 0, 0, int64(0), int64(0)
orgs, orgErr := s.listOrgs(ctx, cr)
sources = append(sources, srcOf("iam", orgErr, len(orgs), now))
orgs, orgErr := core.ScopedOrgs(s, ctx, c, cr)
sources = append(sources, core.SrcOf("iam", orgErr, len(orgs), now))
commercePartial := false
if orgErr == nil {
orgCount = len(orgs)
for _, o := range orgs {
userCount += s.orgUserCount(ctx, cr, o.Name)
sp, cr2 := s.orgMoney(ctx, o.Name)
userCount += orgUserCount(s, ctx, cr, o.Name)
sp, cr2, ok := core.OrgMoney(s, ctx, o.Name)
spend += sp
credits += cr2
if !ok {
// This org's money did not read — the fleet spend/credits totals are now
// an UNDERCOUNT, so the commerce source must report degraded, not healthy.
commercePartial = true
}
}
}
// Commerce freshness: probe one org's rollup so the tile reflects a real read.
commerceRows := 0
// Commerce freshness derives from the SAME per-org reads the totals fold — NOT a
// single probe org (which could read healthy while commerce was down for every other
// org, masking an undercount). Not-configured when unwired; degraded/partial (the ONE
// core.ErrPartialRevenue sentinel revenue/finance use) when ANY per-org read failed.
var commerceErr error
if s.commerce.configured() {
probe := s.adminOrg
if len(orgs) > 0 {
probe = orgs[0].Name
}
if _, err := s.commerce.usageRollup(ctx, probe, orgSubject(probe)); err != nil {
commerceErr = err
} else {
commerceRows = 1
}
} else {
commerceRows := 0
switch {
case !s.State.Commerce.Ready():
commerceErr = fmt.Errorf("commerce endpoint not configured")
case commercePartial:
commerceErr = core.ErrPartialRevenue
commerceRows = orgCount
default:
commerceRows = orgCount
}
sources = append(sources, srcOf("commerce", commerceErr, commerceRows, now))
sources = append(sources, core.SrcOf("commerce", commerceErr, commerceRows, now))
// o11y System Health.
o11yRows := 0
oOK, oErr := s.health.ok(ctx)
oOK, oErr := s.State.Health.Up(ctx)
if oOK {
o11yRows = 1
}
sources = append(sources, srcOf("o11y", oErr, o11yRows, now))
sources = append(sources, core.SrcOf("o11y", oErr, o11yRows, now))
return ok(c, overviewData{
return core.OK(c, overviewData{
Orgs: orgCount,
Users: userCount,
Products: 0, // workload registry feed pending (platform apps table)
@@ -427,95 +392,33 @@ func (s *svc) overview(c *zip.Ctx) error {
// ── /v1/admin/sync — refresh trigger ─────────────────────────────────────────
// sync answers the operator's "Sync now" button. admin aggregates LIVE on
// every read (there is no cached fleet snapshot in-binary), so there is no batch
// job to kick — the button simply re-reads. We acknowledge honestly with
// { started: true } so the UI re-fetches the (freshly-computed) overview.
func (s *svc) sync(c *zip.Ctx) error {
return ok(c, map[string]bool{"started": true})
// syncNow answers the operator's "Sync now" button. admin aggregates LIVE on every read,
// so there is no batch job to kick — the button simply re-reads. We acknowledge honestly
// with { started: true }.
func syncNow(s *cloud.Service[core.State], c *zip.Ctx) error {
return core.OK(c, map[string]bool{"started": true})
}
// ── aggregation helpers ──────────────────────────────────────────────────────
// listOrgs reads the org directory (owner = admin org) as the typed shape the
// overview/orgs/usage aggregators fold over.
func (s *svc) listOrgs(ctx context.Context, cr creds) ([]iamOrg, error) {
q := url.Values{}
q.Set("owner", s.adminOrg)
res, err := s.iam.getList(ctx, cr, "/v1/iam/get-organizations", q)
if err != nil {
return nil, err
}
var orgs []iamOrg
if len(res.rows) > 0 {
if err := json.Unmarshal(res.rows, &orgs); err != nil {
return nil, fmt.Errorf("orgs decode: %w", err)
}
}
return orgs, nil
}
// orgUserCount returns the member count for one org from the IAM list total
// (data2). Best-effort: an error yields 0 rather than failing the whole row.
func (s *svc) orgUserCount(ctx context.Context, cr creds, org string) int {
// orgUserCount returns the member count for one org from the IAM list total (data2).
// Best-effort: an error yields 0 rather than failing the whole row.
func orgUserCount(s *cloud.Service[core.State], ctx context.Context, cr iam.Creds, org string) int {
q := url.Values{}
q.Set("owner", org)
q.Set("p", "1")
q.Set("pageSize", "1")
res, err := s.iam.getList(ctx, cr, "/v1/iam/get-users", q)
res, err := s.State.IAM.Users(ctx, cr, q)
if err != nil {
return 0
}
return res.total
}
// orgMoney returns (spendCents, creditsCents) for one org from commerce.
// Best-effort: unreachable/unconfigured commerce yields zeros.
func (s *svc) orgMoney(ctx context.Context, org string) (int64, int64) {
subj := orgSubject(org)
var spend, credits int64
if r, err := s.commerce.usageRollup(ctx, org, subj); err == nil {
spend = r.ConsumedCents
}
if c, err := s.commerce.creditsCents(ctx, org, subj); err == nil {
credits = c
}
return spend, credits
}
// orgSubject is the billing subject commerce keys an org's wallet on. Commerce's
// per-org billing store (the 2026-07 durability rework, commerce >=1.46.8)
// namespaces by the TRUSTED X-Org-Id header (set by commerceClient.get from this
// same org) and keys the org wallet under the BARE org slug as the `user` subject —
// NOT "org/user". The prior "org/org" subject (with the wrong X-IAM-Org-Id header)
// resolved to an EMPTY wallet, so every per-org money panel read $0 while real
// balances existed (lux $10,000, maxpower $20,498). Verified live against commerce
// /v1/billing/{balance,usage-rollup}: user=<org> + X-Org-Id=<org> returns the real
// wallet; user="org/org" or a missing/other org header returns $0.
func orgSubject(org string) string { return org }
// srcOf builds a SourceStatus freshness row for the overview.
func srcOf(name string, err error, rows int, at string) sourceStatus {
s := sourceStatus{Name: name, OK: err == nil, Rows: rows, At: at}
if err != nil {
s.Error = err.Error()
}
return s
}
func display(displayName, fallback string) string {
if strings.TrimSpace(displayName) != "" {
return displayName
}
return fallback
return res.Total
}
// ── config resolution ────────────────────────────────────────────────────────
// iamBase resolves the IAM management HTTP base. CLOUD_IAM_HTTP_URL wins (the
// in-cluster Service, e.g. http://iam.hanzo.svc.cluster.local:8000); otherwise
// the public issuer (deps.IAMIssuer, e.g. https://hanzo.id) which also serves
// /v1/iam/*. Empty only when neither is set (endpoint reports not-configured).
// iamBase resolves the IAM management HTTP base. CLOUD_IAM_HTTP_URL wins (the in-cluster
// Service); otherwise the public issuer (deps.IAMIssuer) which also serves /v1/iam/*.
func iamBase(deps cloud.Deps) string {
if v := strings.TrimSpace(os.Getenv("CLOUD_IAM_HTTP_URL")); v != "" {
return v
@@ -532,8 +435,8 @@ func o11yHealthURL() string {
return "http://o11y.hanzo.svc.cluster.local:80/v1/o11y/health"
}
// adminOrgOf resolves the admin org slug (IAM's IsGlobalAdmin owner). IAM_ADMIN_ORG
// mirrors config.go's default; "admin" is the fleet-wide default.
// adminOrgOf resolves the admin org slug (IAM's IsSuperAdmin owner). IAM_ADMIN_ORG mirrors
// config.go's default; "admin" is the fleet-wide default.
func adminOrgOf(_ cloud.Deps) string {
if v := strings.TrimSpace(os.Getenv("IAM_ADMIN_ORG")); v != "" {
return v
@@ -541,15 +444,8 @@ func adminOrgOf(_ cloud.Deps) string {
return "admin"
}
func init() {
// Order 146: after productsvc (145); the admin surface has no ordering
// dependency (it fans out over HTTP), placed adjacent to the other console
// read facades.
cloud.Register("admin", 146, func(app any, deps cloud.Deps) error {
a, ok := app.(*zip.App)
if !ok {
return fmt.Errorf("admin.Mount: app is %T, want *zip.App", app)
}
return Mount(a, deps)
})
// doTokenFromEnv reads the DigitalOcean token from the environment. Sourced from a
// KMSSecret on the cloud deployment (DO_API_TOKEN) — never hard-coded.
func doTokenFromEnv() string {
return strings.TrimSpace(os.Getenv("DO_API_TOKEN"))
}
+138 -54
View File
@@ -10,10 +10,15 @@ import (
"testing"
"time"
fiber "github.com/gofiber/fiber/v3"
"github.com/hanzoai/cloud"
"github.com/zap-proto/zip"
"github.com/hanzoai/cloud/clients/admin/commerce"
"github.com/hanzoai/cloud/clients/admin/core"
"github.com/hanzoai/cloud/clients/admin/digitalocean"
"github.com/hanzoai/cloud/clients/admin/health"
"github.com/hanzoai/cloud/clients/admin/iam"
luxlog "github.com/luxfi/log"
fiber "github.com/zap-proto/fiber/v3"
"github.com/zap-proto/zip"
)
// mount builds a zip app with admin mounted against the given upstream bases,
@@ -23,40 +28,26 @@ func mount(t *testing.T, iamURL, commerceURL, healthURL string) func(method, pat
return do
}
// mountSvc is mount but also returns the underlying svc (so finance tests can swap
// mountSvc is mount but also returns the underlying cloud.Service[state] (so finance tests can swap
// in a fake DigitalOcean client, and the cockpit tests can attach an audit store)
// AND the raw fiber app (so tests that need a request BODY can drive it directly —
// the returned `do` sends a nil body). The handlers read s.* live at request time,
// so an override before issuing a request takes effect.
func mountSvc(t *testing.T, iamURL, commerceURL, healthURL string) (func(method, path string, hdr map[string]string) (*http.Response, []byte), *svc, *fiber.App) {
func mountSvc(t *testing.T, iamURL, commerceURL, healthURL string) (func(method, path string, hdr map[string]string) (*http.Response, []byte), *cloud.Service[core.State], *fiber.App) {
t.Helper()
app := zip.New(zip.Config{Logger: luxlog.New("test")})
s := &svc{
iam: newIAMClient(iamURL),
commerce: newCommerceClient(commerceURL, "test-token"),
health: newHealthClient(healthURL),
do: newDOClient(""), // no token → honest not-configured unless a test overrides s.do
adminOrg: "admin",
}
app.Get("/v1/admin/me", s.guard(s.me))
app.Get("/v1/admin/overview", s.guard(s.overview))
app.Get("/v1/admin/orgs", s.guard(s.orgs))
app.Get("/v1/admin/users", s.guard(s.users))
app.Get("/v1/admin/roles", s.guard(s.roles))
app.Get("/v1/admin/applications", s.guard(s.applications))
app.Get("/v1/admin/audit", s.guard(s.audit))
app.Get("/v1/admin/audit/verify", s.guard(s.auditVerify))
app.Get("/v1/admin/usage", s.guard(s.usage))
app.Get("/v1/admin/products", s.guard(s.products))
app.Get("/v1/admin/finance", s.guard(s.finance))
app.Post("/v1/admin/sync", s.guard(s.sync))
app.Get("/v1/admin/customers", s.guard(s.customers))
app.Get("/v1/admin/customers/:org", s.guard(s.customerDetail))
app.Post("/v1/admin/customers/:org/credit", s.guard(s.grantCredit))
app.Post("/v1/admin/customers/:org/suspend", s.guard(s.suspendCustomer))
app.Post("/v1/admin/customers/:org/reactivate", s.guard(s.reactivateCustomer))
app.Get("/v1/admin/revenue", s.guard(s.revenue))
app.Get("/v1/admin/analytics", s.guard(s.analytics))
s := &cloud.Service[core.State]{State: core.State{
IAM: iam.New(iamURL),
Commerce: commerce.New(commerceURL, "test-token"),
Health: health.New(healthURL),
DO: digitalocean.New(""), // no token → honest not-configured unless a test overrides s.State.DO
AdminOrg: "admin",
}}
// Mirror the REAL Mount EXACTLY by registering the same routes() the subsystem uses
// (org-scoped panels behind GuardScoped, the platform control plane behind Guard,
// each domain owning its own routes), so the harness stays authoritative for the
// two-tier gate + every surface.
routes(app, s)
fa := app.Fiber()
return func(method, path string, hdr map[string]string) (*http.Response, []byte) {
@@ -74,18 +65,28 @@ func mountSvc(t *testing.T, iamURL, commerceURL, healthURL string) (func(method,
}, s, fa
}
// adminRoutes is every mounted /v1/admin route + its method — the full god-mode
// surface the gate must fail-close on for a non-global-admin.
var adminRoutes = []struct{ method, path string }{
type adminRoute struct{ method, path string }
// scopedAdminRoutes are the ORG-SCOPED panels (guardScoped): a SuperAdmin OR a validated
// org admin is admitted, and the handler scopes the data. A caller with NO validated
// principal (anonymous, or an org header but no X-User-Id) is still refused.
var scopedAdminRoutes = []adminRoute{
{"GET", "/v1/admin/me"},
{"GET", "/v1/admin/overview"},
{"GET", "/v1/admin/orgs"},
{"GET", "/v1/admin/users"},
{"GET", "/v1/admin/usage"},
{"GET", "/v1/admin/analytics"},
{"GET", "/v1/admin/bases"},
}
// platformAdminRoutes are SuperAdmin ONLY (s.guard) — the cross-tenant platform reads +
// the launch/release/flags/access control plane. A non-super caller is ALWAYS 403.
var platformAdminRoutes = []adminRoute{
{"GET", "/v1/admin/roles"},
{"GET", "/v1/admin/applications"},
{"GET", "/v1/admin/audit"},
{"GET", "/v1/admin/audit/verify"},
{"GET", "/v1/admin/usage"},
{"GET", "/v1/admin/products"},
{"GET", "/v1/admin/finance"},
{"POST", "/v1/admin/sync"},
@@ -95,11 +96,17 @@ var adminRoutes = []struct{ method, path string }{
{"POST", "/v1/admin/customers/acme/suspend"},
{"POST", "/v1/admin/customers/acme/reactivate"},
{"GET", "/v1/admin/revenue"},
{"GET", "/v1/admin/analytics"},
{"GET", "/v1/admin/flags"},
{"GET", "/v1/admin/waitlist"},
{"POST", "/v1/admin/waitlist/boost"},
}
// adminRoutes is the full surface (both tiers) — the fail-closed gate test denies an
// unauthenticated caller on EVERY one.
var adminRoutes = append(append([]adminRoute{}, scopedAdminRoutes...), platformAdminRoutes...)
// TestGate_DeniesEveryRoute proves the non-negotiable: EVERY /v1/admin/* route is
// global-admin only, fail-closed. An anonymous caller and a tenant-admin (whose
// SuperAdmin only, fail-closed. An anonymous caller and a tenant-admin (whose
// identity carries an org but NOT the sanitizer-minted X-User-IsAdmin) are BOTH
// denied 403 on every route — no upstream is even reached. admin mirrors the
// gateway's admin-guard: SanitizeIdentity sets X-User-IsAdmin only for a
@@ -109,15 +116,18 @@ func TestGate_DeniesEveryRoute(t *testing.T) {
// Upstreams point nowhere reachable; the gate must reject BEFORE any call.
do := mount(t, "http://127.0.0.1:0", "http://127.0.0.1:0", "http://127.0.0.1:0")
cases := []struct {
// NO validated principal ⇒ denied on EVERY route (platform + scoped). guardScoped
// requires a sanitized X-User-Id, which an anonymous caller lacks — and a client
// that merely forges X-Org-Id (the documented Phase-1 residual) still has no
// X-User-Id, so it is refused here and can never reach a scoped read.
noPrincipal := []struct {
name string
hdr map[string]string
}{
{"anonymous", nil},
{"tenant-admin (owner set, not global-admin)", map[string]string{"X-Org-Id": "acme"}},
{"tenant-user with email but no admin", map[string]string{"X-Org-Id": "acme", "X-User-Id": "acme/bob", "X-User-Email": "bob@acme.test"}},
{"forged X-Org-Id, no validated user", map[string]string{"X-Org-Id": "victim"}},
}
for _, tc := range cases {
for _, tc := range noPrincipal {
for _, r := range adminRoutes {
resp, body := do(r.method, r.path, tc.hdr)
if resp.StatusCode != http.StatusForbidden {
@@ -125,17 +135,30 @@ func TestGate_DeniesEveryRoute(t *testing.T) {
}
}
}
// A VALIDATED org admin (X-User-Id + pinned X-Org-Id + the sanitizer-minted
// X-User-IsOrgAdmin, but NO GLOBAL X-User-IsAdmin) is denied on every PLATFORM route
// (super-only). The org-scoped routes admit them but hard-scope the data — proven in
// scope_test.go. (A validated NON-admin member, lacking the org-admin bit, is refused
// on the scoped panels too — TestScope_MemberWithoutOrgAdminDenied.)
orgAdmin := map[string]string{"X-Org-Id": "acme", "X-User-Id": "acme/bob", "X-User-Email": "bob@acme.test", "X-User-IsOrgAdmin": "true"}
for _, r := range platformAdminRoutes {
resp, body := do(r.method, r.path, orgAdmin)
if resp.StatusCode != http.StatusForbidden {
t.Errorf("%s %s [org-admin on platform route]: got %d, want 403 (body=%s)", r.method, r.path, resp.StatusCode, body)
}
}
}
// TestGate_AllowsGlobalAdmin proves the flip side: a validated global admin
// TestGate_AllowsSuperAdmin proves the flip side: a validated SuperAdmin
// (X-User-IsAdmin=true, minted only for owner==AdminOrg) is admitted — the gate
// is not vacuously closed. Reaches /v1/admin/me, which needs no upstream.
func TestGate_AllowsGlobalAdmin(t *testing.T) {
func TestGate_AllowsSuperAdmin(t *testing.T) {
do := mount(t, "http://127.0.0.1:0", "http://127.0.0.1:0", "http://127.0.0.1:0")
admin := map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin", "X-User-Id": "admin/z", "X-User-Email": "z@hanzo.ai"}
resp, body := do("GET", "/v1/admin/me", admin)
if resp.StatusCode != http.StatusOK {
t.Fatalf("global-admin GET /v1/admin/me: got %d, want 200 (body=%s)", resp.StatusCode, body)
t.Fatalf("SuperAdmin GET /v1/admin/me: got %d, want 200 (body=%s)", resp.StatusCode, body)
}
var env struct {
Status string `json:"status"`
@@ -147,9 +170,14 @@ func TestGate_AllowsGlobalAdmin(t *testing.T) {
if env.Status != "ok" {
t.Fatalf("me status = %q, want ok", env.Status)
}
if env.Data.Owner != "admin" || env.Data.Email != "z@hanzo.ai" || !env.Data.IsGlobalAdmin {
if env.Data.Owner != "admin" || env.Data.Email != "z@hanzo.ai" || !env.Data.IsSuperAdmin {
t.Errorf("me identity wrong: %+v", env.Data)
}
// SuperAdmin canonicalization: the isSuperAdmin key MUST be present and true
// for a platform SuperAdmin.
if !env.Data.IsSuperAdmin {
t.Errorf("me: isSuperAdmin must be true for a SuperAdmin: %+v", env.Data)
}
}
// fakeIAM stands in for the IAM management surface. It records whether the
@@ -246,11 +274,9 @@ func newFakeCommerce() *fakeCommerce {
// revenue bug (commerce.go had X-IAM-Org-Id; admin.go orgSubject had "org/org", so
// every real balance read $0). /v1/admin/orgs must surface acme's real $50.00.
func TestCommerce_ReconcilesWithXOrgIdBareSlug(t *testing.T) {
// orgSubject MUST be the bare slug (not "org/org").
if got := orgSubject("acme"); got != "acme" {
t.Fatalf("orgSubject(\"acme\") = %q, want \"acme\" (bare slug; \"acme/acme\" reads an empty commerce wallet)", got)
}
// The billing subject is the bare org slug for BOTH the X-Org-Id header and the
// `user` param — commerce.Client bakes that in (one subject, no "org/org"). This
// test proves it end to end: /v1/admin/orgs must surface acme's real $50.00.
iam := newFakeIAM()
defer iam.server.Close()
commerce := newFakeCommerce()
@@ -338,7 +364,7 @@ func TestOrgs_RealAggregation(t *testing.T) {
}
// TestUsers_MapsIAMToOperatorUser verifies the cross-org directory mapping,
// including the derived isGlobalAdmin (owner == adminOrg) and the data2 total.
// including the derived isSuperAdmin (owner == adminOrg) and the data2 total.
func TestUsers_MapsIAMToOperatorUser(t *testing.T) {
iam := newFakeIAM()
defer iam.server.Close()
@@ -363,9 +389,9 @@ func TestUsers_MapsIAMToOperatorUser(t *testing.T) {
if u.Name != "alice" || u.Email != "alice@hanzo.ai" || !u.IsAdmin || u.LastSignin == "" {
t.Errorf("user mapping wrong: %+v", u)
}
// owner "hanzo" != adminOrg "admin" → not a global admin.
if u.IsGlobalAdmin {
t.Errorf("user owner=hanzo must not be flagged global admin")
// owner "hanzo" != adminOrg "admin" → not a SuperAdmin.
if u.IsSuperAdmin {
t.Errorf("user owner=hanzo must not be flagged SuperAdmin")
}
}
@@ -466,7 +492,7 @@ func TestOverview_RealTilesAndSources(t *testing.T) {
t.Error("overview lastSync must be set")
}
// Source freshness: iam ok, commerce ok, o11y not-ok (unconfigured).
src := map[string]sourceStatus{}
src := map[string]core.SourceStatus{}
for _, s := range d.Sources {
src[s.Name] = s
}
@@ -481,6 +507,64 @@ func TestOverview_RealTilesAndSources(t *testing.T) {
}
}
// TestOverview_CommercePartialOnPerOrgError proves the decomplected freshness rule: the
// commerce source is DEGRADED when ANY per-org money read fails — the fleet total is then
// an undercount and must NOT read healthy. Commerce succeeds for hanzo but 500s for acme;
// the overview folds acme's failure into a not-ok commerce source (the SAME partial
// pattern revenue/finance use) instead of the old single-probe that masked it.
func TestOverview_CommercePartialOnPerOrgError(t *testing.T) {
iam := newFakeIAM()
defer iam.server.Close()
commerce := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Header.Get("X-Org-Id") == "acme" {
w.WriteHeader(500) // commerce down for THIS org only
io.WriteString(w, `{"status":"error","msg":"commerce down for acme"}`)
return
}
switch {
case strings.HasSuffix(r.URL.Path, "/usage-rollup"):
io.WriteString(w, `{"consumedCents":1500,"overageCents":0}`)
case strings.HasSuffix(r.URL.Path, "/balance"):
io.WriteString(w, `{"available":5000,"balance":5000}`)
default:
w.WriteHeader(404)
}
}))
defer commerce.Close()
do := mount(t, iam.server.URL, commerce.URL, "")
admin := map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin"}
resp, body := do("GET", "/v1/admin/overview", admin)
if resp.StatusCode != http.StatusOK {
t.Fatalf("overview: %d (%s)", resp.StatusCode, body)
}
var env struct {
Data overviewData `json:"data"`
}
if err := json.Unmarshal(body, &env); err != nil {
t.Fatalf("decode: %v", err)
}
src := map[string]core.SourceStatus{}
for _, s := range env.Data.Sources {
src[s.Name] = s
}
c, ok := src["commerce"]
if !ok {
t.Fatal("overview must report a commerce source")
}
if c.OK {
t.Errorf("commerce source must be DEGRADED when a per-org read failed (undercount masked as healthy), got %+v", c)
}
if c.Error == "" {
t.Errorf("degraded commerce source must carry an error: %+v", c)
}
// The healthy org still contributes — an honest PARTIAL total, never a hard panel fail.
if env.Data.SpendCents30d != 1500 {
t.Errorf("spend = %d, want 1500 (only hanzo read; acme failed)", env.Data.SpendCents30d)
}
}
// TestUsage_RealTotalsHonestEmptySeries proves the usage roll-up returns the REAL
// fleet spend from commerce but an HONEST empty series/byProduct — the timeseries
// feed lives in insights/datastore, and admin must never fabricate a trend.
+96 -302
View File
@@ -1,23 +1,15 @@
package admin
// Native SaaS business ANALYTICS (/v1/admin/analytics) — cohort retention, growth,
// churn, active-customers (DAU/WAU/MAU), revenue (MRR/ARPU) and usage over time,
// derived from REAL fleet data: IAM org `createdTime` (the signup cohort — always
// available) + the commerce transaction ledger (usage = `withdraw` rows, the true
// customer-activity signal). Global-admin only (s.guard), like every admin route.
// churn, active-customers (DAU/WAU/MAU), revenue (MRR/ARPU) and usage over time, derived
// from REAL fleet data: IAM org `createdTime` (the signup cohort) + the commerce
// transaction ledger (usage = `withdraw` rows). SuperAdmin/org-scoped via GuardScoped.
//
// HONEST BY CONSTRUCTION. There is NO fabricated curve anywhere. Growth/cohorts
// come from real signup timestamps; retention/active/churn/usage come from real
// consumption events. A metric that cannot yet be computed (LTV needs observed
// churn; NRR needs MRR history commerce does not expose point-in-time) returns a
// null / honest-empty series — never an invented trend — and the `computed` map
// flags exactly which metrics are backed by data, so the console renders honest
// states and a reviewer can verify no number was made up.
//
// The heavy read (every org's ledger) is bounded + fanned out concurrently. Admin
// is low-QPS; at fleet scale this belongs in the insights/datastore OLAP mirror
// (same note as the usage series), but the billing ledger is the correct SOURCE
// OF TRUTH for real per-customer activity today.
// The fleet activity model + the continuous spend series live in clients/admin/core
// (core.FleetActivity / core.SpendSeries / core.CustActivity / core.SeriesPoint) because
// the revenue board reuses them — one implementation, DRY. This file holds only the
// analytics-specific derivation (growth/retention/churn/active/LTV) that folds over that
// shared model.
import (
"context"
@@ -26,21 +18,17 @@ import (
"sync"
"time"
"github.com/hanzoai/cloud"
"github.com/hanzoai/cloud/clients/admin/core"
"github.com/hanzoai/cloud/clients/admin/iam"
"github.com/zap-proto/zip"
)
// ── wire shapes (operator contract) ──────────────────────────────────────────
// seriesPoint is one bucketed point (count OR cents, per the series). T is the
// bucket key (RFC3339 date / "2006-01" month).
type seriesPoint struct {
T string `json:"t"`
Value int64 `json:"value"`
}
// retentionCohort is one row of the retention triangle: a signup cohort, its size,
// and the % of it still ACTIVE at each subsequent period (values[0] = the signup
// period itself). Percentages are 0..100.
// retentionCohort is one row of the retention triangle: a signup cohort, its size, and
// the % of it still ACTIVE at each subsequent period (values[0] = the signup period
// itself). Percentages are 0..100.
type retentionCohort struct {
Cohort string `json:"cohort"`
Size int `json:"size"`
@@ -61,40 +49,39 @@ type analyticsData struct {
GeneratedAt string `json:"generatedAt"`
// Growth — from IAM createdTime (always real).
Signups []seriesPoint `json:"signups"`
CumulativeCustomers []seriesPoint `json:"cumulativeCustomers"`
TotalCustomers int `json:"totalCustomers"`
NewCustomers int `json:"newCustomers"`
GrowthRatePct float64 `json:"growthRatePct"`
Signups []core.SeriesPoint `json:"signups"`
CumulativeCustomers []core.SeriesPoint `json:"cumulativeCustomers"`
TotalCustomers int `json:"totalCustomers"`
NewCustomers int `json:"newCustomers"`
GrowthRatePct float64 `json:"growthRatePct"`
// Active customers — from the usage ledger.
ActiveCustomers []seriesPoint `json:"activeCustomers"`
DAU int `json:"dau"`
WAU int `json:"wau"`
MAU int `json:"mau"`
ActiveCustomers []core.SeriesPoint `json:"activeCustomers"`
DAU int `json:"dau"`
WAU int `json:"wau"`
MAU int `json:"mau"`
// Retention triangle — signup cohort × active period.
Retention retentionGrid `json:"retention"`
// Churn — logo churn (count) + rate.
Churn []seriesPoint `json:"churn"`
ChurnRatePct float64 `json:"churnRatePct"`
Churn []core.SeriesPoint `json:"churn"`
ChurnRatePct float64 `json:"churnRatePct"`
// Revenue analytics.
MRRCents int64 `json:"mrrCents"`
Revenue []seriesPoint `json:"revenue"`
ARPUCents int64 `json:"arpuCents"`
LTVCents *int64 `json:"ltvCents"` // null until churn is observed
NRRPct *float64 `json:"nrrPct"` // null — needs MRR history
MRRCents int64 `json:"mrrCents"`
Revenue []core.SeriesPoint `json:"revenue"`
ARPUCents int64 `json:"arpuCents"`
LTVCents *int64 `json:"ltvCents"` // null until churn is observed
NRRPct *float64 `json:"nrrPct"` // null — needs MRR history
// Usage analytics.
Usage []seriesPoint `json:"usage"`
TopCustomers []analyticsSlice `json:"topCustomers"`
Usage []core.SeriesPoint `json:"usage"`
TopCustomers []analyticsSlice `json:"topCustomers"`
// Transparency: which metrics are backed by real data vs honest-empty. A
// reviewer/console reads this to know nothing was fabricated.
Computed map[string]bool `json:"computed"`
Sources []sourceStatus `json:"sources"`
// Transparency: which metrics are backed by real data vs honest-empty.
Computed map[string]bool `json:"computed"`
Sources []core.SourceStatus `json:"sources"`
}
// analyticsSlice is a labelled magnitude (top customers by usage cents).
@@ -104,75 +91,38 @@ type analyticsSlice struct {
Hint string `json:"hint,omitempty"`
}
// ── the activity model the pure math folds over ──────────────────────────────
// txnPoint is one dated usage event (a commerce `withdraw`, in cents).
type txnPoint struct {
T time.Time
Cents int64
}
// custActivity is one customer's real analytics input: when they signed up (IAM
// createdTime) and their consumption events (commerce withdraws). Deposits are
// NOT activity (a credit grant is not the customer using the product), so only
// withdraws feed active/retention/churn/usage — the honest "used it" signal.
type custActivity struct {
Org string
Display string
Created time.Time
HasCreated bool
Usage []txnPoint
SpendCents int64
}
func (ca custActivity) activeIn(bucket string, interval string) bool {
for _, p := range ca.Usage {
if bucketKeyOf(p.T, interval) == bucket {
return true
}
}
return false
}
func (ca custActivity) activeSince(cut time.Time) bool {
for _, p := range ca.Usage {
if !p.T.Before(cut) {
return true
}
}
return false
}
// ── handler ──────────────────────────────────────────────────────────────────
func (s *svc) analytics(c *zip.Ctx) error {
func analytics(s *cloud.Service[core.State], c *zip.Ctx) error {
ctx := c.Context()
cr := callerCreds(c)
cr := core.CallerCreds(c)
now := time.Now().UTC()
rangeStr := normalizeRange(c.Query("range"))
since, interval, _ := rangeWindow(rangeStr, now)
var sources []sourceStatus
var sources []core.SourceStatus
orgs, err := s.listOrgs(ctx, cr)
// Scoped fan-in: a SuperAdmin gets every org (all-orgs SaaS analytics); an org admin
// gets ONLY their own subtree — the ONE tenant-scope predicate (core.ScopedOrgs).
orgs, err := core.ScopedOrgs(s, ctx, c, cr)
if err != nil {
return fail(c, err.Error())
return core.Fail(c, err.Error())
}
sources = append(sources, srcOf("iam", nil, len(orgs), now.Format(time.RFC3339)))
sources = append(sources, core.SrcOf("iam", nil, len(orgs), now.Format(time.RFC3339)))
acts, ledgerOK := s.fleetActivity(ctx, orgs)
acts, ledgerOK := core.FleetActivity(s, ctx, orgs)
ledgerRows := 0
for _, a := range acts {
ledgerRows += len(a.Usage)
}
var ledgerErr error
if !ledgerOK {
ledgerErr = errPartialRevenue // partial ledger read — mark degraded
ledgerErr = core.ErrPartialRevenue // partial ledger read — mark degraded
}
sources = append(sources, srcOf("commerce-ledger", ledgerErr, ledgerRows, now.Format(time.RFC3339)))
sources = append(sources, core.SrcOf("commerce-ledger", ledgerErr, ledgerRows, now.Format(time.RFC3339)))
// MRR from subscriptions (point-in-time), fanned out like the money reads.
mrr := s.fleetMRR(ctx, orgs)
mrr := fleetMRR(s, ctx, orgs)
data := computeAnalytics(analyticsInput{
acts: acts,
@@ -185,13 +135,13 @@ func (s *svc) analytics(c *zip.Ctx) error {
})
data.GeneratedAt = now.Format(time.RFC3339)
data.Sources = sources
return ok(c, data)
return core.OK(c, data)
}
// analyticsInput is everything computeAnalytics needs — no I/O, so the whole SaaS
// analytics derivation is unit-testable without a network.
type analyticsInput struct {
acts []custActivity
acts []core.CustActivity
mrrCents int64
now time.Time
since time.Time
@@ -202,19 +152,19 @@ type analyticsInput struct {
// computeAnalytics is the PURE derivation of every analytics metric from the real
// activity model. Growth is always computed (signup timestamps); the ledger-backed
// metrics compute from real usage when present and degrade to honest empty/zero
// when the fleet has no usage yet — never a fabricated curve. `computed` flags each.
// metrics compute from real usage when present and degrade to honest empty/zero when the
// fleet has no usage yet — never a fabricated curve. `computed` flags each.
func computeAnalytics(in analyticsInput) analyticsData {
buckets := enumerateBuckets(in.since, in.now, in.interval)
buckets := core.EnumerateBuckets(in.since, in.now, in.interval)
// ── Growth (IAM createdTime — always real) ──
signups := make([]seriesPoint, len(buckets))
signups := make([]core.SeriesPoint, len(buckets))
newCount := 0
total := 0
for i, b := range buckets {
signups[i] = seriesPoint{T: b}
signups[i] = core.SeriesPoint{T: b}
}
idx := indexOf(buckets)
idx := core.IndexOf(buckets)
for _, a := range in.acts {
if !a.HasCreated {
continue
@@ -223,12 +173,12 @@ func computeAnalytics(in analyticsInput) analyticsData {
if !a.Created.Before(in.since) {
newCount++
}
if i, ok := idx[bucketKeyOf(a.Created, in.interval)]; ok {
if i, ok := idx[core.BucketKeyOf(a.Created, in.interval)]; ok {
signups[i].Value++
}
}
// Cumulative customers across the SAME buckets (all-time count at each bucket end).
cumulative := make([]seriesPoint, len(buckets))
cumulative := make([]core.SeriesPoint, len(buckets))
for i, b := range buckets {
end := bucketEnd(b, in.interval)
n := 0
@@ -237,15 +187,15 @@ func computeAnalytics(in analyticsInput) analyticsData {
n++
}
}
cumulative[i] = seriesPoint{T: b, Value: int64(n)}
cumulative[i] = core.SeriesPoint{T: b, Value: int64(n)}
}
growthRate := priorWindowGrowth(in.acts, in.since, in.now)
// ── Active customers + usage (ledger-backed) ──
usage := spendSeries(in.acts, in.since, in.now, in.interval)
active := make([]seriesPoint, len(buckets))
usage := core.SpendSeries(in.acts, in.since, in.now, in.interval)
active := make([]core.SeriesPoint, len(buckets))
for i, b := range buckets {
active[i] = seriesPoint{T: b}
active[i] = core.SeriesPoint{T: b}
}
for _, a := range in.acts {
// active in a bucket = at least one usage event in it
@@ -254,7 +204,7 @@ func computeAnalytics(in analyticsInput) analyticsData {
if p.T.Before(in.since) || p.T.After(in.now) {
continue
}
seen[bucketKeyOf(p.T, in.interval)] = true
seen[core.BucketKeyOf(p.T, in.interval)] = true
}
for b := range seen {
if i, ok := idx[b]; ok {
@@ -285,8 +235,7 @@ func computeAnalytics(in analyticsInput) analyticsData {
}
var ltv *int64
if churnRate > 0 && arpu > 0 {
// LTV ≈ ARPU / monthly churn rate — computed ONLY when real churn is
// observed, else honest null (LTV needs churn to mean anything).
// LTV ≈ ARPU / monthly churn rate — computed ONLY when real churn is observed.
v := int64(float64(arpu) / (churnRate / 100.0))
ltv = &v
}
@@ -296,7 +245,7 @@ func computeAnalytics(in analyticsInput) analyticsData {
// Revenue series = realized usage revenue per bucket (same as usage cents for a
// pay-as-you-go fleet; distinct field so the console can theme it as revenue).
revenue := make([]seriesPoint, len(usage))
revenue := make([]core.SeriesPoint, len(usage))
copy(revenue, usage)
return analyticsData{
@@ -336,18 +285,18 @@ func computeAnalytics(in analyticsInput) analyticsData {
}
}
// computeRetention builds the cohort × period retention triangle from real signup
// months and usage months. retention[c][k] = fraction of cohort c ACTIVE in month
// c+k. Cohorts are capped to the last `maxCohorts` months (the classic triangle);
// a cohort with no signups is omitted. Values are 0..100.
func computeRetention(acts []custActivity, now time.Time, maxCohorts int) retentionGrid {
// computeRetention builds the cohort × period retention triangle from real signup months
// and usage months. retention[c][k] = fraction of cohort c ACTIVE in month c+k. Cohorts
// are capped to the last `maxCohorts` months; a cohort with no signups is omitted. Values
// are 0..100.
func computeRetention(acts []core.CustActivity, now time.Time, maxCohorts int) retentionGrid {
// Group customers by signup month.
byCohort := map[string][]custActivity{}
byCohort := map[string][]core.CustActivity{}
for _, a := range acts {
if !a.HasCreated {
continue
}
k := monthKey(a.Created)
k := core.MonthKey(a.Created)
byCohort[k] = append(byCohort[k], a)
}
@@ -361,7 +310,7 @@ func computeRetention(acts []custActivity, now time.Time, maxCohorts int) retent
cohorts = cohorts[len(cohorts)-maxCohorts:]
}
nowMonth := monthKey(now)
nowMonth := core.MonthKey(now)
grid := retentionGrid{Interval: "month"}
maxPeriods := 0
for _, cohort := range cohorts {
@@ -375,7 +324,7 @@ func computeRetention(acts []custActivity, now time.Time, maxCohorts int) retent
month := addMonths(cohort, k)
activeN := 0
for _, m := range members {
if m.activeIn(month, "month") {
if m.ActiveIn(month, "month") {
activeN++
}
}
@@ -392,17 +341,16 @@ func computeRetention(acts []custActivity, now time.Time, maxCohorts int) retent
return grid
}
// computeChurn derives monthly LOGO churn: a customer counts as churned in month M
// if they were active in M-1 but NOT in M. The rate is the average monthly churn
// over the observed window (churned / active-at-start). Returns honest zeros when
// there is no usage history.
func computeChurn(acts []custActivity, now time.Time, months int) ([]seriesPoint, float64) {
// computeChurn derives monthly LOGO churn: a customer counts as churned in month M if
// they were active in M-1 but NOT in M. The rate is the average monthly churn over the
// observed window. Returns honest zeros when there is no usage history.
func computeChurn(acts []core.CustActivity, now time.Time, months int) ([]core.SeriesPoint, float64) {
// Build the last `months` month keys ending at now.
keys := lastMonths(now, months)
series := make([]seriesPoint, len(keys))
series := make([]core.SeriesPoint, len(keys))
var churnedTotal, baseTotal int
for i, m := range keys {
series[i] = seriesPoint{T: m}
series[i] = core.SeriesPoint{T: m}
if i == 0 {
continue // no prior month to compare
}
@@ -410,10 +358,10 @@ func computeChurn(acts []custActivity, now time.Time, months int) ([]seriesPoint
churned := 0
base := 0
for _, a := range acts {
wasActive := a.activeIn(prev, "month")
wasActive := a.ActiveIn(prev, "month")
if wasActive {
base++
if !a.activeIn(m, "month") {
if !a.ActiveIn(m, "month") {
churned++
}
}
@@ -429,31 +377,8 @@ func computeChurn(acts []custActivity, now time.Time, months int) ([]seriesPoint
return series, rate
}
// spendSeries buckets fleet usage cents into a continuous series over since..now.
// Shared by the analytics usage/revenue trend and the revenue board's spend trend
// (one implementation, DRY). A bucket with no usage is an honest 0, not a gap.
func spendSeries(acts []custActivity, since, now time.Time, interval string) []seriesPoint {
buckets := enumerateBuckets(since, now, interval)
idx := indexOf(buckets)
out := make([]seriesPoint, len(buckets))
for i, b := range buckets {
out[i] = seriesPoint{T: b}
}
for _, a := range acts {
for _, p := range a.Usage {
if p.T.Before(since) || p.T.After(now) {
continue
}
if i, ok := idx[bucketKeyOf(p.T, interval)]; ok {
out[i].Value += p.Cents
}
}
}
return out
}
// topCustomersByUsage returns the top-N customers by total usage cents (desc).
func topCustomersByUsage(acts []custActivity, n int) []analyticsSlice {
func topCustomersByUsage(acts []core.CustActivity, n int) []analyticsSlice {
rows := make([]analyticsSlice, 0, len(acts))
for _, a := range acts {
if a.SpendCents <= 0 {
@@ -468,9 +393,9 @@ func topCustomersByUsage(acts []custActivity, n int) []analyticsSlice {
return rows
}
// priorWindowGrowth is the signup growth vs the immediately-preceding window: the
// % change in new signups this window vs last. 0 when the prior window had none.
func priorWindowGrowth(acts []custActivity, since, now time.Time) float64 {
// priorWindowGrowth is the signup growth vs the immediately-preceding window: the %
// change in new signups this window vs last. 0 when the prior window had none.
func priorWindowGrowth(acts []core.CustActivity, since, now time.Time) float64 {
window := now.Sub(since)
priorStart := since.Add(-window)
cur, prev := 0, 0
@@ -491,83 +416,29 @@ func priorWindowGrowth(acts []custActivity, since, now time.Time) float64 {
}
// activeWithin counts customers with at least one usage event since `cut`.
func activeWithin(acts []custActivity, cut time.Time) int {
func activeWithin(acts []core.CustActivity, cut time.Time) int {
n := 0
for _, a := range acts {
if a.activeSince(cut) {
if a.ActiveSince(cut) {
n++
}
}
return n
}
// ── fleet readers (I/O; concurrent, bounded) ─────────────────────────────────
// fleetActivity reads every org's signup time (already on the org row) + usage
// ledger, folded into the pure activity model. Returns (acts, ok) where ok is
// false if ANY org's ledger read failed (the caller marks the source degraded and
// flags the ledger-backed metrics as not-fully-computed). Fanned out concurrently
// with a bound, like the customer list.
func (s *svc) fleetActivity(ctx context.Context, orgs []iamOrg) ([]custActivity, bool) {
acts := make([]custActivity, len(orgs))
oks := make([]bool, len(orgs))
sem := make(chan struct{}, maxCustomerConcurrency)
var wg sync.WaitGroup
for i, o := range orgs {
wg.Add(1)
sem <- struct{}{}
go func(i int, o iamOrg) {
defer wg.Done()
defer func() { <-sem }()
ca := custActivity{Org: o.Name, Display: display(o.DisplayName, o.Name)}
if t, err := time.Parse(time.RFC3339, o.CreatedTime); err == nil {
ca.Created = t.UTC()
ca.HasCreated = true
}
rows, err := s.commerce.transactions(ctx, o.Name, orgSubject(o.Name), 2000)
oks[i] = err == nil
for _, r := range rows {
if strings.ToLower(r.Type) != "withdraw" {
continue // only consumption is "activity"; deposits are credits
}
t, perr := parseTxnTime(r.CreatedAt)
if perr != nil {
continue
}
amt := r.Amount
if amt < 0 {
amt = -amt
}
ca.Usage = append(ca.Usage, txnPoint{T: t, Cents: amt})
ca.SpendCents += amt
}
acts[i] = ca
}(i, o)
}
wg.Wait()
allOK := true
for _, ok := range oks {
if !ok {
allOK = false
break
}
}
return acts, allOK
}
// fleetMRR sums each org's active-subscription MRR concurrently.
func (s *svc) fleetMRR(ctx context.Context, orgs []iamOrg) int64 {
func fleetMRR(s *cloud.Service[core.State], ctx context.Context, orgs []iam.Org) int64 {
vals := make([]int64, len(orgs))
sem := make(chan struct{}, maxCustomerConcurrency)
sem := make(chan struct{}, core.MaxCustomerConcurrency)
var wg sync.WaitGroup
for i, o := range orgs {
wg.Add(1)
sem <- struct{}{}
go func(i int, o iamOrg) {
go func(i int, o iam.Org) {
defer wg.Done()
defer func() { <-sem }()
if sum, err := s.commerce.subscriptionSummary(ctx, o.Name, orgSubject(o.Name)); err == nil {
vals[i] = sum.MRR
if pl, err := s.State.Commerce.Plan(ctx, o.Name); err == nil {
vals[i] = int64(pl.MRR)
}
}(i, o)
}
@@ -579,36 +450,10 @@ func (s *svc) fleetMRR(ctx context.Context, orgs []iamOrg) int64 {
return total
}
// ── pure time-bucket helpers ─────────────────────────────────────────────────
// ── analytics-specific month arithmetic (the shared bucket keys live in core) ──
func monthKey(t time.Time) string { return t.UTC().Format("2006-01") }
func dayKey(t time.Time) string { return t.UTC().Format("2006-01-02") }
// weekKey buckets to the ISO week's Monday (a stable weekly key).
func weekKey(t time.Time) string {
u := t.UTC()
// back up to Monday
wd := int(u.Weekday())
if wd == 0 {
wd = 7
}
monday := u.AddDate(0, 0, -(wd - 1))
return monday.Format("2006-01-02")
}
func bucketKeyOf(t time.Time, interval string) string {
switch interval {
case "month":
return monthKey(t)
case "week":
return weekKey(t)
default:
return dayKey(t)
}
}
// bucketEnd returns the inclusive end instant of a bucket key (for the cumulative
// count). A day/week/month key advances one unit; the end is one nanosecond before.
// bucketEnd returns the inclusive end instant of a bucket key (for the cumulative count).
// A day/week/month key advances one unit; the end is one nanosecond before.
func bucketEnd(key, interval string) time.Time {
switch interval {
case "month":
@@ -627,48 +472,6 @@ func bucketEnd(key, interval string) time.Time {
return time.Now().UTC()
}
// enumerateBuckets lists every bucket key from since..now inclusive so a series has
// a continuous axis (a zero-usage bucket is an honest 0, not a gap).
func enumerateBuckets(since, now time.Time, interval string) []string {
if since.After(now) {
return nil
}
var out []string
seen := map[string]bool{}
step := func(t time.Time) time.Time {
switch interval {
case "month":
return t.AddDate(0, 1, 0)
case "week":
return t.AddDate(0, 0, 7)
default:
return t.AddDate(0, 0, 1)
}
}
// cap iterations so a bad range can never spin unbounded
for t, n := since, 0; !t.After(now) && n < 800; t, n = step(t), n+1 {
k := bucketKeyOf(t, interval)
if !seen[k] {
seen[k] = true
out = append(out, k)
}
}
// ensure the final bucket (now) is present
last := bucketKeyOf(now, interval)
if !seen[last] {
out = append(out, last)
}
return out
}
func indexOf(buckets []string) map[string]int {
m := make(map[string]int, len(buckets))
for i, b := range buckets {
m[b] = i
}
return m
}
// addMonths adds k months to a "2006-01" key.
func addMonths(month string, k int) string {
t, err := time.Parse("2006-01", month)
@@ -692,7 +495,7 @@ func monthsBetween(a, b string) int {
func lastMonths(now time.Time, n int) []string {
out := make([]string, 0, n)
for i := n - 1; i >= 0; i-- {
out = append(out, monthKey(now.AddDate(0, -i, 0)))
out = append(out, core.MonthKey(now.AddDate(0, -i, 0)))
}
return out
}
@@ -704,15 +507,6 @@ func pct(part, whole int) float64 {
return (float64(part) / float64(whole)) * 100
}
// parseTxnTime accepts the commerce ledger's RFC3339 forms.
func parseTxnTime(s string) (time.Time, error) {
s = strings.TrimSpace(s)
if t, err := time.Parse(time.RFC3339, s); err == nil {
return t.UTC(), nil
}
return time.Parse("2006-01-02T15:04:05Z", s)
}
// normalizeRange clamps the range param to the supported set (default 30d).
func normalizeRange(r string) string {
switch strings.TrimSpace(r) {
+10 -8
View File
@@ -4,6 +4,8 @@ import (
"math"
"testing"
"time"
"github.com/hanzoai/cloud/clients/admin/core"
)
// mkTime is a test helper for an RFC3339-ish instant.
@@ -21,14 +23,14 @@ func mkTime(s string) time.Time {
// alpha: signup 2024-05-10; usage 2024-05-20 (100c), 2024-06-05 (200c) [cohort 05, active 05+06]
// beta : signup 2024-05-25; usage 2024-05-28 (50c) [cohort 05, active 05 only]
// gamma: signup 2024-06-15; usage 2024-07-01 (400c) [cohort 06, active 07 only]
func fleetFixture() []custActivity {
return []custActivity{
func fleetFixture() []core.CustActivity {
return []core.CustActivity{
{Org: "alpha", Display: "Alpha", Created: mkTime("2024-05-10"), HasCreated: true,
Usage: []txnPoint{{T: mkTime("2024-05-20"), Cents: 100}, {T: mkTime("2024-06-05"), Cents: 200}}, SpendCents: 300},
Usage: []core.TxnPoint{{T: mkTime("2024-05-20"), Cents: 100}, {T: mkTime("2024-06-05"), Cents: 200}}, SpendCents: 300},
{Org: "beta", Display: "Beta", Created: mkTime("2024-05-25"), HasCreated: true,
Usage: []txnPoint{{T: mkTime("2024-05-28"), Cents: 50}}, SpendCents: 50},
Usage: []core.TxnPoint{{T: mkTime("2024-05-28"), Cents: 50}}, SpendCents: 50},
{Org: "gamma", Display: "Gamma", Created: mkTime("2024-06-15"), HasCreated: true,
Usage: []txnPoint{{T: mkTime("2024-07-01"), Cents: 400}}, SpendCents: 400},
Usage: []core.TxnPoint{{T: mkTime("2024-07-01"), Cents: 400}}, SpendCents: 400},
}
}
@@ -215,10 +217,10 @@ func TestComputeAnalytics_HonestEmptyNoLedger(t *testing.T) {
func TestSpendSeries_ContinuousHonestBuckets(t *testing.T) {
now := mkTime("2024-07-05")
since := mkTime("2024-07-01")
acts := []custActivity{
{Usage: []txnPoint{{T: mkTime("2024-07-01"), Cents: 100}, {T: mkTime("2024-07-03"), Cents: 300}}},
acts := []core.CustActivity{
{Usage: []core.TxnPoint{{T: mkTime("2024-07-01"), Cents: 100}, {T: mkTime("2024-07-03"), Cents: 300}}},
}
series := spendSeries(acts, since, now, "day")
series := core.SpendSeries(acts, since, now, "day")
// 5 daily buckets 07-01..07-05.
if len(series) != 5 {
t.Fatalf("series buckets = %d, want 5 (%+v)", len(series), series)
-182
View File
@@ -1,182 +0,0 @@
package admin
// The /v1/admin/audit query surface, wired to cloud's REAL tamper-evident audit
// store (the audit.Recorder Serve builds and hands over via deps.Audit).
//
// This REPLACES the previous behavior — proxying IAM get-records — as the primary
// source: cloud now keeps its OWN append-only, hash-chained trail of every
// security-relevant request against this binary, and that is what a compliance
// auditor queries here. IAM's own login/session records remain available in IAM;
// they are a DIFFERENT trail (IAM's request surface), and admin still federates
// them as a fallback when cloud's local store is not configured, so no capability
// is lost.
//
// SECURITY. Both handlers are registered behind the SAME s.guard as every other
// /v1/admin/* route (global-admin only, fail-closed). They are READ-ONLY (Query
// and Verify issue SELECT only), so exposing them cannot weaken the append-only
// property. The verify endpoint returns integrity STATUS, never a way to mutate.
import (
"strconv"
"strings"
"time"
"github.com/hanzoai/cloud/audit"
"github.com/zap-proto/zip"
)
// auditRow is one record in the operator's audit table (AuditRow). The JSON tags
// are the operator contract. It is cloud's OWN record shape — richer than the IAM
// Record it supersedes: it carries the outcome, the validated auth context, and
// the hash-chain linkage so the console can show integrity per row.
type auditRow struct {
Seq uint64 `json:"seq"`
Time string `json:"time"`
Org string `json:"org"`
Sub string `json:"sub"`
Email string `json:"email,omitempty"`
Action string `json:"action"`
Resource string `json:"resource"`
ResourceID string `json:"resourceId,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Result string `json:"result"`
Status int `json:"status"`
Reason string `json:"reason,omitempty"`
SourceIP string `json:"sourceIp,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
RequestID string `json:"requestId,omitempty"`
IsAdmin bool `json:"isAdmin"`
Auth string `json:"authMethod,omitempty"`
Hash string `json:"hash"`
PrevHash string `json:"prevHash"`
}
// audit answers GET /v1/admin/audit from cloud's local tamper-evident store when
// configured, else falls back to the IAM get-records proxy (federated view).
// Filters: org, sub, action, resource, result, since, until, pageSize, p (page).
// The response is the /v1 list envelope { data:[rows], data2:total } the
// operator decodes, with the current chain integrity summary attached.
func (s *svc) audit(c *zip.Ctx) error {
// No local store configured → preserve the legacy federated IAM view so the
// endpoint never regresses to empty.
if s.auditStore == nil {
return s.auditFromIAM(c)
}
f := auditFilterFromQuery(c)
rows, total, err := s.auditStore.Query(c.Context(), f)
if err != nil {
return fail(c, err.Error())
}
out := make([]auditRow, 0, len(rows))
for _, r := range rows {
out = append(out, toAuditRow(r))
}
// Attach the live integrity summary so the console can badge the trail as
// verified. Best-effort: a verify error must not fail the listing.
integrity, ivErr := s.auditStore.Verify(c.Context())
var integrityPayload any
if ivErr == nil {
integrityPayload = integrity
}
return c.JSON(200, map[string]any{
"status": "ok",
"msg": "",
"data": out,
"data2": total,
"integrity": integrityPayload,
})
}
// auditVerify answers GET /v1/admin/audit/verify — the tamper-evidence check. It
// walks the whole hash chain and returns the integrity result (ok, count, head,
// and the seq where the chain first breaks if tampered). Global-admin gated like
// every admin route.
func (s *svc) auditVerify(c *zip.Ctx) error {
if s.auditStore == nil {
return fail(c, "audit store not configured")
}
integrity, err := s.auditStore.Verify(c.Context())
if err != nil {
return fail(c, err.Error())
}
return ok(c, integrity)
}
// auditFilterFromQuery builds an audit.Filter from the request query params. Time
// bounds accept RFC3339. pageSize (default 100, cap 1000) and p (1-based page)
// drive Limit/Offset. Unknown/blank params are simply not applied.
func auditFilterFromQuery(c *zip.Ctx) audit.Filter {
f := audit.Filter{
Org: strings.TrimSpace(c.Query("org")),
Sub: strings.TrimSpace(c.Query("sub")),
Action: strings.TrimSpace(c.Query("action")),
Resource: strings.TrimSpace(c.Query("resource")),
Result: strings.TrimSpace(c.Query("result")),
}
if v := strings.TrimSpace(c.Query("since")); v != "" {
if t, err := time.Parse(time.RFC3339, v); err == nil {
f.Since = t
}
}
if v := strings.TrimSpace(c.Query("until")); v != "" {
if t, err := time.Parse(time.RFC3339, v); err == nil {
f.Until = t
}
}
pageSize := 100
if v := strings.TrimSpace(c.Query("pageSize")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
pageSize = n
}
}
f.Limit = pageSize
if v := strings.TrimSpace(c.Query("p")); v != "" {
if page, err := strconv.Atoi(v); err == nil && page > 1 {
f.Offset = (page - 1) * pageSize
}
}
return f
}
// toAuditRow maps a stored audit.Record to the operator wire row.
func toAuditRow(r audit.Record) auditRow {
return auditRow{
Seq: r.Seq,
Time: r.Time.UTC().Format(time.RFC3339Nano),
Org: r.Actor.Org,
Sub: r.Actor.Sub,
Email: r.Actor.Email,
Action: r.Action,
Resource: r.Resource.Type,
ResourceID: r.Resource.ID,
Method: r.Method,
Path: r.Path,
Result: r.Outcome.Result,
Status: r.Outcome.Status,
Reason: r.Outcome.Reason,
SourceIP: r.SourceIP,
UserAgent: r.UserAgent,
RequestID: r.RequestID,
IsAdmin: r.Auth.IsAdmin,
Auth: r.Auth.Method,
Hash: r.Hash,
PrevHash: r.PrevHash,
}
}
// auditFromIAM is the legacy federated view: when cloud has no local audit store,
// forward the IAM get-records read verbatim (the prior behavior), so the endpoint
// still surfaces IAM's own audit trail rather than an empty list.
func (s *svc) auditFromIAM(c *zip.Ctx) error {
q := iamAuditQuery(c)
res, err := s.iam.getList(c.Context(), callerCreds(c), "/v1/iam/get-records", q)
if err != nil {
return fail(c, err.Error())
}
return okRaw(c, res.rows, res.total)
}
+151
View File
@@ -0,0 +1,151 @@
// Package audit is the /v1/admin/audit query surface, wired to cloud's REAL
// tamper-evident audit store (the audit.Recorder Serve builds and hands over via
// deps.Audit).
//
// cloud keeps its OWN append-only, hash-chained trail of every security-relevant
// request against this binary, and that is what a compliance auditor queries here. IAM's
// own login/session records remain a DIFFERENT trail; admin still federates them as a
// fallback when cloud's local store is not configured, so no capability is lost.
//
// SECURITY. Both handlers are registered behind core.Guard (SuperAdmin only,
// fail-closed). They are READ-ONLY (Query and Verify issue SELECT only), so exposing
// them cannot weaken the append-only property.
package audit
import (
"net/url"
"strconv"
"strings"
"time"
"github.com/hanzoai/cloud"
auditstore "github.com/hanzoai/cloud/audit"
"github.com/hanzoai/cloud/clients/admin/core"
"github.com/zap-proto/zip"
)
// Routes registers the /v1/admin/audit* surface (SuperAdmin only).
func Routes(app *zip.App, s *cloud.Service[core.State]) {
app.Get("/v1/admin/audit", core.Guard(s, Records))
app.Get("/v1/admin/audit/verify", core.Guard(s, Verify))
}
// Records answers GET /v1/admin/audit from cloud's local tamper-evident store when
// configured, else falls back to the IAM get-records proxy (federated view). Filters:
// org, sub, action, resource, result, since, until, pageSize, p (page). The response is
// the /v1 list envelope { data:[rows], data2:total } with the current chain integrity
// summary attached.
func Records(s *cloud.Service[core.State], c *zip.Ctx) error {
// No local store configured → preserve the legacy federated IAM view so the endpoint
// never regresses to empty.
if s.State.AuditStore == nil {
return fromIAM(s, c)
}
f := auditFilterFromQuery(c)
rows, total, err := s.State.AuditStore.Query(c.Context(), f)
if err != nil {
return core.Fail(c, err.Error())
}
out := make([]auditstore.Wire, 0, len(rows))
for _, r := range rows {
out = append(out, r.ToWire())
}
// Attach the live integrity summary so the console can badge the trail as verified.
// Best-effort: a verify error must not fail the listing.
integrity, ivErr := s.State.AuditStore.Verify(c.Context())
var integrityPayload any
if ivErr == nil {
integrityPayload = integrity
}
return c.JSON(200, map[string]any{
"status": "ok",
"msg": "",
"data": out,
"data2": total,
"integrity": integrityPayload,
})
}
// Verify answers GET /v1/admin/audit/verify — the tamper-evidence check. It walks the
// whole hash chain and returns the integrity result (ok, count, head, and the seq where
// the chain first breaks if tampered).
func Verify(s *cloud.Service[core.State], c *zip.Ctx) error {
if s.State.AuditStore == nil {
return core.Fail(c, "audit store not configured")
}
integrity, err := s.State.AuditStore.Verify(c.Context())
if err != nil {
return core.Fail(c, err.Error())
}
return core.OK(c, integrity)
}
// auditFilterFromQuery builds an audit.Filter from the request query params. Time bounds
// accept RFC3339. pageSize (default 100) and p (1-based page) drive Limit/Offset.
// Unknown/blank params are simply not applied.
func auditFilterFromQuery(c *zip.Ctx) auditstore.Filter {
f := auditstore.Filter{
Org: strings.TrimSpace(c.Query("org")),
Sub: strings.TrimSpace(c.Query("sub")),
Action: strings.TrimSpace(c.Query("action")),
Resource: strings.TrimSpace(c.Query("resource")),
ResourceID: strings.TrimSpace(c.Query("resourceId")),
Result: strings.TrimSpace(c.Query("result")),
}
if v := strings.TrimSpace(c.Query("since")); v != "" {
if t, err := time.Parse(time.RFC3339, v); err == nil {
f.Since = t
}
}
if v := strings.TrimSpace(c.Query("until")); v != "" {
if t, err := time.Parse(time.RFC3339, v); err == nil {
f.Until = t
}
}
pageSize := 100
if v := strings.TrimSpace(c.Query("pageSize")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
pageSize = n
}
}
f.Limit = pageSize
if v := strings.TrimSpace(c.Query("p")); v != "" {
if page, err := strconv.Atoi(v); err == nil && page > 1 {
f.Offset = (page - 1) * pageSize
}
}
return f
}
// fromIAM is the legacy federated view: when cloud has no local audit store, forward the
// IAM get-records read verbatim (the prior behavior), so the endpoint still surfaces
// IAM's own audit trail rather than an empty list.
func fromIAM(s *cloud.Service[core.State], c *zip.Ctx) error {
q := iamAuditQuery(c)
res, err := s.State.IAM.List(c.Context(), core.CallerCreds(c), "/v1/iam/get-records", q)
if err != nil {
return core.Fail(c, err.Error())
}
return core.OKRaw(c, res.Rows, res.Total)
}
// iamAuditQuery builds the IAM get-records query for the federated fallback.
func iamAuditQuery(c *zip.Ctx) url.Values {
q := url.Values{}
if org := strings.TrimSpace(c.Query("org")); org != "" {
q.Set("organizationName", org)
}
q.Set("p", "1")
ps := strings.TrimSpace(c.Query("pageSize"))
if ps == "" {
ps = "100"
}
q.Set("pageSize", ps)
q.Set("sortField", "createdTime")
q.Set("sortOrder", "descend")
return q
}
@@ -1,9 +1,9 @@
package admin
package audit
// Tests for the store-backed /v1/admin/audit + /v1/admin/audit/verify surface.
// They wire admin against a REAL audit.Recorder (on-disk SQLite) seeded with
// records, drive requests through the whole zip app, and assert the query
// results, the integrity summary, and the global-admin gate.
// Tests for the store-backed /v1/admin/audit + /v1/admin/audit/verify surface. They wire
// the audit domain against a REAL audit.Recorder (on-disk SQLite) seeded with records,
// drive requests through the whole zip app, and assert the query results, the integrity
// summary, and the SuperAdmin gate.
import (
"context"
@@ -15,29 +15,29 @@ import (
"testing"
"time"
fiber "github.com/gofiber/fiber/v3"
"github.com/hanzoai/cloud/audit"
"github.com/zap-proto/zip"
"github.com/hanzoai/cloud"
auditstore "github.com/hanzoai/cloud/audit"
"github.com/hanzoai/cloud/clients/admin/core"
luxlog "github.com/luxfi/log"
fiber "github.com/zap-proto/fiber/v3"
"github.com/zap-proto/zip"
)
// mountWithStore builds a zip app with admin's audit routes wired to a real audit
// store, and returns the store + a request helper. Only the audit routes are
// mounted here (the rest are covered by mount()); this keeps the store-backed
// tests focused.
func mountWithStore(t *testing.T) (*audit.Recorder, func(method, path string, hdr map[string]string) (*http.Response, []byte)) {
// mountWithStore builds a zip app with the audit routes wired to a real audit store, and
// returns the store + a request helper. Only the audit routes are mounted here.
func mountWithStore(t *testing.T) (*auditstore.Recorder, func(method, path string, hdr map[string]string) (*http.Response, []byte)) {
t.Helper()
path := filepath.Join(t.TempDir(), "audit.db")
rec, err := audit.Open(path, nil)
rec, err := auditstore.Open(path, nil)
if err != nil {
t.Fatalf("audit.Open: %v", err)
}
t.Cleanup(func() { _ = rec.Close() })
app := zip.New(zip.Config{Logger: luxlog.New("test")})
s := &svc{adminOrg: "admin", auditStore: rec}
app.Get("/v1/admin/audit", s.guard(s.audit))
app.Get("/v1/admin/audit/verify", s.guard(s.auditVerify))
s := &cloud.Service[core.State]{State: core.State{AdminOrg: "admin", AuditStore: rec}}
app.Get("/v1/admin/audit", core.Guard(s, Records))
app.Get("/v1/admin/audit/verify", core.Guard(s, Verify))
fa := app.Fiber()
do := func(method, p string, hdr map[string]string) (*http.Response, []byte) {
@@ -56,17 +56,17 @@ func mountWithStore(t *testing.T) (*audit.Recorder, func(method, path string, hd
return rec, do
}
func seedAudit(t *testing.T, rec *audit.Recorder, n int) {
func seedAudit(t *testing.T, rec *auditstore.Recorder, n int) {
t.Helper()
ctx := context.Background()
for i := 0; i < n; i++ {
_, err := rec.Append(ctx, audit.Record{
_, err := rec.Append(ctx, auditstore.Record{
Time: time.Now().UTC(),
Actor: audit.Actor{Org: "admin", Sub: "z@hanzo.ai"},
Actor: auditstore.Actor{Org: "admin", Sub: "z@hanzo.ai"},
Action: "DELETE /v1/admin/orgs",
Resource: audit.Resource{Type: "org", ID: "acme"},
Auth: audit.AuthContext{Method: "jwt", IsAdmin: true},
Outcome: audit.Outcome{Result: "success", Status: 200},
Resource: auditstore.Resource{Type: "org", ID: "acme"},
Auth: auditstore.AuthContext{Method: "jwt", IsAdmin: true},
Outcome: auditstore.Outcome{Result: "success", Status: 200},
Method: "DELETE",
Path: "/v1/admin/orgs/acme",
})
@@ -76,15 +76,15 @@ func seedAudit(t *testing.T, rec *audit.Recorder, n int) {
}
}
var globalAdmin = map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin", "X-User-Id": "z@hanzo.ai"}
var superAdmin = map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin", "X-User-Id": "z@hanzo.ai"}
// TestAdminAudit_ReturnsRealRecords proves GET /v1/admin/audit returns the
// store's records (newest-first) with an accurate total and an integrity summary.
// TestAdminAudit_ReturnsRealRecords proves GET /v1/admin/audit returns the store's
// records (newest-first) with an accurate total and an integrity summary.
func TestAdminAudit_ReturnsRealRecords(t *testing.T) {
rec, do := mountWithStore(t)
seedAudit(t, rec, 5)
resp, body := do("GET", "/v1/admin/audit", globalAdmin)
resp, body := do("GET", "/v1/admin/audit", superAdmin)
if resp.StatusCode != http.StatusOK {
t.Fatalf("audit: got %d (body=%s)", resp.StatusCode, body)
}
@@ -123,10 +123,10 @@ func TestAdminAudit_Filters(t *testing.T) {
rec, do := mountWithStore(t)
ctx := context.Background()
// One deny among successes.
_, _ = rec.Append(ctx, audit.Record{Action: "POST /v1/admin/roles", Actor: audit.Actor{Org: "admin"}, Outcome: audit.Outcome{Result: "deny", Status: 403}})
_, _ = rec.Append(ctx, auditstore.Record{Action: "POST /v1/admin/roles", Actor: auditstore.Actor{Org: "admin"}, Outcome: auditstore.Outcome{Result: "deny", Status: 403}})
seedAudit(t, rec, 3)
resp, body := do("GET", "/v1/admin/audit?result=deny", globalAdmin)
resp, body := do("GET", "/v1/admin/audit?result=deny", superAdmin)
if resp.StatusCode != http.StatusOK {
t.Fatalf("got %d (body=%s)", resp.StatusCode, body)
}
@@ -143,13 +143,13 @@ func TestAdminAudit_Filters(t *testing.T) {
}
}
// TestAdminAudit_VerifyEndpoint proves GET /v1/admin/audit/verify returns the
// integrity result for the chain.
// TestAdminAudit_VerifyEndpoint proves GET /v1/admin/audit/verify returns the integrity
// result for the chain.
func TestAdminAudit_VerifyEndpoint(t *testing.T) {
rec, do := mountWithStore(t)
seedAudit(t, rec, 8)
resp, body := do("GET", "/v1/admin/audit/verify", globalAdmin)
resp, body := do("GET", "/v1/admin/audit/verify", superAdmin)
if resp.StatusCode != http.StatusOK {
t.Fatalf("verify: got %d (body=%s)", resp.StatusCode, body)
}
@@ -172,12 +172,9 @@ func TestAdminAudit_VerifyEndpoint(t *testing.T) {
}
}
// TestAdminAudit_DeniedWithoutGlobalAdmin proves BOTH audit endpoints fail-closed
// 403 for a non-global-admin, and — critically — the store is NEVER read on a
// denied request (the gate runs before the handler, so no records leak to an
// unauthorized caller). We assert non-leakage by seeding records and confirming
// the denied response body contains none of them.
func TestAdminAudit_DeniedWithoutGlobalAdmin(t *testing.T) {
// TestAdminAudit_DeniedWithoutSuperAdmin proves BOTH audit endpoints fail-closed 403 for
// a non-SuperAdmin, and — critically — the store is NEVER read on a denied request.
func TestAdminAudit_DeniedWithoutSuperAdmin(t *testing.T) {
rec, do := mountWithStore(t)
seedAudit(t, rec, 3)
@@ -203,17 +200,14 @@ func TestAdminAudit_DeniedWithoutGlobalAdmin(t *testing.T) {
}
}
// TestAdminAudit_FallsBackToIAMWhenNoStore proves that when no local store is
// configured (auditStore == nil), /v1/admin/audit still serves the federated IAM
// view rather than erroring — preserving the prior capability. Covered by the
// existing TestAudit_MapsRecords (IAM proxy path); here we assert the nil-store
// verify endpoint reports "not configured" rather than panicking.
// TestAdminAudit_VerifyWithoutStore proves the nil-store verify endpoint reports "not
// configured" rather than panicking.
func TestAdminAudit_VerifyWithoutStore(t *testing.T) {
app := zip.New(zip.Config{Logger: luxlog.New("test")})
s := &svc{adminOrg: "admin"} // no auditStore
app.Get("/v1/admin/audit/verify", s.guard(s.auditVerify))
s := &cloud.Service[core.State]{State: core.State{AdminOrg: "admin"}} // no auditStore
app.Get("/v1/admin/audit/verify", core.Guard(s, Verify))
req := httptest.NewRequest("GET", "/v1/admin/audit/verify", nil)
for k, v := range globalAdmin {
for k, v := range superAdmin {
req.Header.Set(k, v)
}
resp, err := app.Fiber().Test(req, fiber.TestConfig{Timeout: 30 * time.Second})

Some files were not shown because too many files have changed in this diff Show More