Compare commits
225
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12d0081e3b | ||
|
|
1256cda741 | ||
|
|
abcbbb155b | ||
|
|
48d3b35e67 | ||
|
|
3fef8bccce | ||
|
|
30a566846b | ||
|
|
ff5cefcddd | ||
|
|
aafa89064d | ||
|
|
893e7d7759 | ||
|
|
b6f15cd27c | ||
|
|
31e87b7f1e | ||
|
|
28c4f699d0 | ||
|
|
3649758225 | ||
|
|
e06813a5ed | ||
|
|
f09d98a1a0 | ||
|
|
707b6332ad | ||
|
|
524ffb7cdb | ||
|
|
4bd4feabe4 | ||
|
|
b7b61933bf | ||
|
|
a952bed0b7 | ||
|
|
2f3535d5be | ||
|
|
807bad3f4c | ||
|
|
fc3de9ede2 | ||
|
|
3a417701c8 | ||
|
|
3a464b01c4 | ||
|
|
c90196fa14 | ||
|
|
4264ddeb19 | ||
|
|
69cf880b2f | ||
|
|
1d309c9474 | ||
|
|
db2e9284be | ||
|
|
0a9c727609 | ||
|
|
a63189c83a | ||
|
|
f3843d34b5 | ||
|
|
807cf30294 | ||
|
|
e930c39fd6 | ||
|
|
2c1dd75101 | ||
|
|
a9e6e028b4 | ||
|
|
399b893b09 | ||
|
|
c59dcb2a85 | ||
|
|
4055226f6c | ||
|
|
8408c141eb | ||
|
|
605f565138 | ||
|
|
4a2e098705 | ||
|
|
4500f609ed | ||
|
|
d6f98175df | ||
|
|
5527827b46 | ||
|
|
96232be94e | ||
|
|
096de3d8b1 | ||
|
|
0d8c0df95f | ||
|
|
3b09f22fb1 | ||
|
|
be2243afc8 | ||
|
|
eff0ca6b79 | ||
|
|
17924d81b2 | ||
|
|
55f168324d | ||
|
|
d0f2a64ca9 | ||
|
|
6bdb64d13a | ||
|
|
8f398960bd | ||
|
|
b5292c5639 | ||
|
|
134ff852ef | ||
|
|
fbe07f3e7c | ||
|
|
222f91b898 | ||
|
|
f5a7ccdfc7 | ||
|
|
fdb7a31dd0 | ||
|
|
256b848ece | ||
|
|
643926bc76 | ||
|
|
5019d7a384 | ||
|
|
efbdab87f6 | ||
|
|
78a8197e49 | ||
|
|
83519a957e | ||
|
|
7b19236966 | ||
|
|
2e3dc7d818 | ||
|
|
906f89a2b6 | ||
|
|
84cea2889a | ||
|
|
fa6cc69a65 | ||
|
|
0063793f12 | ||
|
|
198a025cf9 | ||
|
|
7b204ee0de | ||
|
|
81515ef108 | ||
|
|
320af40b0b | ||
|
|
277ea80a4f | ||
|
|
cd42e5f902 | ||
|
|
c0672a1fa6 | ||
|
|
675d17f29c | ||
|
|
46f42f43e6 | ||
|
|
214b5d2925 | ||
|
|
42f2ed8f52 | ||
|
|
70f8d29447 | ||
|
|
01378dea23 | ||
|
|
694bc4f716 | ||
|
|
184945862f | ||
|
|
b3e058490c | ||
|
|
7c301185ee | ||
|
|
40ca519c51 | ||
|
|
0f86fd4a5b | ||
|
|
5ac8e7a1a5 | ||
|
|
3baee40745 | ||
|
|
2cb2e8e286 | ||
|
|
6dc2b3a355 | ||
|
|
6134408bad | ||
|
|
36fc7c3b74 | ||
|
|
180fd74369 | ||
|
|
78e0d35199 | ||
|
|
e80a6fc641 | ||
|
|
577d4a14fa | ||
|
|
2636741033 | ||
|
|
4cf5815f52 | ||
|
|
cb8a915bfe | ||
|
|
d8e7017862 | ||
|
|
814d453bd5 | ||
|
|
0f375f684b | ||
|
|
98155f51a3 | ||
|
|
9ecd5a87b8 | ||
|
|
df33e858ce | ||
|
|
7d4568ff72 | ||
|
|
263473c2cb | ||
|
|
169beabdc2 | ||
|
|
932e1f6f32 | ||
|
|
87e578c6db | ||
|
|
c86ddfbec9 | ||
|
|
3b3eea5ede | ||
|
|
8dd682e160 | ||
|
|
dd4b0f5c72 | ||
|
|
1565bb2657 | ||
|
|
37bfe14380 | ||
|
|
f5948dccca | ||
|
|
65aa122ca9 | ||
|
|
34643df667 | ||
|
|
9c56a93ffb | ||
|
|
caf0db43f7 | ||
|
|
75cdae8172 | ||
|
|
945441e402 | ||
|
|
4042dcc7d2 | ||
|
|
4e648305dc | ||
|
|
671c08f57a | ||
|
|
5ffb30f9dd | ||
|
|
ede3887880 | ||
|
|
4a1b33cff5 | ||
|
|
4eb1e74ebb | ||
|
|
7d3df8ac2a | ||
|
|
6f75859b3c | ||
|
|
bd7bce6b39 | ||
|
|
faefd7d4d3 | ||
|
|
7e0fc65a0a | ||
|
|
bc5bdcd4c0 | ||
|
|
18eb2edfb7 | ||
|
|
0b30320f79 | ||
|
|
5dac9c3f34 | ||
|
|
655e491414 | ||
|
|
004c6101f4 | ||
|
|
e922033543 | ||
|
|
af93855841 | ||
|
|
5ec96533e5 | ||
|
|
051df1a96b | ||
|
|
7add862ca6 | ||
|
|
684e447943 | ||
|
|
4e0f4c87ca | ||
|
|
d3f60be7e6 | ||
|
|
4f9c09aa30 | ||
|
|
3e34b7bd54 | ||
|
|
3f279cbb19 | ||
|
|
54b81309be | ||
|
|
268e79369e | ||
|
|
f977650c30 | ||
|
|
bb021e49a7 | ||
|
|
bca49760b1 | ||
|
|
f470bcab93 | ||
|
|
d31cd1cde6 | ||
|
|
2527b4957e | ||
|
|
22a268cd29 | ||
|
|
6012f52b6a | ||
|
|
cf663ec015 | ||
|
|
5e75f25b45 | ||
|
|
ca9c4682dd | ||
|
|
8eabff4d44 | ||
|
|
6cde53fb05 | ||
|
|
9560169625 | ||
|
|
4ee67c1797 | ||
|
|
2bb35ac291 | ||
|
|
0782431509 | ||
|
|
e2929b82b0 | ||
|
|
d19f1d9066 | ||
|
|
7241bc952e | ||
|
|
8a50e0d335 | ||
|
|
1484745a01 | ||
|
|
9dc3038051 | ||
|
|
a06b5fb1a2 | ||
|
|
675809dcdf | ||
|
|
f43883d34e | ||
|
|
74fe777aeb | ||
|
|
9963b3d055 | ||
|
|
e8fa9d6f18 | ||
|
|
18289d0eb6 | ||
|
|
fac1cf9aa3 | ||
|
|
f7ded021ec | ||
|
|
dbc4966aeb | ||
|
|
d38984f03f | ||
|
|
0aa853f300 | ||
|
|
610dcc166d | ||
|
|
26a1910bca | ||
|
|
d411200359 | ||
|
|
071174a414 | ||
|
|
bc98da0308 | ||
|
|
7456318242 | ||
|
|
d9a20e2798 | ||
|
|
36231f57e2 | ||
|
|
4343cdc684 | ||
|
|
187473bd92 | ||
|
|
9659d1a56f | ||
|
|
75d6f36639 | ||
|
|
dcd107b336 | ||
|
|
04a4d68118 | ||
|
|
a773c9225a | ||
|
|
50bbf3a64d | ||
|
|
7685705165 | ||
|
|
ed4d37235f | ||
|
|
0655cdb8cd | ||
|
|
7ff5862f42 | ||
|
|
fceb34c1d2 | ||
|
|
d5e12b3df1 | ||
|
|
36ba00f540 | ||
|
|
db53daea72 | ||
|
|
919d96f3f8 | ||
|
|
d846f17bf8 | ||
|
|
1648c08839 | ||
|
|
385237bdaa |
@@ -111,6 +111,28 @@ jobs:
|
||||
echo "GOPROXY=https://proxy.golang.org,direct"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: zen streaming-fix floor — go.mod must pin github.com/hanzoai/zen >= v1.4.1
|
||||
# The SSE body-close fix (zen commit 50328b8, first released in zen v1.4.1)
|
||||
# is what makes streaming completions return a body instead of an empty
|
||||
# stream. A stale-branch merge that reverts go.mod's zen pin below the floor
|
||||
# silently re-breaks streaming, and `next build`'s ignoreBuildErrors hides
|
||||
# the runtime break — so no image may be cut on a regressed pin. This is the
|
||||
# durable root-cause guard: it reads the EFFECTIVE module version (post-MVS,
|
||||
# exactly what the build links) and fails the PR/push below the floor.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
FLOOR="v1.4.1"
|
||||
V="$(go list -m -f '{{.Version}}' github.com/hanzoai/zen)"
|
||||
echo "effective github.com/hanzoai/zen = ${V} (floor ${FLOOR})"
|
||||
# semver-correct compare: the lowest of {V, FLOOR} under `sort -V` must be
|
||||
# the FLOOR, i.e. V >= FLOOR. (sort -V orders v1.4.2 above v1.4.10 too.)
|
||||
low="$(printf '%s\n%s\n' "$V" "$FLOOR" | sort -V | head -1)"
|
||||
if [ "$low" != "$FLOOR" ]; then
|
||||
echo "::error::github.com/hanzoai/zen is pinned at ${V}, below the streaming-fix floor ${FLOOR} — this re-breaks SSE streaming (empty completions). Re-pin zen to >= ${FLOOR} in go.mod before merging."
|
||||
exit 1
|
||||
fi
|
||||
echo "OK: zen ${V} is at or above the streaming-fix floor ${FLOOR}"
|
||||
|
||||
- name: positive proof — clients/controlplane is unreachable from the default build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
+161
-37
@@ -124,20 +124,6 @@ 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:
|
||||
@@ -160,8 +146,12 @@ jobs:
|
||||
# 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
|
||||
if echo "$REGISTRY_PASSWORD" | docker login registry.hanzo.ai -u "$REGISTRY_USER" --password-stdin; then
|
||||
echo "MIRROR_OK=1" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "mirror login failed (registry.hanzo.ai unreachable) — mirror skipped, release continues"
|
||||
fi
|
||||
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')
|
||||
@@ -180,8 +170,11 @@ jobs:
|
||||
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"
|
||||
if echo "${UP#*:}" | docker login registry.hanzo.ai -u "${UP%%:*}" --password-stdin; then
|
||||
echo "MIRROR_OK=1" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "mirror login failed (registry.hanzo.ai unreachable) — mirror skipped, release continues"
|
||||
fi
|
||||
|
||||
- name: Log in to ghcr.io (GH_PAT — writes the cloud package despite its ai-repo linkage)
|
||||
uses: docker/login-action@v3
|
||||
@@ -190,6 +183,39 @@ jobs:
|
||||
username: hanzo-dev
|
||||
password: ${{ secrets.GH_PAT }}
|
||||
|
||||
- name: Resolve decomplection artifact digests (the Go-only build's prebuilt inputs)
|
||||
id: artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# cloud compiles ONLY Go; it pulls three prebuilt artifacts (console SPA,
|
||||
# agent-skills catalog, native flags staticlib). Resolve each published
|
||||
# :latest to an IMMUTABLE digest so THIS release is reproducible (pinned,
|
||||
# not floating :latest) AND a console/skills/flags change is picked up —
|
||||
# its CI republished :latest, so this resolves to the NEW digest. A MISSING
|
||||
# artifact FAILS the release HERE, before build/smoke/push/tag: the receipt
|
||||
# invariant means we never tag an image that couldn't embed the real console.
|
||||
command -v crane >/dev/null 2>&1 || {
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
curl -fsSL "https://github.com/google/go-containerregistry/releases/latest/download/go-containerregistry_Linux_x86_64.tar.gz" \
|
||||
| tar -xz -C "$HOME/.local/bin" crane
|
||||
}
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
resolve() {
|
||||
local repo="$1" d
|
||||
d="$(crane digest "ghcr.io/hanzoai/${repo}:latest" 2>/dev/null || true)"
|
||||
[ -n "$d" ] || { echo "::error::decomplection artifact ghcr.io/hanzoai/${repo}:latest is not published — refusing to cut a release that would embed a stale/placeholder ${repo}"; return 1; }
|
||||
printf 'ghcr.io/hanzoai/%s@%s' "$repo" "$d"
|
||||
}
|
||||
CONSOLE_IMAGE="$(resolve console-embed)" || exit 1
|
||||
SKILLS_IMAGE="$(resolve agent-skills)" || exit 1
|
||||
FLAGS_IMAGE="$(resolve cloud-flags)" || exit 1
|
||||
{
|
||||
echo "console_image=${CONSOLE_IMAGE}"
|
||||
echo "skills_image=${SKILLS_IMAGE}"
|
||||
echo "flags_image=${FLAGS_IMAGE}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "resolved: console=${CONSOLE_IMAGE} skills=${SKILLS_IMAGE} flags=${FLAGS_IMAGE}"
|
||||
|
||||
- name: OCI labels
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
@@ -216,11 +242,13 @@ jobs:
|
||||
load: true
|
||||
tags: cloud:smoke
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
# 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.
|
||||
# cloud compiles ONLY Go: pull the three prebuilt artifacts pinned to the
|
||||
# digests resolved above (reproducible, and fresh — a console/skills/flags
|
||||
# change is a new digest). No node/python/rust toolchain in this build.
|
||||
build-args: |
|
||||
CONSOLE_CACHEBUST=${{ steps.ver.outputs.cachebust }}
|
||||
CONSOLE_IMAGE=${{ steps.artifacts.outputs.console_image }}
|
||||
SKILLS_IMAGE=${{ steps.artifacts.outputs.skills_image }}
|
||||
FLAGS_IMAGE=${{ steps.artifacts.outputs.flags_image }}
|
||||
# GIT_AUTH_TOKEN: BuildKit secret the Dockerfile consumes to fetch private
|
||||
# cross-org Go modules (hanzoai/*, luxfi/*) over authenticated git.
|
||||
secrets: |
|
||||
@@ -462,10 +490,12 @@ jobs:
|
||||
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.
|
||||
# SAME artifact digests as the smoke build → every layer is a cache hit from
|
||||
# step 1 and the pushed image is byte-identical to the one smoke proved.
|
||||
build-args: |
|
||||
CONSOLE_CACHEBUST=${{ steps.ver.outputs.cachebust }}
|
||||
CONSOLE_IMAGE=${{ steps.artifacts.outputs.console_image }}
|
||||
SKILLS_IMAGE=${{ steps.artifacts.outputs.skills_image }}
|
||||
FLAGS_IMAGE=${{ steps.artifacts.outputs.flags_image }}
|
||||
secrets: |
|
||||
GIT_AUTH_TOKEN=${{ secrets.GH_PAT }}
|
||||
|
||||
@@ -499,12 +529,25 @@ jobs:
|
||||
# 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.
|
||||
# Fail-CLOSED. An ORPHANED container tag — image pushed by a run that
|
||||
# died or was cancelled after imagetools-create but before its git tag —
|
||||
# MUST raise the floor, or a later run reassigns that same number to a
|
||||
# different image (an ambiguous mutable prod tag; the v1.801.50 flip). A
|
||||
# git-only floor can't see the orphan, so if the container-tag lookup
|
||||
# ERRORS (vs legitimately returning no tags) we retry the whole attempt
|
||||
# rather than silently proceeding — a version with a pushed image is never
|
||||
# reused. (Reordering git-tag before imagetools-create is the WRONG fix: it
|
||||
# reintroduces the phantom "tag ⇔ no image" this workflow exists to prevent.)
|
||||
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)"
|
||||
if cont_raw="$(GH_TOKEN="$GH_PAT" gh api \
|
||||
'/orgs/hanzoai/packages/container/cloud/versions?per_page=100' \
|
||||
--jq '.[].metadata.container.tags[]?' 2>/dev/null)"; then
|
||||
cont_max="$(printf '%s\n' "$cont_raw" \
|
||||
| sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1 || true)"
|
||||
else
|
||||
echo " container-tag lookup failed — retry so an orphaned tag can't be reused (attempt $attempt)"; sleep 3; continue
|
||||
fi
|
||||
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)"
|
||||
@@ -534,8 +577,12 @@ jobs:
|
||||
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"
|
||||
# Bounded: registry.hanzo.ai can *hang* (not just fail), and this
|
||||
# is best-effort — an unbounded crane copy once livelocked the whole
|
||||
# tag step and held the serialized release lane. timeout makes the
|
||||
# mirror truly best-effort so the git-tag receipt below always runs.
|
||||
timeout 120 crane copy "$SHA_IMG" "registry.hanzo.ai/hanzoai/cloud:${MT}" \
|
||||
|| echo "::warning::mirror registry.hanzo.ai/hanzoai/cloud:${MT} failed or timed out"
|
||||
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})"
|
||||
@@ -552,9 +599,86 @@ jobs:
|
||||
echo "::error::could not acquire a free version tag after 8 attempts"
|
||||
exit 1
|
||||
|
||||
# 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.
|
||||
# ── Promote: the declared-tag bump that makes the release DEPLOY ─────────────
|
||||
# The tag minted above is the receipt for a pushed, smoke-passed image; THIS job
|
||||
# records it as the desired state Hanzo CD reconciles. The universe-crs ArgoCD
|
||||
# Application (ns hanzo-cd, `automated` sync + selfHeal) syncs
|
||||
# infra/k8s/operator/crs/*.yaml → cluster and the operator rolls the Deployment,
|
||||
# so a tag bump committed here reaches api.hanzo.ai with NO hand-dispatch and NO
|
||||
# hand-edit of the CR.
|
||||
#
|
||||
# This is the SAME yq-bump → `deploy(<svc>): <tag>` universe commit the hanzoai/ci
|
||||
# reusable (build.yml deploy step) does for every other service. cloud owns it
|
||||
# HERE because its image is built by this workflow, not the ci reusable — its
|
||||
# hanzo.yml carries no main `images:` entry and `# NO deploy`, so the shared
|
||||
# deploy step never bumps cloud's CR. A direct in-cluster CR patch is NOT enough:
|
||||
# ArgoCD selfHeal reverts any live edit not also recorded in git within ~45s.
|
||||
# The retired notify-universe repository_dispatch had no receiver after the
|
||||
# image-update.yml deploy hub was deleted in the Hanzo CD cutover; the git commit
|
||||
# IS the sanctioned path now.
|
||||
promote:
|
||||
needs: build-amd64
|
||||
# Only a real release promotes: build+smoke+push+tag all succeeded, so a
|
||||
# proven v* image exists. A failure earlier leaves version_v empty → skipped.
|
||||
if: ${{ needs.build-amd64.outputs.version_v != '' }}
|
||||
runs-on: [hanzo-build-linux-amd64]
|
||||
steps:
|
||||
- name: Record the proven tag in universe crs/cloud.yaml (Hanzo CD rolls it)
|
||||
env:
|
||||
# GH_PAT already pushes this repo's git tags above (contents:write on the
|
||||
# hanzoai org), so it writes hanzoai/universe too — the SAME token the ci
|
||||
# reusable falls back to for the universe deploy commit.
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
VERSION_V: ${{ needs.build-amd64.outputs.version_v }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[ -n "${GH_PAT:-}" ] || { echo "::error::no GH_PAT — cannot record the declared-tag bump in universe"; exit 1; }
|
||||
|
||||
# Bare arc runners ship no yq — provision the static binary (sudo-free,
|
||||
# same pattern the ci reusable and this workflow's kubectl/crane fetches use).
|
||||
if ! command -v yq >/dev/null 2>&1; then
|
||||
mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
|
||||
curl -fsSL https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 \
|
||||
-o "$HOME/.local/bin/yq" && chmod +x "$HOME/.local/bin/yq"
|
||||
fi
|
||||
|
||||
git clone -q --depth 1 \
|
||||
"https://x-access-token:${GH_PAT}@github.com/hanzoai/universe.git" \
|
||||
"$RUNNER_TEMP/universe"
|
||||
CR="$RUNNER_TEMP/universe/infra/k8s/operator/crs/cloud.yaml"
|
||||
[ -f "$CR" ] || { echo "::error::crs/cloud.yaml not found in universe"; exit 1; }
|
||||
|
||||
CUR="$(yq -r '.spec.image.tag // ""' "$CR")"
|
||||
echo "cloud CR: ${CUR:-<empty>} → ${VERSION_V}"
|
||||
|
||||
# Monotonic guard: never roll the CR BACKWARD. Release runs finish under a
|
||||
# serialized lane but a slow older run must never overwrite a newer promote.
|
||||
# Skip iff the CR already holds a semver >= the version we just cut.
|
||||
CURN="${CUR#v}"; NEWN="${VERSION_V#v}"
|
||||
if printf '%s' "$CURN" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
top="$(printf '%s\n%s\n' "$CURN" "$NEWN" | sort -V | tail -1)"
|
||||
if [ "$top" = "$CURN" ] && [ "$CURN" != "$NEWN" ]; then
|
||||
echo "::notice::cloud CR already at v${CURN} (≥ ${VERSION_V}) — not rolling back"; exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
yq -i ".spec.image.tag = \"${VERSION_V}\"" "$CR"
|
||||
if git -C "$RUNNER_TEMP/universe" diff --quiet; then
|
||||
echo "::notice::crs/cloud.yaml already at ${VERSION_V} — nothing to record"; exit 0
|
||||
fi
|
||||
git -C "$RUNNER_TEMP/universe" -c user.name=hanzo-ci -c user.email=dev@hanzo.ai \
|
||||
commit -qam "deploy(cloud): ${VERSION_V} (${GITHUB_REPOSITORY}@$(echo "${GITHUB_SHA}" | cut -c1-7))"
|
||||
|
||||
# Rebase-safe push: universe main advances on every service's deploy, so a
|
||||
# concurrent commit must not make cloud's promote lose the whole roll. Retry
|
||||
# a few times, rebasing between attempts.
|
||||
for attempt in $(seq 1 5); do
|
||||
if git -C "$RUNNER_TEMP/universe" push -q origin HEAD:main; then
|
||||
echo "recorded deploy(cloud): ${VERSION_V} — Hanzo CD (universe-crs) will roll it to api.hanzo.ai"
|
||||
exit 0
|
||||
fi
|
||||
echo " universe push lost the race — rebasing (attempt ${attempt})"
|
||||
git -C "$RUNNER_TEMP/universe" pull -q --rebase origin main || true
|
||||
sleep 3
|
||||
done
|
||||
echo "::error::could not record the cloud tag bump in universe after 5 attempts"; exit 1
|
||||
|
||||
@@ -34,4 +34,5 @@ Thumbs.db
|
||||
.shots/
|
||||
|
||||
.claude/
|
||||
.worktrees/
|
||||
native/flags/target
|
||||
|
||||
@@ -6,6 +6,86 @@ artifact serves `api.hanzo.ai`, `api.lux.cloud`, `api.zoo.cloud`, `api.osage.clo
|
||||
and every white-label reseller. Brand, enabled subsystems, and org scope are
|
||||
deployment configuration.
|
||||
|
||||
## Open Cloud planes
|
||||
|
||||
Spec home: HIP-0129 `hip-0129-open-cloud-planes` (hips repo). This section is a
|
||||
map, not the spec. One noun, one owner, one route family. No plane reads another
|
||||
plane's store; imports flow custody-ward only (channels -> integrations, never
|
||||
reverse).
|
||||
|
||||
| Route | Noun | Owner | Tier |
|
||||
| --- | --- | --- | --- |
|
||||
| `/v1/connectors` | Custody: per-user BYO external accounts | `clients/integrations` (extends; user scope new) | In flight (branch `feat/connectors`) |
|
||||
| `/v1/channels` | Transport: portable message envelope, DM pairing, send + inbox | `clients/channels` (new) | Planned (branch `feat/channels` reserved; no transport code yet) |
|
||||
| `/v1/sync` | Data: bidirectional sync engine | `clients/sync` | Shipped |
|
||||
| `/v1/automations` | Workflows: flows/runs, goja piece runtime | `clients/automations` | Shipped |
|
||||
| `/v1/compute/bots` | Hosting: `@hanzo/bot` Node containers | `clients/bots` | Shipped |
|
||||
| `/v1/tasks` | Durable engine | `clients/tasks` | Shipped |
|
||||
| `/v1/gpus` + fleet | BYO GPU presence | `clients/fleet` + `clients/visor` | Shipped |
|
||||
| IAM | Identity: users, orgs, roles | IAM | Shipped |
|
||||
| KMS | Secret custody: sealed secrets | `clients/kms` | Shipped |
|
||||
|
||||
Custody invariants: secrets sealed in KMS at
|
||||
`/orgs/{org}/users/{user}/connectors/{provider}/{label}`, never in SQLite rows;
|
||||
verify before store. Refresh is single-flight with rotation resealing; the CLI
|
||||
does local browser PKCE and posts the bundle to
|
||||
`POST /v1/connectors/:provider/credential`; cloud owns device-code flows.
|
||||
|
||||
Transport invariants: typed actions (`command|url|select|approval`), no raw
|
||||
string sniffing; pairing codes 8 chars, 1h TTL, max 3 pending per account,
|
||||
owner bootstrap on first approval.
|
||||
|
||||
Container boundary is permanent for native-module, host-filesystem, loop-state,
|
||||
and vendor-Node work (agent loop, exec/PTY, harnesses, browser, voice, codecs,
|
||||
Node-bound channels, plugin SDK/loader). The Node plugin SDK is never ported to
|
||||
Go; cloud extensibility is connectors/automations/tools.
|
||||
|
||||
Port roadmap (P1-P15) lives in HIP-0129; do not restate it here. Every claim
|
||||
carries its tier: Shipped (on main, named package/route), In flight (named
|
||||
pre-main branch), Planned (backlog id or named reservation).
|
||||
|
||||
## Build & module graph — standalone module, NOT a go.work member
|
||||
|
||||
`cloud` is a self-contained deploy unit: its own `go.mod`, `Dockerfile`, binary.
|
||||
It is intentionally NOT listed in the parent `~/work/hanzo/go.work` workspace —
|
||||
that workspace deliberately excludes the heavy modules, and merging cloud's
|
||||
k8s/otel dependency tree with `o11y`'s reintroduces `koanf`/`ugorji`
|
||||
monolith-vs-split import ambiguities (the parent workspace is itself red on the
|
||||
koanf split; that is not cloud's bug to fix).
|
||||
|
||||
The catch: `go` auto-discovers that parent `go.work` whenever you run a bare
|
||||
`go build ./...` / `go test ./...` from inside this tree, which puts the build in
|
||||
workspace mode and SILENTLY DROPS cloud's own `go.mod` directives. Those
|
||||
directives are load-bearing and each fixes exactly one graph hazard:
|
||||
|
||||
- `replace github.com/vulcand/oxy/v2 => github.com/traefik/oxy/v2 <pseudo>` — the
|
||||
bare require is a placeholder (`v2.0.0-00010101000000-000000000000`); without
|
||||
the replace it resolves to an invalid version.
|
||||
- `exclude github.com/ugorji/go <old-monolith>` — drops the pre-split monolith so
|
||||
`github.com/ugorji/go/codec` (pulled by gin) is unambiguous.
|
||||
- the `k8s.io/*` staging replace block pins every staging module to the `v0.35.3`
|
||||
line. `k8s.io/kubernetes` is a GRAPH-ONLY transitive require of
|
||||
`hanzoai/deploy/gitops-engine` (clients/deploy uses its `pkg/utils/kube`); NO
|
||||
cloud package imports `k8s.io/kubernetes`, so its staging tree never compiles —
|
||||
do not "drop k8s.io/kubernetes", the pins keep the graph consistent and it is
|
||||
never built. koanf resolves to the split modules; the `koanf v1.5.0` monolith
|
||||
require is a harmless graph leaf, never imported.
|
||||
|
||||
So: build cloud in module mode, never workspace mode. `make build`/`test`/`vet`/
|
||||
`tidy` force `GOWORK=off` (matches CI and the Dockerfile, which check out cloud
|
||||
alone with no parent go.work). For a bare `go` command from this tree, prefix
|
||||
`GOWORK=off`. `GOWORK=off go build ./...` and `go vet ./...` are green; `go mod
|
||||
tidy` is stable. Do NOT commit a `go.work` here — it would flip the Dockerfile
|
||||
(`COPY go.mod go.sum` → `go mod download` → `COPY . .`) into workspace mode after
|
||||
its `-mod=readonly` download step.
|
||||
|
||||
Test modes: `make test` is pure-Go (`CGO_ENABLED=0`). Encrypted-at-rest OrgDB
|
||||
tests (`cek`, `CLOUD_KMS_MASTER_KEY_REF` set) REQUIRE `CGO_ENABLED=1` +
|
||||
libsqlcipher (`cek/cek.go` refuses to encrypt in pure-Go); those run only in the
|
||||
Dockerfile's dedicated `-tags libsqlite3` CGO stage, and fail under `make test`
|
||||
by design (clients/git, kms, flags, x402, cmd/kmsreseal, finance). Bundle-embed
|
||||
tests (clients/tasks/ui) need `make deploy-ui` first (real bundle is gitignored).
|
||||
|
||||
## Framework doctrine
|
||||
|
||||
One way to do everything. Composable, orthogonal, DRY. A new subsystem is a
|
||||
@@ -184,3 +264,39 @@ Import path (already-incorporated orgs): Google Drive → data room, a Google Sh
|
||||
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`.
|
||||
|
||||
## Deploy plane (`clients/deploy`, `/v1/deploy`)
|
||||
|
||||
Native ArgoCD-grade GitOps console over the operator-managed fleet, parallel to
|
||||
`/v1/git`: each `hanzo.ai/v1` App CR IS the Application, and the plane OBSERVES the
|
||||
operator's reconcile — `GET /v1/deploy/applications` (fleet list), `/{name}/tree`
|
||||
(ownerRef resource tree + per-node health/sync), `/{name}/resource/{ref}` (live
|
||||
manifest + desired-vs-live diff), `/{name}/logs`; `POST /{name}/rollback` pins the CR
|
||||
image to a prior semver and `/{name}/sync` requests a reconcile. SUPERADMIN-only on
|
||||
`c.IsAdmin()`, fail-closed; Secret nodes are never surfaced. `engine.go` embeds the argo
|
||||
`gitops-engine` (`hanzoai/deploy/gitops-engine` v0.7.2, no replace) in-process for the
|
||||
reconcile half behind `DEPLOY_ENGINE_ENABLED` (default off), with a prune-safety fuse.
|
||||
|
||||
## The `hanzo` CLI targets THIS binary — one contract, one IAM login
|
||||
|
||||
The `hanzo` CLI (`cli/`) is the same unified binary; its control-plane verbs speak the
|
||||
routes THIS process serves, authorized off a plain `hanzo login` (the IAM access token is
|
||||
the final bearer fallback — no `--platform-token`). The ONE contract, no TS-Dokploy drift:
|
||||
|
||||
- `hanzo apps list|get` → `GET /v1/paas/apps[/{app}]` (`clients/paas` fleet drift board)
|
||||
- `hanzo deploy <app>` → `POST /v1/paas/apps/{app}/deploy` — a zero-downtime ROLLING
|
||||
RESTART (stamps the Deployment pod-template `hanzo.ai/restartedAt` annotation; never
|
||||
changes the declared TAG — that stays a git commit CD reconciles). `--env` picks the ns.
|
||||
- `hanzo clusters list|get` → `GET /v1/clusters` (`clients/visor`, tenant-scoped)
|
||||
- `hanzo build` → `POST /v1/runner` (native buildkit fabric)
|
||||
|
||||
`/v1/paas/*` auth mirrors `/v1/runner` (`clients/platform/runner.go`): the `guard` admits a
|
||||
validated principal who is SuperAdmin OR OrgAdmin, then each handler CONFINES a non-super
|
||||
caller to the platform namespaces its own validated org owns (`scopedNamespaces`, keyed on
|
||||
`principal.Org` — a tenant admin can never observe/restart another org's, or a platform,
|
||||
app; `?org=` cannot widen it). The rolling restart needs `patch` on `apps/deployments`
|
||||
(ClusterRole/cloud, universe `infra/k8s/cloud/rbac.yaml`). There is NO `/v1/apps`,
|
||||
`/v1/org/{org}/cluster`, or `/v1/platform/projects` CLI path — the first two never existed
|
||||
here (TS-Dokploy contract, 404), and `/v1/platform/*` needs a co-resident IAM store this
|
||||
deployment does not fold in (IAM runs as a separate svc) so it 500s; the live apps backend
|
||||
is `/v1/paas`, whose board reads k8s directly with no IAM-store dependency.
|
||||
|
||||
@@ -4,6 +4,18 @@
|
||||
GO ?= go
|
||||
BIN ?= cloud
|
||||
PKG ?= ./cmd/cloud
|
||||
|
||||
# cloud is a STANDALONE Go module — a self-contained deploy unit (its own go.mod,
|
||||
# Dockerfile, binary). It is intentionally NOT a member of the parent
|
||||
# ~/work/hanzo/go.work workspace (that workspace deliberately excludes the heavy
|
||||
# modules; adding cloud would merge its k8s/otel graph with o11y's and reintroduce
|
||||
# koanf/ugorji import ambiguities). But `go` auto-discovers that parent go.work
|
||||
# whenever a dev builds from inside this tree, which shadows cloud's own
|
||||
# replace/exclude directives (oxy pin, ugorji monolith exclude, k8s staging pins)
|
||||
# and breaks `go build ./...`. Force module mode so make targets build EXACTLY
|
||||
# what CI/Docker build (fresh checkout, no parent go.work). Overridable via
|
||||
# `make GOWORK=... <target>` for the rare cross-module case.
|
||||
export GOWORK := off
|
||||
DOCKER_IMAGE ?= ghcr.io/hanzoai/cloud
|
||||
DOCKER_TAG ?= dev
|
||||
LDFLAGS ?= -s -w
|
||||
@@ -24,7 +36,7 @@ OPENAPI_DIR ?= ../openapi
|
||||
# forces the fork to modernc too so the whole binary registers "sqlite" once.
|
||||
CGO_ENABLED ?= 0
|
||||
|
||||
.PHONY: help native webui agentskills build build-standalone hanzo run smoke test test-cgo vet tidy docker docker-push clean
|
||||
.PHONY: help native webui deploy-ui 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)
|
||||
@@ -40,6 +52,17 @@ webui: ## Build the real console static bundle into webui/dist (go:embed source)
|
||||
cp -r "$(CONSOLE_DIR)/out/." webui/dist/
|
||||
@echo ">> embedded real console bundle into webui/dist (index.html $$(wc -c < webui/dist/index.html) bytes)"
|
||||
|
||||
deploy-ui: ## Build the monochrome ArgoCD dashboard bundle into clients/deploy/webui/dist (go:embed source). DEPLOY_DIR=<path to hanzoai/deploy>.
|
||||
@command -v yarn >/dev/null 2>&1 || { echo "yarn is required to build the deploy dashboard bundle"; exit 1; }
|
||||
@test -f "$(DEPLOY_DIR)/ui/package.json" || { echo "deploy checkout not found at $(DEPLOY_DIR) — set DEPLOY_DIR=<path to hanzoai/deploy on rebrand/hanzo-monochrome>"; exit 1; }
|
||||
@test -d "$(DEPLOY_DIR)/ui/node_modules" || (cd "$(DEPLOY_DIR)/ui" && yarn install --frozen-lockfile)
|
||||
cd "$(DEPLOY_DIR)/ui" && NODE_OPTIONS=--max-old-space-size=8192 yarn build
|
||||
# Overlay the fresh bundle, keeping only the tracked fallback (.gitignore +
|
||||
# index.html shell); the real 43MB bundle is build-time-only (gitignored).
|
||||
find clients/deploy/webui/dist -mindepth 1 -maxdepth 1 ! -name .gitignore -exec rm -rf {} +
|
||||
cp -r "$(DEPLOY_DIR)/ui/dist/app/." clients/deploy/webui/dist/
|
||||
@echo ">> embedded monochrome ArgoCD bundle into clients/deploy/webui/dist (index.html $$(wc -c < clients/deploy/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
|
||||
|
||||
+54
-45
@@ -34,7 +34,6 @@ package apps
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/zap-proto/zip"
|
||||
@@ -51,6 +50,7 @@ import (
|
||||
// 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/admission"
|
||||
"github.com/hanzoai/cloud/clients/ads"
|
||||
"github.com/hanzoai/cloud/clients/affiliates"
|
||||
"github.com/hanzoai/cloud/clients/agent"
|
||||
@@ -65,15 +65,17 @@ import (
|
||||
"github.com/hanzoai/cloud/clients/bots"
|
||||
"github.com/hanzoai/cloud/clients/captable"
|
||||
"github.com/hanzoai/cloud/clients/catalogsync"
|
||||
"github.com/hanzoai/cloud/clients/channels"
|
||||
"github.com/hanzoai/cloud/clients/cloudflare"
|
||||
"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/dns"
|
||||
"github.com/hanzoai/cloud/clients/do"
|
||||
"github.com/hanzoai/cloud/clients/domain"
|
||||
"github.com/hanzoai/cloud/clients/entitlements"
|
||||
"github.com/hanzoai/cloud/clients/eval"
|
||||
"github.com/hanzoai/cloud/clients/exec"
|
||||
@@ -85,7 +87,6 @@ import (
|
||||
"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"
|
||||
@@ -108,6 +109,7 @@ import (
|
||||
"github.com/hanzoai/cloud/clients/provisioning"
|
||||
"github.com/hanzoai/cloud/clients/pubsub"
|
||||
"github.com/hanzoai/cloud/clients/referrals"
|
||||
"github.com/hanzoai/cloud/clients/rollingcap"
|
||||
"github.com/hanzoai/cloud/clients/runtime"
|
||||
"github.com/hanzoai/cloud/clients/sbom"
|
||||
"github.com/hanzoai/cloud/clients/security"
|
||||
@@ -123,6 +125,7 @@ import (
|
||||
"github.com/hanzoai/cloud/clients/tracker"
|
||||
"github.com/hanzoai/cloud/clients/treasury"
|
||||
"github.com/hanzoai/cloud/clients/usage"
|
||||
"github.com/hanzoai/cloud/clients/validators"
|
||||
"github.com/hanzoai/cloud/clients/visor"
|
||||
"github.com/hanzoai/cloud/clients/wallets"
|
||||
"github.com/hanzoai/cloud/clients/websearch"
|
||||
@@ -163,22 +166,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
// 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).
|
||||
@@ -210,15 +197,12 @@ func Wire() []cloud.MountSpec {
|
||||
// /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 IAM identity plane (/v1/iam/*, /login/oauth/*) — the identity authority,
|
||||
// mounts before its dependents. The ONE implementation: the clean-room iam-v2
|
||||
// (zip-native + hanzoai/orm, beego-free); the retired Casdoor iam-v1 embed is GONE.
|
||||
// STAGED: the operator adds "iam" to --enable only after IAM config + the fold are
|
||||
// verified (login/authorize/token/jwks + the operator SSO chain).
|
||||
{Name: "iam", Mount: iam.Mount},
|
||||
// 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},
|
||||
@@ -236,7 +220,10 @@ func Wire() []cloud.MountSpec {
|
||||
// CommerceClient is wired directly in pickCommerceClient).
|
||||
{Name: "commerce", Mount: mountCommerce},
|
||||
{Name: "licensing", Mount: licensing.Mount},
|
||||
{Name: "plans", Mount: plan.Mount, OwnsHealth: true},
|
||||
// clients/plan.Mount. Enable id normalized "plans" -> "plan" to match the
|
||||
// package + generated cmd/plan (one subsystem, one name). Its product routes
|
||||
// stay /v1/plans/* (incl. the OwnsHealth /v1/plans/health probe) — unchanged.
|
||||
{Name: "plan", 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).
|
||||
@@ -244,12 +231,22 @@ func Wire() []cloud.MountSpec {
|
||||
// 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},
|
||||
// Rolling AI-spend cap: installs the ai gate's per-tier trailing-window cap
|
||||
// reader (registers no routes; its admin-editable knobs are platform switches
|
||||
// surfaced in the /v1/admin/flags cockpit). After commerce/plan so the tier +
|
||||
// finance globals it composes are wired.
|
||||
{Name: "rollingcap", Mount: rollingcap.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},
|
||||
// The /v1/dns forward head: relays the console DNS dashboard to the DNS
|
||||
// control plane under the caller's own validated bearer (clients/dns).
|
||||
{Name: "dns", Mount: dns.Mount},
|
||||
// The registrar: search/price/register domains (name.com) per org.
|
||||
{Name: "domain", Mount: domain.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
|
||||
@@ -293,6 +290,11 @@ func Wire() []cloud.MountSpec {
|
||||
// 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)},
|
||||
// GDA/SDM validator onboarding /v1/validators/* — wallet-sig + ETH-mainnet
|
||||
// GenesisNFT ownerOf → seal luxd staking identity into KMS → write a NEW-node
|
||||
// LuxNetwork CR (node.lux.cloud, never the live luxd) → enqueue an owner-gated
|
||||
// registration (never auto-submitted to any P-Chain). Owns a DB handle.
|
||||
{Name: "validators", Mount: validators.Mount, Shutdown: ctxShutdown(validators.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
|
||||
@@ -314,10 +316,16 @@ func Wire() []cloud.MountSpec {
|
||||
{Name: "graph", Mount: graph.Mount},
|
||||
{Name: "security", Mount: security.Mount, Shutdown: ctxShutdown(security.Shutdown), OwnsHealth: true},
|
||||
{Name: "integrations", Mount: integrations.Mount, Shutdown: integrations.Shutdown},
|
||||
// Per-org Cloudflare asset plane /v1/integrations/cloudflare/{pages,workers,r2,kv,d1}/*.
|
||||
// Mounts AFTER integrations because it reads the org's Cloudflare token through
|
||||
// the integrations custody seam (integrations.TokenFor) — one token, one
|
||||
// custody boundary. Stateless: no store, no shutdown.
|
||||
{Name: "cloudflare", Mount: cloudflare.Mount},
|
||||
{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: "channels", Mount: channels.Mount, Shutdown: channels.Shutdown},
|
||||
{Name: "gateway", Mount: gateway.Mount},
|
||||
{Name: "entitlements", Mount: entitlements.Mount, Shutdown: entitlements.Shutdown},
|
||||
{Name: "exec", Mount: exec.Mount},
|
||||
@@ -336,23 +344,24 @@ func Wire() []cloud.MountSpec {
|
||||
{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.
|
||||
// Launch-control gate (per-service waitlist): the COMPLETE feature — host→service
|
||||
// registry + brand seed + the waitlist.<svc> switch registration + the
|
||||
// /v1/flags/waitlist (and /v1/admission/mode compat) mode read + the Enforce
|
||||
// middleware — COMPOSING the flags engine one-way (flags.Bool/Register/
|
||||
// SetPlatformSwitch; flags never imports admission). Mounts AFTER flags so the
|
||||
// engine's platform-switch plane is installed first; the admin board is the
|
||||
// /v1/admin/services lens over it. Owns the registry store handle → Shutdown.
|
||||
{Name: "admission", Mount: admission.Mount, Shutdown: ctxShutdown(admission.Shutdown)},
|
||||
// Tasks: the durable workflow/UI surface AND platform cron (durable schedules
|
||||
// on the same shared engine, replacing every k8s CronJob). cron was a separate
|
||||
// Wire entry; it mounts no routes and only registers schedules, so it is folded
|
||||
// in as a sub-mount of tasks.Mount — ONE tasks subsystem.
|
||||
{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},
|
||||
// Automations: the connector catalogue + flow engine AND native single-connector
|
||||
// execution (POST /v1/automations/connectors/:id/run, HIP-0126). The connector
|
||||
// runner mounts no other routes, so it is folded in as a sub-mount of
|
||||
// automations.Mount (was a separate "connectorruntime" entry) — ONE subsystem.
|
||||
{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
|
||||
|
||||
@@ -21,15 +21,21 @@ import (
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
accountclient "github.com/hanzoai/cloud/clients/account"
|
||||
"github.com/hanzoai/cloud/clients/commerceclient"
|
||||
"github.com/hanzoai/cloud/clients/commerceinproc"
|
||||
financeclient "github.com/hanzoai/cloud/clients/finance"
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/hanzoai/commerce"
|
||||
commercebilling "github.com/hanzoai/commerce/api/billing"
|
||||
commercestore "github.com/hanzoai/commerce/api/store"
|
||||
commercedatastore "github.com/hanzoai/commerce/datastore"
|
||||
commercemid "github.com/hanzoai/commerce/middleware"
|
||||
"github.com/hanzoai/commerce/middleware/iammiddleware"
|
||||
commercensctx "github.com/hanzoai/commerce/util/nscontext"
|
||||
log "github.com/luxfi/log"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
@@ -156,6 +162,121 @@ func mountCommerce(app *zip.App, deps cloud.Deps) error {
|
||||
commercebilling.RunAutoRechargeAllOrgs,
|
||||
)
|
||||
|
||||
// GET /v1/billing/plans — the public tier catalog the console renders. commerce's
|
||||
// legacy api.Route() billing bundle (ListPlans, invoices, subscriptions, …) is NOT
|
||||
// registered by the co-resident embed: setupRoutes wires only /v1/commerce/*, so
|
||||
// /v1/billing/plans has NO handler in this binary. The account bridge's
|
||||
// /v1/billing/* wildcard (order 122) then forwards the read BACK to commerce at
|
||||
// COMMERCE_URL — which defaults to the public api.hanzo.ai edge — re-entering the
|
||||
// same bridge in an unbounded self-dispatch loop that surfaces as a 502
|
||||
// ("commerce unreachable: Get https://api.hanzo.ai/v1/billing/plans"). Registering
|
||||
// the static ListPlans handler HERE (order 100, ahead of the bridge) shadows that
|
||||
// wildcard and serves plans in-process — the same co-resident move billing.go makes
|
||||
// for usage/balance. RequestContext supplies the namespaced context promo.Active reads.
|
||||
app.Get("/v1/billing/plans", commercemid.RequestContext(), commercebilling.ListPlans)
|
||||
|
||||
// The rest of the console's billing READS, served co-resident for the SAME reason
|
||||
// plans is: commerce's api.Route() billing bundle is never compiled here, so without
|
||||
// these registrations every one of them falls through to the account bridge's
|
||||
// /v1/billing/* wildcard, which forwards to COMMERCE_URL — the public api.hanzo.ai
|
||||
// edge, which is THIS binary — and self-dispatches into a 502 loop. In prod there is
|
||||
// no separate commerce backend to point COMMERCE_URL at (the in-cluster `commerce`
|
||||
// Service selects the cloud pods), so co-residence is the only way to break the loop.
|
||||
//
|
||||
// Chain: RequestContext (gated context) → IAMTokenRequired (resolves the org from the
|
||||
// gateway-validated X-Org-Id into Locals("organization"), the namespace commerce's
|
||||
// GetOrganization reads) → PinBillingSubject (pins the caller's OWN billing subject
|
||||
// into the query — the SAME isolation the bridge applies, so a read can never widen
|
||||
// past the caller; fail-closed for an unvalidated caller) → the commerce handler. The
|
||||
// specific paths shadow the bridge wildcard (order 100 < 122). payment-config is
|
||||
// org-scoped, not subject-scoped, but PinBillingSubject is still the auth gate that
|
||||
// keeps an unvalidated caller from reaching GetOrganization; its pinned (unused)
|
||||
// subject params are ignored by that handler.
|
||||
billingRead := []struct {
|
||||
path string
|
||||
h zip.Handler
|
||||
}{
|
||||
{"/v1/billing/invoices", commercebilling.ListInvoices},
|
||||
{"/v1/billing/invoices/:id/pdf", commercebilling.DownloadInvoicePDF},
|
||||
{"/v1/billing/subscriptions", commercebilling.ListBillingSubscriptions},
|
||||
{"/v1/billing/spend-alerts", commercebilling.ListSpendAlerts},
|
||||
{"/v1/billing/payouts", commercebilling.ListPayouts},
|
||||
{"/v1/billing/payment-config", commercebilling.GetPaymentConfig},
|
||||
}
|
||||
for _, r := range billingRead {
|
||||
app.Get(r.path,
|
||||
commercemid.RequestContext(),
|
||||
iammiddleware.IAMTokenRequired(),
|
||||
accountclient.PinBillingSubject(),
|
||||
r.h,
|
||||
)
|
||||
}
|
||||
|
||||
// GET /v1/billing/spend-alerts/authorize — the per-request per-scope spend-CAP
|
||||
// VERDICT the request-edge metering gate consumes (clients/metering scopeAuthorize,
|
||||
// pathLimitsAuthorize). It is a SERVICE-token S2S read (COMMERCE_SERVICE_TOKEN +
|
||||
// X-Org-Id), NOT a browser/IAM read — so it needs its OWN registration, distinct from
|
||||
// the console billingRead block above: without a co-resident handler this authorize
|
||||
// fell through to the account bridge's /v1/billing/* wildcard (order 122), which — being
|
||||
// service-token-forwardable (billing.go billingForwardable) — re-forwarded it to
|
||||
// COMMERCE_URL (the public api.hanzo.ai edge = THIS binary) over commerceinproc's
|
||||
// self-routing transport, re-entering the same wildcard until the depth-8 guard refused
|
||||
// → 502 → the gate fails OPEN (the cap is a policy overlay, so no traffic was blocked,
|
||||
// but ~135 502s/30m spammed the money path and each burned 8 full-app dispatches). The
|
||||
// plain GET /v1/billing/spend-alerts (registered above) already broke this loop for the
|
||||
// CRUD read; this closes the /authorize sibling the metering gate hits on every call.
|
||||
//
|
||||
// Chain mirrors commerce's OWN gate on this route (api/billing/handlers.go: the `billing`
|
||||
// group's userRequired = TokenRequired) plus the RequestContext the standalone supplies
|
||||
// globally — NOT the IAM/PinBillingSubject console chain: a raw service token is not an
|
||||
// IAM JWT, so IAMTokenRequired would leave GetOrganization unset and AuthorizeSpendCap
|
||||
// would 500. TokenRequired authenticates the service token AND resolves the tenant from
|
||||
// the gateway-pinned X-Org-Id into Locals("organization"), which AuthorizeSpendCap reads.
|
||||
// The specific route shadows the bridge wildcard (order 100 < 122). No PlatformOnly:
|
||||
// authorize is a per-org cap read, not a cross-org mint (unlike auto-recharge/run-all).
|
||||
app.Get("/v1/billing/spend-alerts/authorize",
|
||||
commercemid.RequestContext(),
|
||||
commercemid.TokenRequired(),
|
||||
commercebilling.AuthorizeSpendCap,
|
||||
)
|
||||
|
||||
// Self-service spend-cap CRUD WRITES — the customer half of the cap: a customer
|
||||
// (or the admin S2S) CREATES / EDITS / REMOVES their own usage caps. These are the
|
||||
// write siblings of the co-resident GET /v1/billing/spend-alerts list; without their
|
||||
// own registration they too fell through the account bridge's /v1/billing/* wildcard
|
||||
// (billingForwardable includes POST spend-alerts) into the SAME 502 self-dispatch loop
|
||||
// authorize hit — so a customer could not set a cap AT ALL in the unified binary
|
||||
// (POST/PATCH/DELETE all 502'd). Same chain commerce's own route table gates them with
|
||||
// (api/billing/handlers.go:322-325, the `user` group's userRequired = TokenRequired) +
|
||||
// the global RequestContext — an IAM JWT OR the COMMERCE_SERVICE_TOKEN, org resolved
|
||||
// from the gateway-pinned X-Org-Id into Locals("organization"). Org-scoped by that
|
||||
// namespace (a caller only ever writes their OWN org's caps; a foreign :id is a
|
||||
// not-found miss in the caller's namespace), so no PinBillingSubject — spend-alerts are
|
||||
// org-level, not billing-subject-level. Shadow the bridge wildcard (order 100 < 122).
|
||||
// A spend cap is a FINANCIAL SAFETY control, so its writes are gated to an ORG ADMIN
|
||||
// (or SuperAdmin, or the trusted S2S service token for the SuperAdmin cap-oversight
|
||||
// Forward) — never any authenticated member. commerce's own `user` group admits any
|
||||
// member, which would let a compromised member key DELETE the org's cap (→ unbounded
|
||||
// spend) or POST a 1¢ enforce cap (→ org-wide 402 DoS). requireSpendCapAdmin closes that.
|
||||
app.Post("/v1/billing/spend-alerts",
|
||||
commercemid.RequestContext(),
|
||||
commercemid.TokenRequired(),
|
||||
requireSpendCapAdmin(),
|
||||
commercebilling.CreateSpendAlert,
|
||||
)
|
||||
app.Patch("/v1/billing/spend-alerts/:id",
|
||||
commercemid.RequestContext(),
|
||||
commercemid.TokenRequired(),
|
||||
requireSpendCapAdmin(),
|
||||
commercebilling.UpdateSpendAlert,
|
||||
)
|
||||
app.Delete("/v1/billing/spend-alerts/:id",
|
||||
commercemid.RequestContext(),
|
||||
commercemid.TokenRequired(),
|
||||
requireSpendCapAdmin(),
|
||||
commercebilling.DeleteSpendAlert,
|
||||
)
|
||||
|
||||
// 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.
|
||||
@@ -164,6 +285,19 @@ func mountCommerce(app *zip.App, deps cloud.Deps) error {
|
||||
commerceinproc.SetApp(app)
|
||||
commerceclient.PublishEmbedded(embedded)
|
||||
|
||||
// Usage-cap enforcement on the FINANCE path. The unified binary records usage in
|
||||
// the finance ledger (fin.RecordUsage), NOT commerce's transaction store — which
|
||||
// it leaves empty — so the cap must read spend from, and fire alerts on, the
|
||||
// finance ledger. Two seams, both org-wide (the finance Entry carries no scope;
|
||||
// per-scope caps are a follow-up):
|
||||
// - SetPeriodSpendReader: AuthorizeSpendCap's scopeSpentCents reads the org's
|
||||
// finance period spend instead of the empty commerce transaction ledger, so
|
||||
// a real LLM request increments the cap's `spent` and trips the 402.
|
||||
// - SetUsageHook: after each finance debit, fire the org's spend-alerts on the
|
||||
// SAME crossing (the alert half), reading the same finance spend + debouncing.
|
||||
commercebilling.SetPeriodSpendReader(financePeriodSpend)
|
||||
financeclient.SetUsageHook(fireCapAlert)
|
||||
|
||||
lg.Info("commerce embedded natively (hanzoai/commerce module on the shared zip app)",
|
||||
"data_dir", dataDir,
|
||||
"brand", deps.Brand,
|
||||
@@ -215,3 +349,57 @@ func mountCommerceFailClosed(app *zip.App) {
|
||||
app.All(p+"/*", failed)
|
||||
}
|
||||
}
|
||||
|
||||
// financePeriodSpend is the usage-cap's period-spend source (injected into commerce
|
||||
// via SetPeriodSpendReader). It returns the org's finance-ledger usage in cents since
|
||||
// the start of the CURRENT UTC month — the window the cap resets on (mirrors
|
||||
// commerce periodStartUTC). Org-wide: the finance Entry carries no project/service,
|
||||
// so scope args are ignored and the org total is returned (what the covering
|
||||
// org-wide spend-alert row binds on). A finance impl without the sum capability, or a
|
||||
// split deploy (no co-resident finance), reports 0 — the cap can never over-count.
|
||||
func financePeriodSpend(ctx context.Context, org string, test bool, _, _ string) (int64, error) {
|
||||
fin := financeclient.Current()
|
||||
if fin == nil {
|
||||
return 0, nil
|
||||
}
|
||||
summer, ok := fin.(interface {
|
||||
SumUsageSince(context.Context, string, bool, int64) (int64, error)
|
||||
})
|
||||
if !ok {
|
||||
return 0, nil
|
||||
}
|
||||
n := time.Now().UTC()
|
||||
since := time.Date(n.Year(), n.Month(), 1, 0, 0, 0, 0, time.UTC).Unix()
|
||||
return summer.SumUsageSince(ctx, org, test, since)
|
||||
}
|
||||
|
||||
// fireCapAlert fires the org's spend-alerts after a finance usage debit — the alert
|
||||
// half of the cap on the finance path (wired via finance.SetUsageHook). It resolves
|
||||
// the org's commerce datastore (where the spend-alert rows live) and calls the
|
||||
// exported commerce trigger, which reads the org's period spend via financePeriodSpend
|
||||
// and stamps/debounces. Detached + best-effort; never blocks the money path. Runs in
|
||||
// its own goroutine (the hook is invoked with `go`), so a background context is right.
|
||||
func fireCapAlert(org string, test bool, project, service string) {
|
||||
if strings.TrimSpace(org) == "" {
|
||||
return
|
||||
}
|
||||
ctx := commercensctx.WithNamespace(context.Background(), org)
|
||||
db := commercedatastore.New(ctx)
|
||||
commercebilling.FireSpendAlerts(ctx, db, org, test, project, service, nil)
|
||||
}
|
||||
|
||||
// requireSpendCapAdmin gates a spend-alert WRITE to a validated ORG ADMIN or platform
|
||||
// SuperAdmin (the unforgeable SanitizeIdentity-minted X-User-IsOrgAdmin / isAdmin bits),
|
||||
// OR the trusted in-proc S2S service token (the SuperAdmin cap-oversight Forward + internal
|
||||
// automation). A validated non-admin MEMBER is REFUSED (403): a spend cap is a financial
|
||||
// safety boundary — a member must not be able to delete the org's cap (→ unbounded spend)
|
||||
// or set a punitive 1¢ cap (→ org-wide 402 DoS). The read paths (list/authorize) stay
|
||||
// member/S2S-open; only the mutations require admin.
|
||||
func requireSpendCapAdmin() zip.Handler {
|
||||
return func(c *zip.Ctx) error {
|
||||
if principal.IsSuperAdmin(c) || principal.IsOrgAdmin(c) || accountclient.IsServiceToken(c) {
|
||||
return c.Next()
|
||||
}
|
||||
return zip.ErrForbidden("org admin required to change spend caps")
|
||||
}
|
||||
}
|
||||
|
||||
+91
-86
@@ -23,92 +23,97 @@ var frozen = []struct {
|
||||
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
|
||||
{"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
|
||||
{"plan", true, false}, // was order 111; enable id normalized plans->plan (routes stay /v1/plans/*)
|
||||
{"pricing", true, false}, // was order 112
|
||||
{"storage", true, false}, // was order 118
|
||||
{"provisioning", false, false}, // was order 120
|
||||
{"billing", false, false}, // was order 121
|
||||
{"rollingcap", false, false}, // rolling spend-cap gate (after billing); golden drifted — refrozen
|
||||
{"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
|
||||
{"dns", false, false}, // new: /v1/dns zone plane (after projects)
|
||||
{"domain", false, false}, // new: Hanzo Domains registrar (/v1/domain), after dns
|
||||
{"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)
|
||||
{"validators", false, true}, // new: NFT-gated node provisioning (after ads); golden refrozen
|
||||
{"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
|
||||
{"cloudflare", false, false}, // new: /v1/cloudflare edge plane (after integrations)
|
||||
{"sbom", true, false}, // was order 137
|
||||
{"team", false, true}, // was order 138
|
||||
{"settings", false, true}, // was order 138
|
||||
{"notify", true, false}, // was order 139
|
||||
{"channels", false, true}, // new: /v1/channels transport plane (after notify; must mount after integrations so RegisterIngress installs before webhooks emit)
|
||||
{"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
|
||||
{"admission", false, true}, // launch-control gate: composes flags (registry+seed+mode route+Enforce); Shutdown closes the registry store
|
||||
{"tasks", false, false}, // was order 147; platform cron folded in as a sub-mount of tasks.Mount (was a separate entry)
|
||||
{"automations", false, true}, // was order 148; connectorruntime (POST /v1/automations/connectors/:id/run) folded in as a sub-mount of automations.Mount
|
||||
{"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
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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_AcceptsHanzoTeam pins the hanzo.team OIDC client. IAM mints
|
||||
// team's access tokens with aud=hanzo-team (each app's aud is its client_id);
|
||||
// the team OAuth callback sets that token as the hanzo_iam_token cookie, and
|
||||
// the usage/wallet page (/v1/team/billing/ui/) reads /v1/billing/balance +
|
||||
// /v1/usage/summary same-origin on it. If hanzo-team is not accepted the
|
||||
// cookie resolves anonymous and every wallet read 401s — and the callback's
|
||||
// own validator (NewTokenValidator shares this allowlist) refuses the login.
|
||||
func TestJWTAudiences_AcceptsHanzoTeam(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-team") {
|
||||
t.Fatalf("defaultJWTAudiences must include hanzo-team (the hanzo.team client_id); got %v", defaultJWTAudiences)
|
||||
}
|
||||
if !has(jwtAudiencesFromEnv(), "hanzo-team") {
|
||||
t.Fatalf("resolved JWT audiences must include hanzo-team; got %v", jwtAudiencesFromEnv())
|
||||
}
|
||||
}
|
||||
+50
-4
@@ -37,10 +37,10 @@ type keyResolver interface {
|
||||
// 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]
|
||||
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
|
||||
@@ -55,6 +55,52 @@ func newIAMKeys() *iamKeys {
|
||||
}
|
||||
}
|
||||
|
||||
// sharedKeys memoizes ONE API-key resolver (and its 60s cache) for the whole
|
||||
// binary. The identity boundary (SanitizeIdentity, via newIdentityValidator) and
|
||||
// any subsystem that must resolve a key OUT-OF-BAND of the Authorization header
|
||||
// (analytics capture: a project key posted in the SDK body/query) both go through
|
||||
// this ONE seam, so a key resolves to the SAME org either way and IAM sees one
|
||||
// warm cache — never a second, drifting resolver.
|
||||
var (
|
||||
sharedKeysOnce sync.Once
|
||||
sharedKeysInst *iamKeys
|
||||
)
|
||||
|
||||
func sharedKeys() *iamKeys {
|
||||
sharedKeysOnce.Do(func() { sharedKeysInst = newIAMKeys() })
|
||||
return sharedKeysInst
|
||||
}
|
||||
|
||||
// maxKeyOrgLen bounds a resolved org key the same way principal.MaxOrgLen does: the
|
||||
// org becomes a warehouse partition key, so an over-long value (malformed / hostile)
|
||||
// is refused rather than stored.
|
||||
const maxKeyOrgLen = 128
|
||||
|
||||
// OrgForKey resolves an opaque Hanzo API key (hk-/sk-/pk-/fw_/hz_) to the org it
|
||||
// belongs to — the SAME owner org SanitizeIdentity mints when that key arrives as a
|
||||
// bearer — through the ONE IAM key seam (get-user?accessKey). It is the exported
|
||||
// door a keyed, bearer-less SDK path uses to attribute a project key to a tenant.
|
||||
//
|
||||
// FAILS CLOSED: ("", false) for a non-key-shaped string, an unknown/unresolvable
|
||||
// key, an unconfigured resolver, or an out-of-bounds org — never a fabricated or
|
||||
// default tenant, so a bad key can never be written into another org's partition.
|
||||
// The isAPIKey prefix gate keeps garbage strings off the IAM network path.
|
||||
func OrgForKey(ctx context.Context, key string) (string, bool) {
|
||||
key = strings.TrimSpace(key)
|
||||
if !isAPIKey(key) {
|
||||
return "", false
|
||||
}
|
||||
claims := sharedKeys().resolve(ctx, key)
|
||||
if claims == nil {
|
||||
return "", false
|
||||
}
|
||||
owner := strings.TrimSpace(claims.Owner)
|
||||
if owner == "" || len(owner) > maxKeyOrgLen {
|
||||
return "", false
|
||||
}
|
||||
return owner, true
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
+44
-21
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/go-jose/go-jose/v4/jwt"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
model "github.com/hanzoai/iam/pkg/model"
|
||||
)
|
||||
|
||||
// idClaims is the subset of Hanzo IAM JWT claims the identity sanitizer needs.
|
||||
@@ -40,12 +41,14 @@ import (
|
||||
type idClaims struct {
|
||||
jwt.Claims
|
||||
|
||||
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"`
|
||||
Owner string `json:"owner"` // org slug (the org)
|
||||
Project string `json:"project"` // org SUB-SCOPE within owner (empty ⟹ default project)
|
||||
BillingAccount string `json:"billing_account"` // WHO PAYS, stated by IAM (empty ⟹ pre-claim token)
|
||||
Name string `json:"name"` // display name (id fallback)
|
||||
PreferredUsername string `json:"preferred_username"` // id fallback
|
||||
Email string `json:"email"`
|
||||
IsAdmin bool `json:"isAdmin"`
|
||||
Orgs []model.OrgRef `json:"orgs"` // membership SET (home first); empty on legacy tokens
|
||||
}
|
||||
|
||||
// mintedProject returns the project id to stamp into X-Project-Id, or "" when the
|
||||
@@ -62,6 +65,20 @@ func (c *idClaims) mintedProject() string {
|
||||
return strings.TrimSpace(c.Project)
|
||||
}
|
||||
|
||||
// mintedBillingAccount returns the funding account to stamp into
|
||||
// X-Billing-Account-Id, or "" when the header must be OMITTED (a token minted
|
||||
// before IAM shipped the claim, or one IAM could not attribute).
|
||||
//
|
||||
// WHO PAYS IS NOT A CLIENT'S TO NAME. This rides the validated `billing_account`
|
||||
// claim — IAM's signed statement, resolved at the identity boundary from the real
|
||||
// grant context — exactly like `owner` and `project`. It mirrors the edge
|
||||
// (iamauth.Claims.MintedBillingAccount) byte-for-byte, so the in-binary path binds
|
||||
// the same header the gateway would, and ai/object.Payer reads the same payer on
|
||||
// both. The raw client copy is deleted on ingress and NEVER restored.
|
||||
func (c *idClaims) mintedBillingAccount() string {
|
||||
return strings.TrimSpace(c.BillingAccount)
|
||||
}
|
||||
|
||||
// userID resolves the canonical user id: sub, then preferred_username, then
|
||||
// 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.
|
||||
@@ -123,7 +140,7 @@ func newIdentityValidator(issuer, jwksURL string, audiences []string, ttl time.D
|
||||
issuers: trustedIssuers(issuer),
|
||||
audiences: audiences,
|
||||
cache: newJWKSCache(jwksURL, ttl),
|
||||
keys: newIAMKeys(),
|
||||
keys: sharedKeys(), // ONE resolver+cache, shared with OrgForKey (analytics capture)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +214,16 @@ func (v *identityValidator) validate(raw string) (*idClaims, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Fail SECURE on a misconfigured (empty) trust set: an empty issuer OR audience
|
||||
// allowlist must REJECT every token, never silently disable that axis. In
|
||||
// production both are always resolved non-empty (BrandIssuers + the baked
|
||||
// audience defaults, unioned in config.go so they are "never empty"), so this
|
||||
// fires ONLY on an operator misconfiguration (CLOUD_JWT_AUDIENCES="" emptying the
|
||||
// resolved set, or an empty issuer set) — and then it denies, it never admits (I2).
|
||||
if len(v.issuers) == 0 || len(v.audiences) == 0 {
|
||||
return nil, fmt.Errorf("identity validator misconfigured: empty issuer or audience allowlist")
|
||||
}
|
||||
|
||||
// Reject a missing issuer: an empty issuer must never pass the set check.
|
||||
if claims.Issuer == "" {
|
||||
return nil, fmt.Errorf("missing issuer")
|
||||
@@ -221,14 +248,13 @@ func (v *identityValidator) validate(raw string) (*idClaims, error) {
|
||||
// gates on owner == :org. Without this, a real client_credentials machine token
|
||||
// (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 {
|
||||
auds := v.audiences
|
||||
if mach := kmsMachineAudience(claims.Owner); mach != "" {
|
||||
auds = append(append(make([]string, 0, len(v.audiences)+1), v.audiences...), mach)
|
||||
}
|
||||
expected.AnyAudience = jwt.Audience(auds)
|
||||
// The audience allowlist is guaranteed non-empty (checked above), so the
|
||||
// audience axis is ALWAYS enforced — never silently skipped.
|
||||
auds := v.audiences
|
||||
if mach := kmsMachineAudience(claims.Owner); mach != "" {
|
||||
auds = append(append(make([]string, 0, len(v.audiences)+1), v.audiences...), mach)
|
||||
}
|
||||
expected := jwt.Expected{AnyAudience: jwt.Audience(auds)}
|
||||
if err := claims.Claims.ValidateWithLeeway(expected, 2*time.Minute); err != nil {
|
||||
return nil, fmt.Errorf("claims: %w", err)
|
||||
}
|
||||
@@ -425,14 +451,11 @@ func trustedIssuers(primary string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// issuerAllowed reports whether iss is one of the trusted issuers. An empty set
|
||||
// (no primary, no brands — never the case in production) skips the check, matching
|
||||
// the prior "empty issuer disables the check" behavior; a non-empty set is
|
||||
// fail-secure (a token whose iss is not in the set is rejected).
|
||||
// issuerAllowed reports whether iss is one of the trusted issuers. It is
|
||||
// fail-secure in BOTH directions: an empty trusted set matches NOTHING (deny), so
|
||||
// a misconfiguration that empties the issuer allowlist rejects every token instead
|
||||
// of silently disabling the check (I2); a non-empty set rejects any iss not in it.
|
||||
func issuerAllowed(iss string, trusted []string) bool {
|
||||
if len(trusted) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, t := range trusted {
|
||||
if iss == t {
|
||||
return true
|
||||
|
||||
@@ -1,10 +1,45 @@
|
||||
package cloud
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestValidate_FailSecureOnEmptyTrustSet proves I2: a validator whose resolved
|
||||
// issuer OR audience allowlist is empty REJECTS an otherwise-valid, correctly
|
||||
// signed token — the axis is never silently disabled. Production always resolves
|
||||
// non-empty sets; this guards the misconfiguration path (CLOUD_JWT_AUDIENCES=""
|
||||
// or an empty issuer set), which must fail closed, not open.
|
||||
func TestValidate_FailSecureOnEmptyTrustSet(t *testing.T) {
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("genkey: %v", err)
|
||||
}
|
||||
jwks := jwksServer(t, &key.PublicKey)
|
||||
future := time.Now().Add(time.Hour)
|
||||
tok := signWith(t, key, tokenClaims("hanzo-console", "acme", "", false, future))
|
||||
|
||||
// Sanity: a properly configured validator accepts the token.
|
||||
if _, err := newIdentityValidator(testIssuer, jwks.URL, []string{"hanzo-console"}, 0).validate(tok); err != nil {
|
||||
t.Fatalf("baseline valid token must be accepted, got %v", err)
|
||||
}
|
||||
|
||||
// Empty audience set → deny.
|
||||
if _, err := newIdentityValidator(testIssuer, jwks.URL, nil, 0).validate(tok); err == nil {
|
||||
t.Error("empty audience allowlist must REJECT (fail-secure), not accept")
|
||||
}
|
||||
|
||||
// Empty issuer set → deny (construct directly; trustedIssuers never yields empty
|
||||
// with a primary, so bypass it to exercise the guard).
|
||||
vEmptyIss := &identityValidator{issuers: nil, audiences: []string{"hanzo-console"}, cache: newJWKSCache(jwks.URL, 0), keys: newIAMKeys()}
|
||||
if _, err := vEmptyIss.validate(tok); err == nil {
|
||||
t.Error("empty issuer allowlist must REJECT (fail-secure), not accept")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrustedIssuers_WhiteLabel proves the in-binary validator's trusted-issuer
|
||||
// set is the primary issuer UNIONED with every white-label brand issuer plus the
|
||||
// WHITELABEL_ISSUERS override, deduped, primary-first.
|
||||
@@ -40,7 +75,8 @@ func TestTrustedIssuers_WhiteLabel(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestIssuerAllowed proves the set membership check: brand issuers pass, an
|
||||
// outsider is rejected, and an empty set (never in prod) skips the check.
|
||||
// outsider is rejected, and an empty set is fail-secure — it matches NOTHING (I2),
|
||||
// so a misconfiguration that empties the allowlist denies every token.
|
||||
func TestIssuerAllowed(t *testing.T) {
|
||||
set := []string{"https://hanzo.id", "https://lux.id"}
|
||||
if !issuerAllowed("https://lux.id", set) {
|
||||
@@ -49,8 +85,8 @@ func TestIssuerAllowed(t *testing.T) {
|
||||
if issuerAllowed("https://attacker.id", set) {
|
||||
t.Error("attacker.id must be rejected")
|
||||
}
|
||||
if !issuerAllowed("anything", nil) {
|
||||
t.Error("empty set must skip the check (matches prior empty-issuer behavior)")
|
||||
if issuerAllowed("anything", nil) {
|
||||
t.Error("empty set must DENY (fail-secure), never skip the check")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
"github.com/hanzoai/cloud/clients"
|
||||
"github.com/hanzoai/cloud/clients/finance"
|
||||
"github.com/hanzoai/cloud/clients/gatewaypolicy"
|
||||
"github.com/hanzoai/cloud/clients/gateway/edge"
|
||||
"github.com/hanzoai/cloud/clients/money"
|
||||
"github.com/hanzoai/cloud/clients/s3admin"
|
||||
"github.com/hanzoai/cloud/types"
|
||||
@@ -63,14 +63,15 @@ func BuildDeps(cfg *Config) Deps {
|
||||
)
|
||||
|
||||
deps := Deps{
|
||||
Logger: logger,
|
||||
Brand: cfg.Brand,
|
||||
Version: cfg.Version,
|
||||
Env: cfg.Env,
|
||||
Domain: cfg.Domain,
|
||||
IAMIssuer: cfg.IAMIssuer,
|
||||
DataDir: cfg.DataDir,
|
||||
AIDefaultModel: cfg.AIDefaultModel,
|
||||
Logger: logger,
|
||||
Brand: cfg.Brand,
|
||||
Version: cfg.Version,
|
||||
Env: cfg.Env,
|
||||
Domain: cfg.Domain,
|
||||
IAMIssuer: cfg.IAMIssuer,
|
||||
DataDir: cfg.DataDir,
|
||||
AIDefaultModel: cfg.AIDefaultModel,
|
||||
AIFallbackModel: cfg.AIFallbackModel,
|
||||
}
|
||||
|
||||
// For each subsystem: enabled → leave nil (Mount fills it); not
|
||||
@@ -90,7 +91,14 @@ func BuildDeps(cfg *Config) Deps {
|
||||
// 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)
|
||||
wireTierReader(deps.Metering, logger)
|
||||
// AI (completions, WRITE) and Embed (embeddings, READ-ONLY) are DISTINCT
|
||||
// credentials by concern: completions never ride the read-only publishable
|
||||
// (pk-) key — the gateway 403s a pk- key on any write endpoint — so deps.AI
|
||||
// resolves to the M2M identity, while deps.Embed keeps the pk- key (correct
|
||||
// least-privilege for a read-only call). Both meter through the ONE commerce path.
|
||||
deps.AI = meteredAIClient(pickCompletionsClient(cfg, logger), deps)
|
||||
deps.Embed = meteredAIClient(pickEmbedClient(cfg, logger), deps)
|
||||
wireFinance(cfg, logger)
|
||||
deps.O11y = pick(cfg, logger, "o11y", "O11y", cfg.O11yZAPAddr, clients.O11yRPCAt, clients.DisabledO11y)
|
||||
deps.VFS = pickVFSClient(cfg, logger)
|
||||
@@ -107,7 +115,7 @@ func BuildDeps(cfg *Config) Deps {
|
||||
// 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))
|
||||
gp, err := edge.New(cfg.DataDir, cfg.AdminOrg, staticEdgePolicy(cfg))
|
||||
if err != nil {
|
||||
logger.Warn("gateway policy store degraded to static-only", "err", err)
|
||||
}
|
||||
@@ -117,10 +125,10 @@ func BuildDeps(cfg *Config) Deps {
|
||||
}
|
||||
|
||||
// staticEdgePolicy projects the static env/flag edge config into the boot-default
|
||||
// policy the gatewaypolicy.Store layers runtime overrides on top of. A disabled
|
||||
// policy the edge.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{
|
||||
func staticEdgePolicy(cfg *Config) edge.Policy {
|
||||
p := edge.Policy{
|
||||
CORSOrigins: cfg.CORSOrigins,
|
||||
WindowSec: cfg.EdgeRateWindowSec,
|
||||
}
|
||||
@@ -157,9 +165,15 @@ func buildMeteringClient(cfg *Config, log luxlog.Logger) *metering.Client {
|
||||
httpClient = commerceinproc.Client(0) // in-process dispatch; no network timeout
|
||||
}
|
||||
m, err := metering.New(metering.Config{
|
||||
BaseURL: base,
|
||||
Token: cfg.CommerceServiceToken,
|
||||
Org: cfg.Brand, // X-Org-Id default for S2S; per-request org overrides.
|
||||
BaseURL: base,
|
||||
Token: cfg.CommerceServiceToken,
|
||||
Org: cfg.Brand, // X-Org-Id default for S2S; per-request org overrides.
|
||||
// Honor the documented METERING_TEST env: when "true", route every debit to
|
||||
// commerce's TEST/sandbox books (fin.RecordUsage in.Test=true) so a staging /
|
||||
// canary deployment records NO real money — and the usage-cap read (org.TestMode
|
||||
// via SQUARE_ENVIRONMENT=sandbox) sees the SAME test books. Unset in prod → live,
|
||||
// unchanged. Without this the flag was silently ignored (always live).
|
||||
Test: strings.EqualFold(strings.TrimSpace(os.Getenv(metering.EnvTest)), "true"),
|
||||
FailOpen: cfg.BillingFailOpen,
|
||||
HTTPClient: httpClient, // nil off the co-resident path → metering builds its own
|
||||
})
|
||||
@@ -169,6 +183,11 @@ func buildMeteringClient(cfg *Config, log luxlog.Logger) *metering.Client {
|
||||
log.Error("billing: invalid commerce URL, gate disabled", "err", err)
|
||||
m, _ = metering.New(metering.Config{})
|
||||
}
|
||||
// Observe every cap-check fail-open (timeout / slow / broken commerce) — a cap that
|
||||
// silently allows must never be silent. The completion still proceeds (fail-open).
|
||||
metering.OnCapError = func(err error) {
|
||||
log.Warn("spend-cap check failed open (allowing completion) — commerce authorize slow/unavailable", "err", err)
|
||||
}
|
||||
if m.Enabled() {
|
||||
log.Info("billing gate enabled", "commerce", boolStr(inProcess, "in-process", "http:"+base), "fail_open", cfg.BillingFailOpen)
|
||||
} else {
|
||||
@@ -184,6 +203,28 @@ func boolStr(b bool, t, f string) string {
|
||||
return f
|
||||
}
|
||||
|
||||
// wireTierReader installs the embedded ai module's per-tier SKU gate reader so it
|
||||
// resolves the caller's commerce subscription tier through the SAME co-resident
|
||||
// commerce client the metering gate bills over — in-process (commerceinproc) when
|
||||
// commerce is folded in, S2S HTTP with the service token otherwise — NEVER an authed
|
||||
// self-call to the cloud edge. That self-call is the toothless-gate bug: the edge
|
||||
// 401/403s a service call to /v1/billing/*, so the ai module's own HTTP lookup always
|
||||
// returned "" in-cluster and every tier-gated SKU failed OPEN. This mirrors
|
||||
// wireFinance's SetBalanceReader: cloud owns the co-resident read, ai stays
|
||||
// transport-agnostic. Fail-safe is preserved — Client.Tier folds a commerce error or
|
||||
// an unknown plan to "", which the gate treats as ALLOW, so a commerce blip never
|
||||
// locks out a paying caller. No-op when commerce is unreachable (metering !Enabled),
|
||||
// leaving ai's standalone HTTP fallback in place.
|
||||
func wireTierReader(m *metering.Client, log luxlog.Logger) {
|
||||
if m == nil || !m.Enabled() {
|
||||
return
|
||||
}
|
||||
aiobject.SetTierReader(func(ctx context.Context, subject, namespace string) (string, error) {
|
||||
return m.Tier(ctx, subject, namespace)
|
||||
})
|
||||
log.Info("ai per-tier SKU gate wired to co-resident commerce (in-process tier read, fail-safe)")
|
||||
}
|
||||
|
||||
// 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 +
|
||||
@@ -545,44 +586,76 @@ func RegisterCommerceClientFactory(f func(cfg *Config, log luxlog.Logger) Commer
|
||||
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
|
||||
// must return a concrete client, never nil. (A nil deps.AI was the live bug —
|
||||
// the default all-enabled config returned nil here and nothing ever filled it,
|
||||
// so every /v1/agents/:name/run 503'd "inference is not configured".)
|
||||
// publishableKey reports whether apiKey is a read-only PUBLISHABLE key (pk-). The
|
||||
// Hanzo gateway 403s a publishable key on any WRITE endpoint — "Publishable keys
|
||||
// can only access read-only endpoints … use a secret key (sk-)". So the COMPLETIONS
|
||||
// resolver must refuse it (it would only 403 chat), while the EMBED resolver accepts
|
||||
// it (embeddings ARE read-only). pk- is the IAM key family's read-only member
|
||||
// (hk-/sk-/pk-/fw_/hz_; clients/admission). This ONE predicate is the split's crux:
|
||||
// it kept the intermittent-403 bug — a pk- embed key riding the shared completions
|
||||
// client — from ever recurring, wherever the key comes from.
|
||||
func publishableKey(apiKey string) bool {
|
||||
return strings.HasPrefix(strings.TrimSpace(apiKey), "pk-")
|
||||
}
|
||||
|
||||
// pickCompletionsClient resolves deps.AI — the client the agents run path (and
|
||||
// guide/crm/content/sitegen/code /ask) execute CHAT COMPLETIONS through. There is
|
||||
// NO in-process "ai" mount that fills a nil deps.AI: inference is an external
|
||||
// gateway, so this returns a concrete client, never nil.
|
||||
//
|
||||
// Completions are a WRITE endpoint: a read-only publishable (pk-) key 403s them. So
|
||||
// this resolver NEVER rides a pk- key — that is the embed credential (pickEmbedClient).
|
||||
// Preference order:
|
||||
// 1. Static-key HTTP gateway when a base URL AND a static key are configured —
|
||||
// an operator override / pre-provisioned key. The key is a KMS-injected
|
||||
// secret; only the base URL and default model are ever logged.
|
||||
// 1. Static SECRET-key HTTP gateway when a base URL AND a completions-capable
|
||||
// (non-pk-) static key are configured — an explicit operator override (sk-/hk-).
|
||||
// A pk- key here is REFUSED (it would only 403 chat) and the resolver falls
|
||||
// through to M2M — THE fix for the intermittent publishable-key 403 on bot replies.
|
||||
// 2. M2M HTTP gateway when a base URL AND the binary's IAM identity are present
|
||||
// (the durable Hanzo default): the client mints+refreshes a client-
|
||||
// credentials token from IAM_CLIENT_ID/SECRET — no static key to rotate. The
|
||||
// secret is never logged.
|
||||
// (the durable Hanzo default): the client mints+refreshes a client-credentials
|
||||
// token from IAM_CLIENT_ID/SECRET — no static key to rotate. Secret never logged.
|
||||
// 3. ZAP RPC when an addr is configured (split-deploy of a future ai subsystem).
|
||||
// 4. Fail-closed stub otherwise — a run records an honest error, never fakes one.
|
||||
func pickAIClient(cfg *Config, log luxlog.Logger) AIClient {
|
||||
if cfg.AIBaseURL != "" && cfg.AIAPIKey != "" {
|
||||
log.Info("deps.AI → HTTP gateway (static key)", "base_url", cfg.AIBaseURL, "default_model", cfg.AIDefaultModel)
|
||||
func pickCompletionsClient(cfg *Config, log luxlog.Logger) AIClient {
|
||||
if cfg.AIBaseURL != "" && cfg.AIAPIKey != "" && !publishableKey(cfg.AIAPIKey) {
|
||||
log.Info("deps.AI (completions) → HTTP gateway (static secret key)", "base_url", cfg.AIBaseURL, "default_model", cfg.AIDefaultModel)
|
||||
return clients.AIHTTPAt(cfg.AIBaseURL, cfg.AIAPIKey, cfg.AIDefaultModel)
|
||||
}
|
||||
if cfg.AIAPIKey != "" && publishableKey(cfg.AIAPIKey) {
|
||||
log.Info("deps.AI (completions) → refusing read-only publishable (pk-) key for chat; using M2M", "base_url", cfg.AIBaseURL)
|
||||
}
|
||||
if cfg.AIBaseURL != "" && cfg.AIAuthClientID != "" && cfg.AIAuthClientSecret != "" {
|
||||
tokenURL := aiM2MTokenURL(cfg)
|
||||
if tokenURL != "" {
|
||||
log.Info("deps.AI → HTTP gateway (IAM M2M)", "base_url", cfg.AIBaseURL,
|
||||
log.Info("deps.AI (completions) → 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)
|
||||
log.Info("deps.AI (completions) → ZAP RPC", "addr", cfg.AIZAPAddr)
|
||||
return clients.AIRPCAt(cfg.AIZAPAddr)
|
||||
}
|
||||
log.Info("deps.AI → disabled (no CLOUD_AI_API_KEY, no IAM M2M identity, no gateway configured)")
|
||||
log.Info("deps.AI (completions) → disabled (no secret key, no IAM M2M identity, no gateway configured)")
|
||||
return clients.DisabledAI()
|
||||
}
|
||||
|
||||
// pickEmbedClient resolves deps.Embed — the client code-index + KB knowledge run
|
||||
// EMBEDDINGS through. Embeddings are a READ-ONLY endpoint, so the read-only
|
||||
// publishable (pk-) key (CLOUD_AI_API_KEY ← cloud-ai-embed-key) is the CORRECT
|
||||
// least-privilege credential here, and is used UNCHANGED — this path is deliberately
|
||||
// not rewired. Preference order:
|
||||
// 1. Static-key HTTP gateway when a base URL AND a static key are configured. The
|
||||
// key (pk- or sk-) is a KMS-injected secret; only base URL + model are logged.
|
||||
// 2. Otherwise share the completions resolution (M2M / ZAP / fail-closed) so a
|
||||
// deploy with no dedicated embed key still indexes — no regression.
|
||||
func pickEmbedClient(cfg *Config, log luxlog.Logger) AIClient {
|
||||
if cfg.AIBaseURL != "" && cfg.AIAPIKey != "" {
|
||||
log.Info("deps.Embed → HTTP gateway (static embed key)", "base_url", cfg.AIBaseURL, "default_model", cfg.AIDefaultModel)
|
||||
return clients.AIHTTPAt(cfg.AIBaseURL, cfg.AIAPIKey, cfg.AIDefaultModel)
|
||||
}
|
||||
return pickCompletionsClient(cfg, log)
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package cloud
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
luxlog "github.com/luxfi/log"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// CallerBearer relays the caller's OWN validated JWT bearer and nothing else: a JWT
|
||||
// passes through unchanged, an opaque API key is not relayable, and no credential
|
||||
// yields "". This is the token a downstream org-scoped service (the DNS forward
|
||||
// head) re-validates to enforce tenant isolation across the hop.
|
||||
func TestCallerBearer(t *testing.T) {
|
||||
app := zip.New(zip.Config{Logger: luxlog.New("test")})
|
||||
app.Get("/probe", func(c *zip.Ctx) error { return c.Bytes(200, []byte(CallerBearer(c))) })
|
||||
|
||||
probe := func(setup func(*http.Request)) string {
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
if setup != nil {
|
||||
setup(req)
|
||||
}
|
||||
res, err := app.Fiber().Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
return string(b)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(*http.Request)
|
||||
want string
|
||||
}{
|
||||
{"jwt bearer relayed unchanged", func(r *http.Request) { r.Header.Set("Authorization", "Bearer jwt.header.sig") }, "jwt.header.sig"},
|
||||
{"X-Authorization fallback", func(r *http.Request) { r.Header.Set("X-Authorization", "Bearer x.y.z") }, "x.y.z"},
|
||||
{"opaque hk- api key is NOT relayable", func(r *http.Request) { r.Header.Set("Authorization", "Bearer hk-secret") }, ""},
|
||||
{"opaque sk- api key is NOT relayable", func(r *http.Request) { r.Header.Set("Authorization", "Bearer sk-secret") }, ""},
|
||||
{"no credential yields empty", nil, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := probe(c.setup); got != c.want {
|
||||
t.Errorf("%s: CallerBearer = %q, want %q", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-10
@@ -63,7 +63,9 @@ var controlCommands = map[string]string{
|
||||
"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)",
|
||||
"link": "bring this machine into the Hanzo cloud fleet as a node (fabric + compute worker)",
|
||||
"unlink": "take this machine out of the fleet (deregister + stop hanzod)",
|
||||
"status": "show the org's fleet — every node with each of its GPUs",
|
||||
"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)",
|
||||
@@ -474,11 +476,14 @@ func (e *Env) freshAccessToken() string {
|
||||
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
|
||||
// (in precedence) the bound --platform-token flag, the environment, then the
|
||||
// credential store. Never hardcoded.
|
||||
// platformToken resolves the bearer the platform control plane authenticates
|
||||
// apps/clusters/redeploy with. ONE identity authorizes everything: after a plain
|
||||
// `hanzo login` the IAM access token is the FINAL fallback, so no separate
|
||||
// --platform-token is needed — the platform verifies the IAM JWT (signature,
|
||||
// issuer, expiry) and org-scopes the caller. A dedicated service token still
|
||||
// wins when present (flag > env > credential store > IAM login), so purpose-minted
|
||||
// machine tokens keep their precedence and internal automation is unchanged.
|
||||
// Never hardcoded.
|
||||
func (e *Env) platformToken(flagVal string) string {
|
||||
return firstNonEmpty(
|
||||
flagVal,
|
||||
@@ -486,17 +491,22 @@ func (e *Env) platformToken(flagVal string) string {
|
||||
os.Getenv("PLATFORM_SERVICE_TOKEN"),
|
||||
os.Getenv("PAAS_SERVICE_TOKEN"),
|
||||
e.creds.PlatformToken,
|
||||
e.accessToken(), // IAM login is the one identity that authorizes control-plane ops
|
||||
)
|
||||
}
|
||||
|
||||
// buildToken resolves the platform build-enqueue token (a distinct credential
|
||||
// from the service token — see /v1/runner).
|
||||
// buildToken resolves the bearer `hanzo build` sends to the platform build
|
||||
// enqueue (/v1/runner). Same unify-infra contract as platformToken: a dedicated
|
||||
// build token wins when present, but a plain IAM login is the FINAL fallback, so
|
||||
// `hanzo build` works off the one identity with no separate --build-token — the
|
||||
// platform verifies the IAM JWT and authorizes the build by org + role.
|
||||
func (e *Env) buildToken(flagVal string) string {
|
||||
return firstNonEmpty(
|
||||
flagVal,
|
||||
os.Getenv("HANZO_BUILD_TOKEN"),
|
||||
os.Getenv("PLATFORM_BUILD_CALLBACK_TOKEN"),
|
||||
e.creds.BuildToken,
|
||||
e.accessToken(), // IAM login is the one identity that authorizes builds
|
||||
)
|
||||
}
|
||||
|
||||
@@ -588,10 +598,11 @@ func newRootCmd() *cobra.Command {
|
||||
newDeployCmd(envOf, &f),
|
||||
newClustersCmd(envOf, &f),
|
||||
newBuildCmd(envOf, &f),
|
||||
newK8sCmd(envOf, &f),
|
||||
newConfigCmd(),
|
||||
newSecurityCmd(envOf),
|
||||
newGPUCmd(envOf, &f),
|
||||
newLinkCmd(envOf, &f),
|
||||
newUnlinkCmd(envOf, &f),
|
||||
newStatusCmd(envOf, &f),
|
||||
newEngineCmd(envOf, &f),
|
||||
newCodeCmd(envOf, &f),
|
||||
newRunnerCmd(envOf, &f),
|
||||
|
||||
@@ -141,6 +141,29 @@ func TestPlatformTokenPrecedence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformTokenFallsBackToIAM is the UNIFY-INFRA contract for the control
|
||||
// plane: after a plain `hanzo login`, the IAM access token is the FINAL fallback
|
||||
// so `hanzo apps`/`hanzo deploy` authorize off the one identity. An explicit
|
||||
// platform service token (creds/env/flag) still wins.
|
||||
func TestPlatformTokenFallsBackToIAM(t *testing.T) {
|
||||
sandbox(t)
|
||||
// Only an IAM login: no platform token anywhere ⇒ the IAM access token is sent.
|
||||
e := resolve(&Config{}, &Credentials{AccessToken: "iam-jwt"}, globalFlags{})
|
||||
if got := e.platformToken(""); got != "iam-jwt" {
|
||||
t.Fatalf("IAM access token should be the final platform-token fallback: %q", got)
|
||||
}
|
||||
// A dedicated platform service token still beats the IAM token.
|
||||
e = resolve(&Config{}, &Credentials{AccessToken: "iam-jwt", PlatformToken: "svc"}, globalFlags{})
|
||||
if got := e.platformToken(""); got != "svc" {
|
||||
t.Fatalf("dedicated platform token must beat the IAM fallback: %q", got)
|
||||
}
|
||||
// No login at all ⇒ empty (caller surfaces "run `hanzo login`").
|
||||
e = resolve(&Config{}, &Credentials{}, globalFlags{})
|
||||
if got := e.platformToken(""); got != "" {
|
||||
t.Fatalf("no token and no login should resolve empty: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTokenPrecedence(t *testing.T) {
|
||||
sandbox(t)
|
||||
e := resolve(&Config{}, &Credentials{BuildToken: "creds"}, globalFlags{})
|
||||
@@ -156,6 +179,37 @@ func TestBuildTokenPrecedence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTokenFallsBackToIAM is the UNIFY-INFRA contract: after a plain
|
||||
// `hanzo login` (no --build-token), the IAM access token is the FINAL fallback,
|
||||
// so `hanzo build` authorizes off the one identity. An explicit build token
|
||||
// (creds/env/flag) still wins — the IAM token is the LAST resort, never an
|
||||
// override of a purpose-minted machine token.
|
||||
func TestBuildTokenFallsBackToIAM(t *testing.T) {
|
||||
sandbox(t)
|
||||
// Only an IAM login: no build token anywhere ⇒ the IAM access token is sent.
|
||||
e := resolve(&Config{}, &Credentials{AccessToken: "iam-jwt"}, globalFlags{})
|
||||
if got := e.buildToken(""); got != "iam-jwt" {
|
||||
t.Fatalf("IAM access token should be the final build-token fallback: %q", got)
|
||||
}
|
||||
// A dedicated build token still beats the IAM token (precedence preserved).
|
||||
e = resolve(&Config{}, &Credentials{AccessToken: "iam-jwt", BuildToken: "creds"}, globalFlags{})
|
||||
if got := e.buildToken(""); got != "creds" {
|
||||
t.Fatalf("dedicated build token must beat the IAM fallback: %q", got)
|
||||
}
|
||||
// HANZO_TOKEN (the env form of the IAM token) is also honored via accessToken().
|
||||
e = resolve(&Config{}, &Credentials{}, globalFlags{})
|
||||
t.Setenv("HANZO_TOKEN", "iam-env")
|
||||
if got := e.buildToken(""); got != "iam-env" {
|
||||
t.Fatalf("HANZO_TOKEN should back the build-token fallback: %q", got)
|
||||
}
|
||||
// No login at all ⇒ empty, so the caller can surface "run `hanzo login`".
|
||||
t.Setenv("HANZO_TOKEN", "")
|
||||
e = resolve(&Config{}, &Credentials{}, globalFlags{})
|
||||
if got := e.buildToken(""); got != "" {
|
||||
t.Fatalf("no token and no login should resolve empty: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessTokenFromEnvOverCreds(t *testing.T) {
|
||||
sandbox(t)
|
||||
e := resolve(&Config{}, &Credentials{AccessToken: "creds"}, globalFlags{})
|
||||
|
||||
+64
-22
@@ -147,6 +147,7 @@ type codeAgent struct {
|
||||
bin string // executable to exec
|
||||
wire wire // how it finds the cloud
|
||||
fullAuto []string // flags that bypass approval prompts
|
||||
continueArgs []string // harness-native form of Hanzo -c/--continue
|
||||
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
|
||||
@@ -163,10 +164,11 @@ type codeAgent struct {
|
||||
// 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"},
|
||||
bin: bin,
|
||||
wire: openaiWire,
|
||||
fullAuto: []string{"--dangerously-bypass-approvals-and-sandbox"},
|
||||
continueArgs: []string{"resume", "--last"},
|
||||
modelArg: []string{"-m"},
|
||||
provider: func(base string) []string {
|
||||
return []string{
|
||||
"-c", "model_provider=hanzo",
|
||||
@@ -174,6 +176,12 @@ func codexLike(bin, install string) codeAgent {
|
||||
"-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"`,
|
||||
// api.hanzo.ai exposes the standard OpenAI /v1/models shape,
|
||||
// not Codex's private remote model-catalog schema. Skip that
|
||||
// optional refresh and supply the coding model's metadata here.
|
||||
"-c", `features.remote_models=false`,
|
||||
"-c", `model_context_window=262144`,
|
||||
"-c", `model_auto_compact_token_limit=235929`,
|
||||
}
|
||||
},
|
||||
install: install,
|
||||
@@ -190,9 +198,10 @@ const zenIdentityPrompt = "You are running through the Hanzo AI cloud as a Hanzo
|
||||
|
||||
var codeAgents = map[string]codeAgent{
|
||||
"claude": {
|
||||
bin: "claude",
|
||||
wire: anthropicWire,
|
||||
fullAuto: []string{"--dangerously-skip-permissions"},
|
||||
bin: "claude",
|
||||
wire: anthropicWire,
|
||||
fullAuto: []string{"--dangerously-skip-permissions"},
|
||||
continueArgs: []string{"--continue"},
|
||||
// --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
|
||||
@@ -246,9 +255,12 @@ func newCodeCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
|
||||
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.",
|
||||
"(glm5.2 -> glm-5.2), -c resumes either harness, and agents run full-auto unless\n" +
|
||||
"you pass --safe. Unknown options pass through; -- forces verbatim passthrough.",
|
||||
Example: " hanzo code # dev, the default agent\n" +
|
||||
" hanzo code claude\n" +
|
||||
" hanzo code claude -c\n" +
|
||||
" hanzo code codex -c\n" +
|
||||
" hanzo code codex deepseek-v4-pro\n" +
|
||||
" hanzo code dev glm5.2 -- --resume\n" +
|
||||
" hanzo code ls",
|
||||
@@ -320,19 +332,10 @@ func runCode(env *Env, agent codeAgent, args []string) error {
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
// First non-flag arg before -- is the model; --safe and --continue are ours.
|
||||
// Unknown options pass through unchanged. Everything after -- belongs to the
|
||||
// agent, including positional subcommands and raw Codex -c config overrides.
|
||||
model, safe, continueLast, rest := splitCodeArgs(args)
|
||||
if model == "" {
|
||||
model = defaultCodeModel
|
||||
}
|
||||
@@ -382,7 +385,7 @@ func runCode(env *Env, agent codeAgent, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
argv := codeArgv(agent, base, model, safe, rest)
|
||||
argv := codeArgv(agent, base, model, safe, codeAgentRest(agent, continueLast, rest))
|
||||
|
||||
for k, v := range agent.wire(base, token, model) {
|
||||
if err := os.Setenv(k, v); err != nil {
|
||||
@@ -397,6 +400,45 @@ func runCode(env *Env, agent codeAgent, args []string) error {
|
||||
return execEngine(bin, argv) // exec: signals + exit code flow straight through
|
||||
}
|
||||
|
||||
// splitCodeArgs pulls the launcher-owned tokens (the model, --safe, -c/--continue)
|
||||
// out of the raw args; everything else is the agent's. The `--` separator is ours
|
||||
// and switches on verbatim passthrough — every token after it goes to the agent
|
||||
// untouched, including positional subcommands (`codex exec`) and raw Codex -c
|
||||
// config overrides that would otherwise look like our --continue.
|
||||
func splitCodeArgs(args []string) (model string, safe, continueLast bool, rest []string) {
|
||||
rest = make([]string, 0, len(args))
|
||||
passthrough := false
|
||||
for _, a := range args {
|
||||
switch {
|
||||
case passthrough:
|
||||
rest = append(rest, a)
|
||||
case a == "--": // the separator is ours; the agent must not see it
|
||||
passthrough = true
|
||||
case a == "--safe" || a == "--ask":
|
||||
safe = true
|
||||
case a == "-c" || a == "--continue":
|
||||
continueLast = true
|
||||
case model == "" && !strings.HasPrefix(a, "-") && len(rest) == 0:
|
||||
model = a
|
||||
default:
|
||||
rest = append(rest, a)
|
||||
}
|
||||
}
|
||||
return model, safe, continueLast, rest
|
||||
}
|
||||
|
||||
// codeAgentRest prepends the agent's harness-native resume tokens when -c/--continue
|
||||
// was given, so one Hanzo flag resumes the last session on either harness (`--continue`
|
||||
// for Claude Code, `resume --last` for Codex/dev).
|
||||
func codeAgentRest(agent codeAgent, continueLast bool, rest []string) []string {
|
||||
if !continueLast {
|
||||
return rest
|
||||
}
|
||||
args := make([]string, 0, len(agent.continueArgs)+len(rest))
|
||||
args = append(args, agent.continueArgs...)
|
||||
return append(args, rest...)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
+77
-10
@@ -18,6 +18,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -48,6 +49,72 @@ func TestCodeAgentsBypassPermissionsByDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeArgsSeparatorPreservesAgentSubcommand(t *testing.T) {
|
||||
model, safe, continueLast, rest := splitCodeArgs([]string{"--safe", "--", "exec", "--ephemeral", "do it"})
|
||||
if model != "" || !safe || continueLast {
|
||||
t.Fatalf("model=%q safe=%v continue=%v, want default model and safe mode", model, safe, continueLast)
|
||||
}
|
||||
if want := []string{"exec", "--ephemeral", "do it"}; !reflect.DeepEqual(rest, want) {
|
||||
t.Fatalf("agent args = %q, want %q", rest, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeArgsExplicitModelBeforeSeparator(t *testing.T) {
|
||||
model, safe, continueLast, rest := splitCodeArgs([]string{"zen5-max", "--", "exec"})
|
||||
if model != "zen5-max" || safe || continueLast || !reflect.DeepEqual(rest, []string{"exec"}) {
|
||||
t.Fatalf("model=%q safe=%v continue=%v rest=%q", model, safe, continueLast, rest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeContinueIsNormalizedForBothHarnesses(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
want []string
|
||||
}{
|
||||
{name: "claude", want: []string{"--continue"}},
|
||||
{name: "codex", want: []string{"resume", "--last"}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
model, safe, continueLast, rest := splitCodeArgs([]string{"-c"})
|
||||
if model != "" || safe || !continueLast || len(rest) != 0 {
|
||||
t.Fatalf("model=%q safe=%v continue=%v rest=%q", model, safe, continueLast, rest)
|
||||
}
|
||||
if got := codeAgentRest(codeAgents[tt.name], continueLast, rest); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("normalized continue args = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeUnknownOptionsAndPostSeparatorArgsPassThrough(t *testing.T) {
|
||||
unknown := []string{"--mystery", "value", "--other=1"}
|
||||
model, safe, continueLast, rest := splitCodeArgs(unknown)
|
||||
if model != "" || safe || continueLast || !reflect.DeepEqual(rest, unknown) {
|
||||
t.Fatalf("unknown options changed: model=%q safe=%v continue=%v rest=%q", model, safe, continueLast, rest)
|
||||
}
|
||||
|
||||
_, _, continueLast, rest = splitCodeArgs([]string{"--", "-c", "model=x"})
|
||||
if continueLast || !reflect.DeepEqual(rest, []string{"-c", "model=x"}) {
|
||||
t.Fatalf("post-separator Codex config must pass verbatim: continue=%v rest=%q", continueLast, rest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexProviderUsesNativeResponsesMetadata(t *testing.T) {
|
||||
argv := codeArgv(codeAgents["codex"], "https://api.hanzo.ai", defaultCodeModel, false, nil)
|
||||
for _, want := range []string{
|
||||
`model_provider=hanzo`,
|
||||
`model_providers.hanzo.base_url="https://api.hanzo.ai/v1"`,
|
||||
`model_providers.hanzo.wire_api="responses"`,
|
||||
`features.remote_models=false`,
|
||||
`model_context_window=262144`,
|
||||
`model_auto_compact_token_limit=235929`,
|
||||
} {
|
||||
if !slices.Contains(argv, want) {
|
||||
t.Errorf("Codex argv %q does not contain %q", argv, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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_*).
|
||||
@@ -60,10 +127,10 @@ func TestCodeTokenPrecedence(t *testing.T) {
|
||||
freshExpiry := time.Now().Add(1 * time.Hour).Unix()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
envKey string // HANZO_API_KEY override
|
||||
creds Credentials
|
||||
want string
|
||||
name string
|
||||
envKey string // HANZO_API_KEY override
|
||||
creds Credentials
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "fresh JWT beats hk- key",
|
||||
@@ -81,16 +148,16 @@ func TestCodeTokenPrecedence(t *testing.T) {
|
||||
want: "hk-stored",
|
||||
},
|
||||
{
|
||||
name: "HANZO_API_KEY overrides everything (deliberate operator override)",
|
||||
name: "HANZO_API_KEY overrides everything (deliberate operator override)",
|
||||
envKey: "hk-explicit",
|
||||
creds: Credentials{AccessToken: "jwt-live", Expiry: freshExpiry},
|
||||
want: "hk-explicit",
|
||||
creds: Credentials{AccessToken: "jwt-live", Expiry: freshExpiry},
|
||||
want: "hk-explicit",
|
||||
},
|
||||
{
|
||||
name: "HANZO_API_KEY overrides even an expired JWT",
|
||||
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",
|
||||
creds: Credentials{AccessToken: "jwt-dead", Expiry: time.Now().Add(-1 * time.Hour).Unix()},
|
||||
want: "hk-explicit",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+103
-222
@@ -3,6 +3,7 @@ package cli
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -15,12 +16,12 @@ func (e *Env) platform(gf *globalFlags) *Platform {
|
||||
return newPlatform(e.PlatformURL, e.platformToken(gf.platformToken))
|
||||
}
|
||||
|
||||
// deref renders a *string for a table cell, "-" when nil/empty.
|
||||
func deref(p *string) string {
|
||||
if p == nil || *p == "" {
|
||||
// dashIfEmpty renders a string cell, "-" when empty.
|
||||
func dashIfEmpty(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return *p
|
||||
return s
|
||||
}
|
||||
|
||||
// yesno renders a bool for a table cell.
|
||||
@@ -37,7 +38,8 @@ func newTab(w io.Writer) *tabwriter.Writer {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// apps — the observe surface.
|
||||
// apps — the fleet drift board (GET /v1/paas/apps). Org-confined server-side by
|
||||
// the IAM identity: a superadmin sees the whole fleet, an org-admin only its own.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func newAppsCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
@@ -56,7 +58,6 @@ func newAppsCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
res, err := e.platform(gf).Apps(cmd.Context(), AppsQuery{
|
||||
Org: e.Org, // empty == all (single-tenant default)
|
||||
Env: envFilter,
|
||||
Health: healthFilter,
|
||||
Drift: driftOnly,
|
||||
@@ -69,8 +70,8 @@ func newAppsCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
fmt.Fprintln(tw, "ORG\tAPP\tENV\tDECLARED\tRUNNING\tHEALTH\tDRIFT")
|
||||
for _, a := range res.Apps {
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
a.Org, a.App, a.Env, deref(a.DeclaredTag), deref(a.RunningTag),
|
||||
deref(a.Health), driftSeverity(a.Drift))
|
||||
a.Org, a.App, a.Env, dashIfEmpty(a.DeclaredTag), dashIfEmpty(a.RunningTag),
|
||||
dashIfEmpty(a.Health), driftSeverity(a.Drift))
|
||||
}
|
||||
tw.Flush()
|
||||
fmt.Fprintf(w, "\n%d apps (ok=%d yellow=%d red=%d)\n",
|
||||
@@ -79,17 +80,17 @@ func newAppsCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
})
|
||||
},
|
||||
}
|
||||
list.Flags().StringVar(&envFilter, "env", "", "filter by env: dev|test|main")
|
||||
list.Flags().StringVar(&envFilter, "env", "", "filter by env: main|test|dev")
|
||||
list.Flags().StringVar(&healthFilter, "health", "", "filter by health: green|yellow|red")
|
||||
list.Flags().BoolVar(&driftOnly, "drift", false, "only rows that are drifting")
|
||||
|
||||
get := &cobra.Command{
|
||||
Use: "get <org/app/env>",
|
||||
Short: "Get one app row by its <org>/<app>/<env> id",
|
||||
Use: "get <app>",
|
||||
Short: "Get one app row by its CR name (production by default)",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
e := envOf()
|
||||
a, err := e.platform(gf).App(cmd.Context(), args[0], e.Org)
|
||||
a, err := e.platform(gf).App(cmd.Context(), args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -101,109 +102,93 @@ func newAppsCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
fmt.Fprintf(tw, "env:\t%s\n", a.Env)
|
||||
fmt.Fprintf(tw, "repo:\t%s\n", a.Repo)
|
||||
fmt.Fprintf(tw, "registry:\t%s\n", a.Registry)
|
||||
fmt.Fprintf(tw, "declared:\t%s\n", deref(a.DeclaredTag))
|
||||
fmt.Fprintf(tw, "running:\t%s\n", deref(a.RunningTag))
|
||||
fmt.Fprintf(tw, "latest:\t%s\n", deref(a.LatestTag))
|
||||
fmt.Fprintf(tw, "health:\t%s\n", deref(a.Health))
|
||||
fmt.Fprintf(tw, "declared:\t%s\n", dashIfEmpty(a.DeclaredTag))
|
||||
fmt.Fprintf(tw, "running:\t%s\n", dashIfEmpty(a.RunningTag))
|
||||
fmt.Fprintf(tw, "health:\t%s\n", dashIfEmpty(a.Health))
|
||||
fmt.Fprintf(tw, "phase:\t%s\n", dashIfEmpty(a.Phase))
|
||||
fmt.Fprintf(tw, "drift:\t%s\n", driftSeverity(a.Drift))
|
||||
fmt.Fprintf(tw, "cluster:\t%s\n", deref(a.Cluster))
|
||||
fmt.Fprintf(tw, "namespace:\t%s\n", deref(a.Namespace))
|
||||
fmt.Fprintf(tw, "updated:\t%s\n", a.UpdatedAt)
|
||||
fmt.Fprintf(tw, "cluster:\t%s\n", dashIfEmpty(a.Cluster))
|
||||
fmt.Fprintf(tw, "namespace:\t%s\n", dashIfEmpty(a.Namespace))
|
||||
if len(a.Endpoints) > 0 {
|
||||
fmt.Fprintf(tw, "endpoints:\t%s\n", strings.Join(a.Endpoints, ", "))
|
||||
}
|
||||
tw.Flush()
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
sync := &cobra.Command{
|
||||
Use: "sync",
|
||||
Short: "Trigger an inventory refresh of the apps board",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
if err := e.platform(gf).SyncApps(cmd.Context()); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "apps sync triggered")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.AddCommand(list, get, sync)
|
||||
cmd.AddCommand(list, get)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// deploy — the drive surface (rolling restart, zero-downtime).
|
||||
// deploy — POST /v1/paas/apps/{app}/deploy: a zero-downtime rolling restart.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func newDeployCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
var project, environment string
|
||||
var environment string
|
||||
cmd := &cobra.Command{
|
||||
Use: "deploy <container>",
|
||||
Short: "Redeploy a container (rolling restart, zero-downtime)",
|
||||
Long: "Drive a platform redeploy: a rolling restart of the container's k8s\n" +
|
||||
"Deployment (re-pulls the image, recreates pods, zero downtime). Coordinates\n" +
|
||||
"are exact — org (--org/config), project (--project), env (--env) and the\n" +
|
||||
"container id (positional). This is the canonical PaaS-driven deploy.",
|
||||
Use: "deploy <app>",
|
||||
Short: "Redeploy an app (rolling restart, zero-downtime) — requires --env",
|
||||
Long: "Drive a platform redeploy: a rolling restart of the app's k8s Deployment\n" +
|
||||
"(re-pulls the declared image, recreates pods, zero downtime). The app is the\n" +
|
||||
"operator App CR name; the org comes from your IAM identity. --env is REQUIRED\n" +
|
||||
"(main|test|dev) — deploy never silently targets production. Restarting a shared\n" +
|
||||
"platform service is a platform-operator action, so this needs a superadmin\n" +
|
||||
"identity. A TAG change is still a git commit — this restarts what is declared.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if strings.TrimSpace(environment) == "" {
|
||||
return fmt.Errorf("--env is required (main|test|dev) — deploy will not default to production")
|
||||
}
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
res, err := e.platform(gf).Redeploy(cmd.Context(), args[0], environment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if project == "" || environment == "" {
|
||||
return fmt.Errorf("--project and --env are required (the container's project/environment ids)")
|
||||
}
|
||||
container := args[0]
|
||||
if err := e.platform(gf).Redeploy(cmd.Context(), org, project, environment, container); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "redeployed %s (org=%s project=%s env=%s)\n", container, org, project, environment)
|
||||
return nil
|
||||
return e.emit(res, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "restarted %s (namespace=%s env=%s at %s)\n",
|
||||
res.App, res.Namespace, dashIfEmpty(res.Env), res.RestartedAt)
|
||||
})
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&project, "project", "", "project id")
|
||||
cmd.Flags().StringVar(&environment, "env", "", "environment id")
|
||||
cmd.Flags().StringVar(&environment, "env", "", "lifecycle env: main|test|dev (REQUIRED)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// clusters — dedicated DOKS cluster lifecycle.
|
||||
// clusters — GET /v1/clusters: the org's compute fleet (Visor-managed + BYO),
|
||||
// tenant-scoped server-side by the IAM identity.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func newClustersCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "clusters",
|
||||
Aliases: []string{"cluster"},
|
||||
Short: "Provision/list/select dedicated DOKS clusters",
|
||||
Short: "List the org's clusters (managed + BYO)",
|
||||
}
|
||||
|
||||
list := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List the org's dedicated clusters",
|
||||
Short: "List the org's clusters",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cs, err := e.platform(gf).Clusters(cmd.Context(), org)
|
||||
cs, err := e.platform(gf).Clusters(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emit(cs, func(w io.Writer) {
|
||||
tw := newTab(w)
|
||||
fmt.Fprintln(tw, "NAME\tID\tREGION\tSTATUS\tPHASE\tACTIVE\tOPERATOR\tBASELINE")
|
||||
fmt.Fprintln(tw, "NAME\tID\tREGION\tSTATUS\tKIND\tNODES\tSIZE\tGPUS")
|
||||
for _, c := range cs {
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
c.Name, c.DoksClusterID, c.Region, c.Status, c.Phase,
|
||||
yesno(c.Active), yesno(c.OperatorInstalled), yesno(c.BaselineInstalled))
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
|
||||
c.Name, dashIfEmpty(c.ID()), dashIfEmpty(c.Region), dashIfEmpty(c.Status),
|
||||
dashIfEmpty(c.Kind), c.NodeCount, dashIfEmpty(c.NodeSize), gpuCell(c))
|
||||
}
|
||||
tw.Flush()
|
||||
if len(cs) == 0 {
|
||||
fmt.Fprintln(w, "(no dedicated clusters)")
|
||||
fmt.Fprintln(w, "(no clusters)")
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -215,151 +200,51 @@ func newClustersCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cs, err := e.platform(gf).Clusters(cmd.Context(), org)
|
||||
cs, err := e.platform(gf).Clusters(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range cs {
|
||||
if c.DoksClusterID == args[0] || c.Name == args[0] {
|
||||
if c.ID() == args[0] || c.Name == args[0] {
|
||||
return e.emit(c, func(w io.Writer) { printCluster(w, c) })
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("cluster %q not found in org %s", args[0], org)
|
||||
return fmt.Errorf("cluster %q not found", args[0])
|
||||
},
|
||||
}
|
||||
|
||||
var region, nodeSize string
|
||||
var ha bool
|
||||
var nodeCount int
|
||||
create := &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Provision a new dedicated DOKS cluster for the org",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c, err := e.platform(gf).ProvisionCluster(cmd.Context(), org, ProvisionReq{
|
||||
Region: region, HA: ha, NodeSize: nodeSize, NodeCount: nodeCount,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emit(c, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "provisioning cluster %s (%s)\n", c.Name, c.DoksClusterID)
|
||||
printCluster(w, *c)
|
||||
})
|
||||
},
|
||||
}
|
||||
create.Flags().StringVar(®ion, "region", "", "DO region (default sfo3)")
|
||||
create.Flags().BoolVar(&ha, "ha", false, "highly-available control plane")
|
||||
create.Flags().StringVar(&nodeSize, "node-size", "", "node size slug (e.g. s-2vcpu-4gb)")
|
||||
create.Flags().IntVar(&nodeCount, "node-count", 0, "node count")
|
||||
|
||||
var shared bool
|
||||
selectCmd := &cobra.Command{
|
||||
Use: "select <cluster-id>",
|
||||
Short: "Set the org's active deploy target (or --shared to revert)",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var clusterID *string
|
||||
switch {
|
||||
case shared:
|
||||
clusterID = nil
|
||||
case len(args) == 1:
|
||||
clusterID = &args[0]
|
||||
default:
|
||||
return fmt.Errorf("give a cluster id, or --shared to revert to the shared cluster")
|
||||
}
|
||||
t, err := e.platform(gf).SelectTarget(cmd.Context(), org, clusterID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emit(t, func(w io.Writer) { printTarget(w, t) })
|
||||
},
|
||||
}
|
||||
selectCmd.Flags().BoolVar(&shared, "shared", false, "revert to the shared cluster")
|
||||
|
||||
installBaseline := &cobra.Command{
|
||||
Use: "install-baseline <cluster-id>",
|
||||
Short: "Install the hanzo-operator + per-tenant baseline on a cluster",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.platform(gf).InstallBaseline(cmd.Context(), org, args[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "baseline install requested for %s\n", args[0])
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
target := &cobra.Command{
|
||||
Use: "target",
|
||||
Short: "Show the org's current resolved deploy target",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := e.platform(gf).Target(cmd.Context(), org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emit(t, func(w io.Writer) { printTarget(w, t) })
|
||||
},
|
||||
}
|
||||
|
||||
cmd.AddCommand(list, get, create, selectCmd, installBaseline, target)
|
||||
cmd.AddCommand(list, get)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// gpuCell renders the live GPU inventory of a cluster ("-" when none).
|
||||
func gpuCell(c Cluster) string {
|
||||
var parts []string
|
||||
if c.NvidiaGPU > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%d nvidia", c.NvidiaGPU))
|
||||
}
|
||||
if c.AmdGPU > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%d amd", c.AmdGPU))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "-"
|
||||
}
|
||||
return strings.Join(parts, "+")
|
||||
}
|
||||
|
||||
func printCluster(w io.Writer, c Cluster) {
|
||||
tw := newTab(w)
|
||||
fmt.Fprintf(tw, "id:\t%s\n", c.DoksClusterID)
|
||||
fmt.Fprintf(tw, "id:\t%s\n", dashIfEmpty(c.ID()))
|
||||
fmt.Fprintf(tw, "name:\t%s\n", c.Name)
|
||||
fmt.Fprintf(tw, "region:\t%s\n", c.Region)
|
||||
fmt.Fprintf(tw, "status:\t%s\n", c.Status)
|
||||
fmt.Fprintf(tw, "phase:\t%s\n", c.Phase)
|
||||
fmt.Fprintf(tw, "active:\t%s\n", yesno(c.Active))
|
||||
fmt.Fprintf(tw, "operatorInstalled:\t%s\n", yesno(c.OperatorInstalled))
|
||||
fmt.Fprintf(tw, "baselineInstalled:\t%s\n", yesno(c.BaselineInstalled))
|
||||
fmt.Fprintf(tw, "endpoint:\t%s\n", deref(c.Endpoint))
|
||||
fmt.Fprintf(tw, "k8sVersion:\t%s\n", deref(c.K8sVersion))
|
||||
fmt.Fprintf(tw, "created:\t%s\n", c.CreatedAt)
|
||||
if c.BaselineError != nil && *c.BaselineError != "" {
|
||||
fmt.Fprintf(tw, "baselineError:\t%s\n", *c.BaselineError)
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
|
||||
func printTarget(w io.Writer, t *Target) {
|
||||
tw := newTab(w)
|
||||
kind := "shared"
|
||||
if t.Dedicated {
|
||||
kind = "dedicated"
|
||||
}
|
||||
fmt.Fprintf(tw, "cluster:\t%s\n", t.Cluster)
|
||||
fmt.Fprintf(tw, "kind:\t%s\n", kind)
|
||||
for ns, env := range t.Namespaces {
|
||||
fmt.Fprintf(tw, "namespace:\t%s -> %s\n", ns, env)
|
||||
fmt.Fprintf(tw, "region:\t%s\n", dashIfEmpty(c.Region))
|
||||
fmt.Fprintf(tw, "status:\t%s\n", dashIfEmpty(c.Status))
|
||||
fmt.Fprintf(tw, "kind:\t%s\n", dashIfEmpty(c.Kind))
|
||||
fmt.Fprintf(tw, "nodeCount:\t%d\n", c.NodeCount)
|
||||
fmt.Fprintf(tw, "nodeSize:\t%s\n", dashIfEmpty(c.NodeSize))
|
||||
fmt.Fprintf(tw, "gpus:\t%s\n", gpuCell(c))
|
||||
fmt.Fprintf(tw, "created:\t%s\n", dashIfEmpty(c.CreatedAt))
|
||||
for _, np := range c.NodePools {
|
||||
fmt.Fprintf(tw, "pool:\t%s (%s x%d, autoscale=%s)\n", np.Name, np.Size, np.Count, yesno(np.AutoScale))
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
@@ -387,6 +272,10 @@ func newBuildCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
if br.Repo == "" || br.SHA == "" || br.Image == "" {
|
||||
return fmt.Errorf("--repo (or positional), --sha and --image are required")
|
||||
}
|
||||
// The platform build muscle clones an https git URL; accept the
|
||||
// idiomatic `owner/name` shorthand and expand it to GitHub (the host
|
||||
// for every hanzoai/luxfi/zooai repo). A full URL passes through.
|
||||
br.Repo = normalizeRepoURL(br.Repo)
|
||||
if br.OrganizationID == "" {
|
||||
br.OrganizationID = e.Org // optional; server defaults to DEFAULT_BUILD_ORG_ID
|
||||
}
|
||||
@@ -419,32 +308,24 @@ func newBuildCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// k8s — deploy-target helpers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func newK8sCmd(envOf func() *Env, gf *globalFlags) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "k8s",
|
||||
Short: "Kubernetes deploy-target helpers",
|
||||
// normalizeRepoURL expands the idiomatic `owner/name` shorthand to a full GitHub
|
||||
// https URL (the platform build muscle clones https), and leaves an explicit URL
|
||||
// (http/https/git/ssh scheme, or a scp-style git@host:owner/name) untouched. Only
|
||||
// a bare single-segment `owner/name` — two path parts, no scheme, no host — is
|
||||
// expanded; anything else is the caller's explicit choice and passes through.
|
||||
func normalizeRepoURL(repo string) string {
|
||||
r := strings.TrimSpace(repo)
|
||||
if r == "" {
|
||||
return r
|
||||
}
|
||||
target := &cobra.Command{
|
||||
Use: "target",
|
||||
Short: "Show the org's current resolved deploy target (cluster + namespaces)",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
e := envOf()
|
||||
org, err := e.requireOrg()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := e.platform(gf).Target(cmd.Context(), org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.emit(t, func(w io.Writer) { printTarget(w, t) })
|
||||
},
|
||||
// Already a URL or scp-style remote → leave as-is.
|
||||
if strings.Contains(r, "://") || strings.Contains(r, "@") {
|
||||
return r
|
||||
}
|
||||
cmd.AddCommand(target)
|
||||
return cmd
|
||||
// Bare owner/name (exactly two non-empty segments, no host dot in the first).
|
||||
parts := strings.Split(strings.Trim(r, "/"), "/")
|
||||
if len(parts) == 2 && parts[0] != "" && parts[1] != "" && !strings.Contains(parts[0], ".") {
|
||||
return "https://github.com/" + parts[0] + "/" + parts[1]
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
+109
-32
@@ -8,6 +8,24 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeRepoURL(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"luxfi/wallet": "https://github.com/luxfi/wallet",
|
||||
"hanzoai/cloud": "https://github.com/hanzoai/cloud",
|
||||
"https://github.com/luxfi/wallet": "https://github.com/luxfi/wallet", // full URL untouched
|
||||
"git@github.com:luxfi/wallet.git": "git@github.com:luxfi/wallet.git", // scp-style untouched
|
||||
"https://gitlab.com/org/repo": "https://gitlab.com/org/repo", // non-github URL untouched
|
||||
"owner/name/extra": "owner/name/extra", // not a bare owner/name
|
||||
"single": "single", // not two segments
|
||||
"": "", // empty
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := normalizeRepoURL(in); got != want {
|
||||
t.Errorf("normalizeRepoURL(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// withPlatform points the CLI at an httptest platform via env (HANZO_PLATFORM_URL
|
||||
// + HANZO_PLATFORM_TOKEN), the same resolution path the real binary uses.
|
||||
func withPlatform(t *testing.T, h http.HandlerFunc) string {
|
||||
@@ -20,11 +38,15 @@ func withPlatform(t *testing.T, h http.HandlerFunc) string {
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
// apps list hits the LIVE board path /v1/paas/apps and renders the fleet table.
|
||||
func TestAppsListCommandTable(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/paas/apps" {
|
||||
t.Errorf("apps path = %s, want /v1/paas/apps", r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(AppsList{
|
||||
Apps: []AppView{
|
||||
{Org: "hanzoai", App: "iam", Env: "main", DeclaredTag: strptr("v1.2.3"), RunningTag: strptr("v1.2.3"), Health: strptr("green"), Drift: json.RawMessage(`{"severity":"ok"}`)},
|
||||
{Org: "hanzoai", App: "iam", Env: "main", DeclaredTag: "v1.2.3", RunningTag: "v1.2.3", Health: "green", Drift: json.RawMessage(`{"severity":"ok"}`)},
|
||||
},
|
||||
Summary: struct {
|
||||
Total int `json:"total"`
|
||||
@@ -43,6 +65,20 @@ func TestAppsListCommandTable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// apps list honors --env/--health/--drift as server query params (the board filters).
|
||||
func TestAppsListCommandFilters(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("env") != "main" || q.Get("health") != "red" || q.Get("drift") != "1" {
|
||||
t.Errorf("filters not forwarded: %s", r.URL.RawQuery)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(AppsList{})
|
||||
})
|
||||
if _, err := runRoot(t, "", "apps", "list", "--env", "main", "--health", "red", "--drift"); err != nil {
|
||||
t.Fatalf("apps list filters: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsListCommandJSON(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(AppsList{Apps: []AppView{{Org: "hanzoai", App: "iam", Env: "main"}}})
|
||||
@@ -60,69 +96,112 @@ func TestAppsListCommandJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// apps get hits /v1/paas/apps/{app}.
|
||||
func TestAppsGetCommand(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/paas/apps/iam" {
|
||||
t.Errorf("path = %s, want /v1/paas/apps/iam", r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(AppView{ID: "hanzoai/iam/main", Org: "hanzoai", App: "iam", Env: "main", DeclaredTag: "v1.2.3", Health: "green", Phase: "Running"})
|
||||
})
|
||||
out, err := runRoot(t, "", "apps", "get", "iam")
|
||||
if err != nil {
|
||||
t.Fatalf("apps get: %v", err)
|
||||
}
|
||||
for _, want := range []string{"hanzoai/iam/main", "Running", "v1.2.3"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("apps get missing %q in:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// deploy hits /v1/paas/apps/{app}/deploy — a rolling restart, org from identity.
|
||||
func TestDeployCommand(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/org/acme/project/p1/env/e1/container/app-x/redeploy" {
|
||||
t.Errorf("redeploy path = %s", r.URL.Path)
|
||||
if r.URL.Path != "/v1/paas/apps/app-x/deploy" || r.URL.Query().Get("env") != "main" {
|
||||
t.Errorf("redeploy request = %s?%s", r.URL.Path, r.URL.RawQuery)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
|
||||
w.WriteHeader(202)
|
||||
_ = json.NewEncoder(w).Encode(DeployResult{OK: true, App: "app-x", Namespace: "hanzo", Env: "main", RestartedAt: "2026-07-18T12:00:00Z"})
|
||||
})
|
||||
out, err := runRoot(t, "", "deploy", "app-x", "--org", "acme", "--project", "p1", "--env", "e1")
|
||||
out, err := runRoot(t, "", "deploy", "app-x", "--env", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("deploy: %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "redeployed app-x") {
|
||||
if !strings.Contains(out, "restarted app-x") || !strings.Contains(out, "namespace=hanzo") {
|
||||
t.Fatalf("deploy output: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployRequiresProjectEnv(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
|
||||
if _, err := runRoot(t, "", "deploy", "app-x", "--org", "acme"); err == nil {
|
||||
t.Fatalf("deploy must require --project/--env")
|
||||
// deploy REQUIRES --env — a bare deploy errors CLI-side, never silently prod.
|
||||
func TestDeployRequiresEnv(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) {
|
||||
t.Error("deploy without --env must not reach the server")
|
||||
w.WriteHeader(202)
|
||||
})
|
||||
if _, err := runRoot(t, "", "deploy", "app-x"); err == nil {
|
||||
t.Fatalf("deploy must require --env")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployRequiresOrg(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
|
||||
if _, err := runRoot(t, "", "deploy", "app-x", "--project", "p1", "--env", "e1"); err == nil {
|
||||
t.Fatalf("deploy must require an org")
|
||||
// deploy --env selects the lifecycle namespace via the ?env query param.
|
||||
func TestDeployCommandEnv(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/paas/apps/chat/deploy" || r.URL.Query().Get("env") != "test" {
|
||||
t.Errorf("deploy env request = %s?%s", r.URL.Path, r.URL.RawQuery)
|
||||
}
|
||||
w.WriteHeader(202)
|
||||
_ = json.NewEncoder(w).Encode(DeployResult{OK: true, App: "chat", Namespace: "hanzo-testnet", Env: "test", RestartedAt: "2026-07-18T12:00:00Z"})
|
||||
})
|
||||
if _, err := runRoot(t, "", "deploy", "chat", "--env", "test"); err != nil {
|
||||
t.Fatalf("deploy --env: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A non-ok deploy response is surfaced as an error.
|
||||
func TestDeployNotOK(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(DeployResult{OK: false})
|
||||
})
|
||||
if _, err := runRoot(t, "", "deploy", "app-x", "--env", "main"); err == nil {
|
||||
t.Fatalf("deploy must error when the server does not report ok")
|
||||
}
|
||||
}
|
||||
|
||||
// clusters list hits the LIVE /v1/clusters (org from identity, not the path).
|
||||
func TestClustersListCommand(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/org/acme/cluster" {
|
||||
t.Errorf("path = %s", r.URL.Path)
|
||||
if r.URL.Path != "/v1/clusters" {
|
||||
t.Errorf("path = %s, want /v1/clusters", r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"clusters": []Cluster{
|
||||
{DoksClusterID: "c1", Name: "hanzo-acme", Region: "sfo3", Status: "running", Phase: "ready", Active: true, OperatorInstalled: true, BaselineInstalled: true},
|
||||
{DoksClusterID: "c1", Name: "hanzo-acme", Region: "sfo3", Status: "running", Kind: "managed", NodeCount: 3, NodeSize: "s-2vcpu-4gb", NvidiaGPU: 2},
|
||||
}})
|
||||
})
|
||||
out, err := runRoot(t, "", "clusters", "list", "--org", "acme")
|
||||
out, err := runRoot(t, "", "clusters", "list")
|
||||
if err != nil {
|
||||
t.Fatalf("clusters list: %v", err)
|
||||
}
|
||||
for _, want := range []string{"NAME", "hanzo-acme", "c1", "ready", "yes"} {
|
||||
for _, want := range []string{"NAME", "hanzo-acme", "c1", "managed", "2 nvidia"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("clusters list missing %q in:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestK8sTargetCommand(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/org/acme/cluster/select" {
|
||||
t.Errorf("path = %s", r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"target": Target{Cluster: "hanzo-k8s", Dedicated: false, Namespaces: map[string]string{"hanzo": "main"}}})
|
||||
// clusters get filters the live list client-side by id or name.
|
||||
func TestClustersGetCommand(t *testing.T) {
|
||||
withPlatform(t, func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"clusters": []Cluster{
|
||||
{DoksClusterID: "c1", Name: "hanzo-acme", Region: "sfo3", Status: "running", Kind: "byo", NodeCount: 1},
|
||||
}})
|
||||
})
|
||||
out, err := runRoot(t, "", "k8s", "target", "--org", "acme")
|
||||
out, err := runRoot(t, "", "clusters", "get", "c1")
|
||||
if err != nil {
|
||||
t.Fatalf("k8s target: %v", err)
|
||||
t.Fatalf("clusters get: %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "hanzo-k8s") || !strings.Contains(out, "shared") {
|
||||
t.Fatalf("k8s target output: %q", out)
|
||||
if !strings.Contains(out, "hanzo-acme") || !strings.Contains(out, "byo") {
|
||||
t.Fatalf("clusters get output: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,5 +246,3 @@ func TestConfigSetGetCommand(t *testing.T) {
|
||||
t.Fatalf("config get = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func strptr(s string) *string { return &s }
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ package cli
|
||||
// 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.
|
||||
// the same /v1/models probe `hanzo link --serve-engine` advertises with.
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
+759
-116
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseRocmSmiCSV — the AMD GPU inventory names a card from its marketing
|
||||
// series + gfx target, exactly as `rocm-smi --showproductname --csv` reports on
|
||||
// evo's gfx1151 Radeon 8060S. This is the primary AMD detection path.
|
||||
func TestParseRocmSmiCSV(t *testing.T) {
|
||||
// Real evo output (header + one card row).
|
||||
csv := []byte("device,Card Series,Card Model,Card Vendor,Card SKU,Subsystem ID,Device Rev,Node ID,GUID,GFX Version\n" +
|
||||
"card0,Radeon 8060S Graphics,0x1586,Advanced Micro Devices Inc. [AMD/ATI],STRXLGEN,-0x7fe3,0xc1,1,49819,gfx1151\n")
|
||||
gpus := parseRocmSmiCSV(csv)
|
||||
if len(gpus) != 1 {
|
||||
t.Fatalf("want 1 AMD GPU, got %d (%+v)", len(gpus), gpus)
|
||||
}
|
||||
if got, want := gpus[0].Name, "Radeon 8060S Graphics (gfx1151)"; got != want {
|
||||
t.Errorf("name = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGfxNameDecodesTargetVersion — the kfd fallback decodes gfx_target_version.
|
||||
func TestGfxNameDecodesTargetVersion(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
v int
|
||||
want string
|
||||
}{
|
||||
{110501, "gfx1151"}, // evo Radeon 8060S / Strix Halo
|
||||
{90012, "gfx9012"}, // sanity: MI-class encoding shape
|
||||
{100300, "gfx1030"}, // RDNA2
|
||||
} {
|
||||
if got := gfxName(c.v); got != c.want {
|
||||
t.Errorf("gfxName(%d) = %q, want %q", c.v, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseKfdTopology — the driver-only fallback (no rocm-smi) still finds the GPU
|
||||
// from /sys/class/kfd: node 0 is the CPU (simd_count 0, skipped), node 1 is the
|
||||
// gfx1151 GPU. Built against a fixture tree mirroring evo's real properties files.
|
||||
func TestParseKfdTopology(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeNode(t, root, "0", "simd_count 0\ngfx_target_version 0\n")
|
||||
writeNode(t, root, "1", "cpu_cores_count 0\nsimd_count 80\ngfx_target_version 110501\n")
|
||||
gpus := parseKfdTopology(root)
|
||||
if len(gpus) != 1 {
|
||||
t.Fatalf("want 1 GPU node (CPU node 0 skipped), got %d (%+v)", len(gpus), gpus)
|
||||
}
|
||||
if got, want := gpus[0].Name, "AMD GPU (gfx1151)"; got != want {
|
||||
t.Errorf("name = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseVulkaninfoSummary — the last resort keeps only AMD/Radeon devices so it
|
||||
// never double-counts a card another vendor path already reported.
|
||||
func TestParseVulkaninfoSummary(t *testing.T) {
|
||||
out := []byte("GPU0:\n\tdeviceName = AMD Radeon Graphics (RADV GFX1151)\n" +
|
||||
"GPU1:\n\tdeviceName = llvmpipe (LLVM 18.1.0, 256 bits)\n")
|
||||
gpus := parseVulkaninfoSummary(out)
|
||||
if len(gpus) != 1 {
|
||||
t.Fatalf("want 1 AMD device (llvmpipe filtered), got %d (%+v)", len(gpus), gpus)
|
||||
}
|
||||
if got := gpus[0].Name; got != "AMD Radeon Graphics (RADV GFX1151)" {
|
||||
t.Errorf("name = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeNode(t *testing.T, root, id, props string) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(root, id)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "properties"), []byte(props), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ func TestBuildRegistrationCarriesEngine(t *testing.T) {
|
||||
jobsNS: "gpu-jobs",
|
||||
gpus: []gpuInfo{{Name: "NVIDIA GB10", MemoryTotal: "122880 MiB"}},
|
||||
serveEngine: true,
|
||||
studioReady: true,
|
||||
engineURL: srv.URL,
|
||||
engineAdvURL: "http://node.example:1234",
|
||||
}
|
||||
@@ -136,7 +137,7 @@ func TestBuildRegistrationCarriesEngine(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCapabilitiesWithoutEngine(t *testing.T) {
|
||||
w := &worker{serveEngine: false}
|
||||
w := &worker{serveEngine: false, studioReady: true}
|
||||
caps := w.capabilities()
|
||||
if len(caps) != 1 || caps[0] != studioCap {
|
||||
t.Fatalf("capabilities = %v, want just [%q] when not serving an engine", caps, studioCap)
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package cli
|
||||
|
||||
// gpu_queue_test.go — the per-GPU claim contract: a job pinned to THIS machine's
|
||||
// lane ("gpu:<identity>") is claimed BEFORE the shared any-GPU lane ("gpu-jobs"),
|
||||
// both within the gpu-jobs namespace. A stub cloud records the taskQueue of every
|
||||
// claim so the ORDER is the assertion.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// stubJobsCloud records the taskQueue of every claim and serves the queued job (if
|
||||
// any) on the matching lane, once. A lane with no job (or already drained) answers
|
||||
// 204; complete/fail/heartbeat answer 200.
|
||||
func stubJobsCloud(t *testing.T, claims *[]string, jobsByLane map[string]*claimedActivity) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/activities/claim") {
|
||||
var body struct {
|
||||
TaskQueue string `json:"taskQueue"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
*claims = append(*claims, body.TaskQueue)
|
||||
if job := jobsByLane[body.TaskQueue]; job != nil {
|
||||
jobsByLane[body.TaskQueue] = nil // deliver once
|
||||
_ = json.NewEncoder(w).Encode(job)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK) // complete / fail / heartbeat
|
||||
}))
|
||||
}
|
||||
|
||||
// echoJob is a GPU-free job the worker's echo handler runs to completion instantly,
|
||||
// so a claim test never needs a real render backend.
|
||||
func echoJob(id string) *claimedActivity {
|
||||
a := &claimedActivity{Input: json.RawMessage(`{}`)}
|
||||
a.Execution.WorkflowId, a.Execution.RunId = id, id
|
||||
a.Type.Name = "echo"
|
||||
return a
|
||||
}
|
||||
|
||||
func testWorker(t *testing.T, url string) *worker {
|
||||
t.Helper()
|
||||
t.Setenv("HANZO_TOKEN", "test-token") // ensureToken honors this; no `hanzo login`
|
||||
return &worker{
|
||||
env: &Env{CloudURL: url},
|
||||
http: &http.Client{Timeout: 5 * time.Second},
|
||||
baseURL: url,
|
||||
identity: "spark",
|
||||
hostname: "spark",
|
||||
jobsNS: "gpu-jobs",
|
||||
handlers: map[string]jobHandler{"echo": echoHandler},
|
||||
studioReady: true, // a render-capable node (preflight passed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGPUQueueLaneName(t *testing.T) {
|
||||
w := &worker{identity: "spark"}
|
||||
if got := w.gpuQueue(); got != "gpu:spark" {
|
||||
t.Fatalf("gpuQueue() = %q, want gpu:spark", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A job pinned to THIS GPU's lane is claimed first — the shared lane is not even
|
||||
// polled that cycle.
|
||||
func TestClaimPrefersTargetedLane(t *testing.T) {
|
||||
var claims []string
|
||||
srv := stubJobsCloud(t, &claims, map[string]*claimedActivity{"gpu:spark": echoJob("j1")})
|
||||
defer srv.Close()
|
||||
if err := testWorker(t, srv.URL).claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("claimAndRun: %v", err)
|
||||
}
|
||||
if len(claims) != 1 || claims[0] != "gpu:spark" {
|
||||
t.Fatalf("claims = %v, want exactly [gpu:spark] (targeted first; shared not polled)", claims)
|
||||
}
|
||||
}
|
||||
|
||||
// With its own lane empty, the worker falls through to the shared any-GPU lane.
|
||||
func TestClaimFallsBackToSharedLane(t *testing.T) {
|
||||
var claims []string
|
||||
srv := stubJobsCloud(t, &claims, map[string]*claimedActivity{"gpu-jobs": echoJob("j2")})
|
||||
defer srv.Close()
|
||||
if err := testWorker(t, srv.URL).claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("claimAndRun: %v", err)
|
||||
}
|
||||
if len(claims) != 2 || claims[0] != "gpu:spark" || claims[1] != "gpu-jobs" {
|
||||
t.Fatalf("claims = %v, want [gpu:spark gpu-jobs] (targeted, then shared)", claims)
|
||||
}
|
||||
}
|
||||
|
||||
// Both lanes empty polls targeted THEN shared and runs nothing.
|
||||
func TestClaimBothLanesEmpty(t *testing.T) {
|
||||
var claims []string
|
||||
srv := stubJobsCloud(t, &claims, map[string]*claimedActivity{})
|
||||
defer srv.Close()
|
||||
if err := testWorker(t, srv.URL).claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("claimAndRun: %v", err)
|
||||
}
|
||||
if len(claims) != 2 || claims[0] != "gpu:spark" || claims[1] != "gpu-jobs" {
|
||||
t.Fatalf("claims = %v, want [gpu:spark gpu-jobs]", claims)
|
||||
}
|
||||
}
|
||||
|
||||
// The render submit seam is the gated worker-mode execute path, not the open /prompt
|
||||
// — the shared contract with the studio's --worker-mode gate.
|
||||
func TestWorkerExecuteSeamIsGated(t *testing.T) {
|
||||
if localWorkerExecute != "http://127.0.0.1:8188/v1/worker/execute" {
|
||||
t.Fatalf("localWorkerExecute = %q, want the gated /v1/worker/execute seam", localWorkerExecute)
|
||||
}
|
||||
}
|
||||
|
||||
// A HUNG nvidia-smi (blocks until its bounded context fires) must NOT block the
|
||||
// caller: reportSample detaches the probe+POST onto a goroutine and returns at once,
|
||||
// so the worker's select loop keeps heartbeating and claiming. Guards the
|
||||
// worker-wedge regression (a synchronous probe that stalls the loop under GPU/driver
|
||||
// pressure → the machine flaps offline mid-render).
|
||||
func TestReportSampleNeverBlocksLoop(t *testing.T) {
|
||||
orig := nvidiaSmi
|
||||
defer func() { nvidiaSmi = orig }()
|
||||
probing := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
nvidiaSmi = func(ctx context.Context) ([]byte, error) {
|
||||
close(probing) // entered the probe (the nvidiaSmi var read already happened)
|
||||
select {
|
||||
case <-release: // the test lets us finish
|
||||
case <-ctx.Done(): // or the bounded probe timeout fires
|
||||
}
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
t.Setenv("HANZO_TOKEN", "t")
|
||||
w := &worker{identity: "spark", hostname: "spark", http: &http.Client{Timeout: time.Second}, env: &Env{}, baseURL: "http://127.0.0.1:0"}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { w.reportSample(context.Background()); close(done) }()
|
||||
select {
|
||||
case <-done: // returned immediately — the select loop is never wedged
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("reportSample blocked the caller — a hung sampler would wedge the worker loop")
|
||||
}
|
||||
select {
|
||||
case <-probing: // the probe really ran, on the detached goroutine (off the critical path)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("probe never started")
|
||||
}
|
||||
close(release)
|
||||
}
|
||||
|
||||
// A node that can't serve renders (preflight failed) claims NOTHING — it must never
|
||||
// pull a render job onto a box that will only refuse it on the gated seam (poison
|
||||
// loop). It still heartbeats presence; it just stays idle.
|
||||
func TestNotStudioReadyClaimsNothing(t *testing.T) {
|
||||
var claims []string
|
||||
srv := stubJobsCloud(t, &claims, map[string]*claimedActivity{"gpu:spark": echoJob("j1")})
|
||||
defer srv.Close()
|
||||
w := testWorker(t, srv.URL)
|
||||
w.studioReady = false
|
||||
if err := w.claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("claimAndRun: %v", err)
|
||||
}
|
||||
if len(claims) != 0 {
|
||||
t.Fatalf("a not-ready node claimed %v; want zero claims", claims)
|
||||
}
|
||||
}
|
||||
|
||||
// The terminal report must hit the RIGHT activity — namespace gpu-jobs, the CLAIMED
|
||||
// workflow+run ids, the correct verb. A stub that 200s every path lets an ns/id
|
||||
// routing regression pass, so assert the exact paths for both complete and fail.
|
||||
func TestTerminalReportsHitCorrectActivityPath(t *testing.T) {
|
||||
t.Setenv("HANZO_TOKEN", "t")
|
||||
var mu sync.Mutex
|
||||
terminal := map[string]string{}
|
||||
served := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/activities/claim"):
|
||||
var body struct {
|
||||
TaskQueue string `json:"taskQueue"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.TaskQueue != "gpu:spark" {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
n := served
|
||||
served++
|
||||
mu.Unlock()
|
||||
switch n {
|
||||
case 0:
|
||||
_ = json.NewEncoder(w).Encode(echoJob("wf1")) // echo handler → complete
|
||||
case 1:
|
||||
j := echoJob("wf2")
|
||||
j.Type.Name = "nope" // no handler → fail
|
||||
_ = json.NewEncoder(w).Encode(j)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
case strings.HasSuffix(r.URL.Path, "/complete"):
|
||||
mu.Lock()
|
||||
terminal["complete"] = r.URL.Path
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case strings.HasSuffix(r.URL.Path, "/fail"):
|
||||
mu.Lock()
|
||||
terminal["fail"] = r.URL.Path
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
w := testWorker(t, srv.URL)
|
||||
if err := w.claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("run1 (echo→complete): %v", err)
|
||||
}
|
||||
if err := w.claimAndRun(context.Background(), io.Discard); err != nil {
|
||||
t.Fatalf("run2 (unknown→fail): %v", err)
|
||||
}
|
||||
if got := terminal["complete"]; got != "/v1/tasks/namespaces/gpu-jobs/activities/wf1/wf1/complete" {
|
||||
t.Fatalf("complete path = %q, want the claimed activity's exact ns+ids", got)
|
||||
}
|
||||
if got := terminal["fail"]; got != "/v1/tasks/namespaces/gpu-jobs/activities/wf2/wf2/fail" {
|
||||
t.Fatalf("fail path = %q, want the claimed activity's exact ns+ids", got)
|
||||
}
|
||||
}
|
||||
|
||||
// SharePolicy.reject's fallback: an ABSENT or unparseable input field skips its gate
|
||||
// (permissive), never a hard error, so a policy only ever narrows on fields it can read.
|
||||
func TestSharePolicyRejectFallback(t *testing.T) {
|
||||
var nilp *SharePolicy
|
||||
if r := nilp.reject("studio.render", nil); r != "" {
|
||||
t.Fatalf("nil policy must allow everything: %q", r)
|
||||
}
|
||||
p := &SharePolicy{AllowedJobTypes: []string{"studio.render"}}
|
||||
if p.reject("echo", nil) == "" {
|
||||
t.Fatal("a disallowed job type must be rejected")
|
||||
}
|
||||
if r := p.reject("studio.render", nil); r != "" {
|
||||
t.Fatalf("an allowed job type must pass: %q", r)
|
||||
}
|
||||
p2 := &SharePolicy{AllowedOrgs: []string{"acme"}}
|
||||
if r := p2.reject("studio.render", json.RawMessage(`{}`)); r != "" {
|
||||
t.Fatalf("absent org must SKIP the org gate (fallback), not reject: %q", r)
|
||||
}
|
||||
if r := p2.reject("studio.render", json.RawMessage(`{"org":"acme"}`)); r != "" {
|
||||
t.Fatalf("a matching org must pass: %q", r)
|
||||
}
|
||||
if p2.reject("studio.render", json.RawMessage(`{"org":"other"}`)) == "" {
|
||||
t.Fatal("a non-allowed org must be rejected")
|
||||
}
|
||||
if r := p2.reject("studio.render", json.RawMessage(`not json`)); r != "" {
|
||||
t.Fatalf("unparseable input must skip input gates, not reject: %q", r)
|
||||
}
|
||||
}
|
||||
|
||||
// studioCap is advertised ONLY when the node can actually render: a missing worker
|
||||
// token is never ready (the gated seam would 403), and the block reason is explicit.
|
||||
func TestStudioReadyGatesCapability(t *testing.T) {
|
||||
t.Setenv("STUDIO_WORKER_TOKEN", "")
|
||||
w := &worker{launchesStudio: true, http: &http.Client{}}
|
||||
w.refreshStudioReady(context.Background())
|
||||
if w.studioReady {
|
||||
t.Fatal("no token must never be studio-ready")
|
||||
}
|
||||
if contains(w.capabilities(), studioCap) {
|
||||
t.Fatalf("studioCap advertised without a token: %v", w.capabilities())
|
||||
}
|
||||
if w.studioBlockReason() == "" {
|
||||
t.Fatal("a not-ready node must explain why it won't render")
|
||||
}
|
||||
// Token present + we launch the studio ⇒ ready ⇒ studioCap advertised.
|
||||
t.Setenv("STUDIO_WORKER_TOKEN", "tok")
|
||||
if changed := w.refreshStudioReady(context.Background()); !changed {
|
||||
t.Fatal("adding the token should flip readiness")
|
||||
}
|
||||
if !w.studioReady || !contains(w.capabilities(), studioCap) {
|
||||
t.Fatalf("token + launchesStudio must be ready + advertise studioCap: ready=%v caps=%v", w.studioReady, w.capabilities())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package cli
|
||||
|
||||
// gpu_spec_test.go — the host static-spec a `hanzo link` node reports so
|
||||
// GET /v1/fleet can show its CPU arch, core count and total RAM (the fields a
|
||||
// code-linked box already carries). Real telemetry only: arch is `uname -m`, cores
|
||||
// are runtime.NumCPU, RAM is parsed from the OS — never a hardcoded machine.
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseMemTotalKB(t *testing.T) {
|
||||
// A real /proc/meminfo head from a 128 GiB box. MemTotal is in kB; we report bytes.
|
||||
meminfo := []byte("MemTotal: 131923980 kB\nMemFree: 1048576 kB\nMemAvailable: 120000000 kB\n")
|
||||
if got, want := parseMemTotalKB(meminfo), int64(131923980)*1024; got != want {
|
||||
t.Fatalf("parseMemTotalKB = %d, want %d bytes", got, want)
|
||||
}
|
||||
// Absent / malformed input is reported as 0 (unknown), never a guess.
|
||||
for name, in := range map[string]string{
|
||||
"empty": "",
|
||||
"no-memtotal": "MemFree: 100 kB\n",
|
||||
"malformed": "MemTotal: notanumber kB\n",
|
||||
"no-value": "MemTotal:\n",
|
||||
} {
|
||||
if got := parseMemTotalKB([]byte(in)); got != 0 {
|
||||
t.Fatalf("%s: parseMemTotalKB = %d, want 0", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// detectMemTotal reads the real host, so on Linux/macOS CI it must return a positive
|
||||
// byte count — proof the reporter reads actual RAM rather than shipping 0.
|
||||
func TestDetectMemTotalIsReal(t *testing.T) {
|
||||
if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
|
||||
t.Skipf("no MemTotal source on %s", runtime.GOOS)
|
||||
}
|
||||
got := detectMemTotal()
|
||||
if got <= 0 {
|
||||
t.Fatalf("detectMemTotal = %d, want the host's real RAM (>0)", got)
|
||||
}
|
||||
// Evidence: what THIS host actually reports (never hardcoded). On the GB10 spark
|
||||
// box this prints aarch64 + ~128 GiB read from /proc/meminfo.
|
||||
t.Logf("real host spec: arch=%s cpus=%d memory=%d bytes (%.1f GiB)",
|
||||
detectArch(), runtime.NumCPU(), got, float64(got)/(1<<30))
|
||||
}
|
||||
|
||||
// detectArch must match the fleet's `uname -m` convention (aarch64 | x86_64 | arm64),
|
||||
// NOT runtime.GOARCH (arm64 | amd64) — so a machine that appears as both a run-target
|
||||
// and a linked worker shows ONE arch string on the board. On Linux uname -m is
|
||||
// aarch64/x86_64; assert the real host agrees and is never GOARCH's amd64.
|
||||
func TestDetectArchMatchesUnameConvention(t *testing.T) {
|
||||
got := detectArch()
|
||||
if got == "" {
|
||||
t.Fatal("detectArch returned empty; must fall back to runtime.GOARCH")
|
||||
}
|
||||
if out, err := exec.Command("uname", "-m").Output(); err == nil {
|
||||
if want := strings.TrimSpace(string(out)); want != "" && got != want {
|
||||
t.Fatalf("detectArch = %q, want `uname -m` %q (fleet convention)", got, want)
|
||||
}
|
||||
}
|
||||
// Guard the regression this test exists for: on Linux amd64 the value must be
|
||||
// x86_64, never GOARCH's "amd64".
|
||||
if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" && got == "amd64" {
|
||||
t.Fatal("arch is GOARCH 'amd64'; the fleet convention is 'x86_64'")
|
||||
}
|
||||
t.Logf("detectArch=%q (GOARCH=%q)", got, runtime.GOARCH)
|
||||
}
|
||||
|
||||
// buildRegistration must carry this host's detected arch (uname -m), cores (NumCPU)
|
||||
// and RAM — so spark reports aarch64 and evo-2 reports x86_64, both ~128 GB, matching
|
||||
// how the same machines already report as code-linked run-targets.
|
||||
func TestBuildRegistrationCarriesHostSpec(t *testing.T) {
|
||||
const mem = int64(137438953472) // 128 GiB
|
||||
w := &worker{hostname: "spark", jobsNS: "gpu-jobs", arch: "aarch64", memory: mem}
|
||||
reg := w.buildRegistration()
|
||||
if reg.Arch != "aarch64" {
|
||||
t.Fatalf("Arch = %q, want the worker's detected arch %q", reg.Arch, "aarch64")
|
||||
}
|
||||
if reg.CPUs != runtime.NumCPU() {
|
||||
t.Fatalf("CPUs = %d, want runtime.NumCPU %d", reg.CPUs, runtime.NumCPU())
|
||||
}
|
||||
if reg.Memory != mem {
|
||||
t.Fatalf("Memory = %d, want the detected total %d", reg.Memory, mem)
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package cli
|
||||
|
||||
// link.go — `hanzo link | unlink | status`: bring THIS machine into the Hanzo
|
||||
// cloud fleet AS A NODE, take it back out, and view the fleet.
|
||||
//
|
||||
// A node is two orthogonal memberships, composed under one verb:
|
||||
//
|
||||
// 1. The FABRIC — hanzod on hanzo.network. `link` starts it by invoking the
|
||||
// canonical fabric verb `hanzo node up` (the Rust node CLI: resolve a hanzod
|
||||
// binary, spawn it detached, record its pid). link does NOT reimplement hanzod
|
||||
// supervision — there is exactly one way to start hanzod, and this composes it.
|
||||
// Best-effort: a node with no hanzod still joins the compute fleet (CPU-only
|
||||
// boxes and dev machines link fine); `--no-fabric` skips it outright.
|
||||
//
|
||||
// 2. The COMPUTE fleet — this machine's inventory (CPU cores + model, memory, and
|
||||
// each GPU as its own resource) registered as a heartbeating presence in the
|
||||
// org's `fleet` namespace, running the outbound worker loop that claims jobs
|
||||
// from `gpu-jobs`. That machinery lives in gpu.go (runConnect); `link` runs it.
|
||||
//
|
||||
// `unlink` reverses both: it deregisters the worker (drops the fleet row), then
|
||||
// stops the fabric (`hanzo node stop`). `status` is the fleet view — every machine
|
||||
// with each of its GPUs shown distinctly, this box highlighted.
|
||||
//
|
||||
// One identity: the IAM token `hanzo login` mints authorizes every cloud call; the
|
||||
// server derives the tenant from the token. No secrets on the box.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// link / unlink / status — the node-level command surface.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func newLinkCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
|
||||
var opts connectOpts
|
||||
var daemon bool
|
||||
var noFabric bool
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "link",
|
||||
Short: "Bring this machine into the Hanzo cloud fleet as a node",
|
||||
Long: "Link this machine into the Hanzo cloud as a node: join the fabric (start\n" +
|
||||
"hanzod on hanzo.network) and register as a compute worker — advertising this\n" +
|
||||
"host's CPU (cores + model), memory, and each GPU as its own resource, then\n" +
|
||||
"heartbeating and claiming jobs from your org's queue. The node shows up in the\n" +
|
||||
"console (Machines + GPUs) and on `hanzo status`. Works on a CPU-only box.\n" +
|
||||
"Authentication reuses the `hanzo login` token; the org is taken from its claims.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if daemon {
|
||||
return installDaemon(cmd, opts)
|
||||
}
|
||||
// 1. Fabric: start hanzod via the canonical `hanzo node up` (best-effort).
|
||||
startFabric(cmd, noFabric)
|
||||
// 2. Compute fleet: register inventory, heartbeat, claim jobs (foreground).
|
||||
return runConnect(cmd, envOf(), opts)
|
||||
},
|
||||
}
|
||||
|
||||
f := cmd.Flags()
|
||||
f.StringVar(&opts.jobsNS, "jobs-namespace", defaultJobsNS, "tasks namespace to claim jobs from")
|
||||
f.BoolVar(&noFabric, "no-fabric", false, "join the compute fleet only; do not start hanzod")
|
||||
f.BoolVar(&daemon, "daemon", false, "install a systemd --user unit (Restart=always) instead of running in the foreground")
|
||||
f.BoolVar(&opts.serveEngine, "serve-engine", false, "also advertise a hanzo-engine model server (OpenAI + Anthropic) running on this node")
|
||||
f.StringVar(&opts.engineURL, "engine-url", defaultEngineURL, "local URL where hanzo-engine is probed (GET /v1/models)")
|
||||
f.StringVar(&opts.engineEndpoint, "engine-endpoint", "", "public URL to advertise for gateway routing (defaults to --engine-url; a node behind NAT needs a reachable URL/tunnel)")
|
||||
f.BoolVar(&opts.registerProvider, "register-provider", false, "auto-register the engine endpoint as an org model provider (POST /v1/add-provider)")
|
||||
f.StringVar(&opts.studioDir, "studio-dir", os.Getenv("HANZO_STUDIO_DIR"), "local Hanzo Studio checkout; when set, link launches and supervises the render backend on 127.0.0.1:8188")
|
||||
f.StringVar(&opts.studioURL, "studio-url", firstNonEmpty(os.Getenv("HANZO_STUDIO_UPLOAD_URL"), defaultStudioUploadURL), "studio base URL the render mirror uploads finished images to (POST /v1/library/upload)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newUnlinkCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "unlink",
|
||||
Short: "Take this machine out of the fleet (deregister + stop hanzod)",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
// Reverse of link, both best-effort: drop the compute-fleet row, then
|
||||
// ALWAYS stop the fabric so a deregister error never leaves hanzod
|
||||
// running. The deregister error is reported, not short-circuited.
|
||||
derr := runDisconnect(cmd, envOf())
|
||||
stopFabric(cmd)
|
||||
return derr
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newStatusCmd(envOf func() *Env, _ *globalFlags) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "Show the org's fleet — every machine with each of its GPUs (this box highlighted)",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error { return runFleetStatus(cmd, envOf()) },
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fabric — compose the canonical `hanzo node up` / `node stop`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// fabricCLI resolves the Hanzo node CLI that owns hanzod supervision — the Rust
|
||||
// fabric/dev CLI with `node up/stop`. In the canonical layout the Go unified binary
|
||||
// takes the `hanzo` name and the Rust CLI is installed alongside it as `hanzo-node`,
|
||||
// so `link` composes `node up` without shelling into itself (this binary has no
|
||||
// `node`). Resolution order: HANZO_FABRIC_CLI, then `hanzo-node`, then a
|
||||
// self-guarded `hanzo` (for boxes where the Rust CLI still holds the `hanzo` name).
|
||||
// Returns "" when none is resolvable.
|
||||
func fabricCLI() string {
|
||||
if p := os.Getenv("HANZO_FABRIC_CLI"); p != "" {
|
||||
return p
|
||||
}
|
||||
if p, err := exec.LookPath("hanzo-node"); err == nil {
|
||||
return p
|
||||
}
|
||||
p, err := exec.LookPath("hanzo")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if self, err := os.Executable(); err == nil {
|
||||
if sp, _ := os.Readlink(p); sp == self || p == self {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Passthrough delegates a verb this binary does not own — node, dev, wallet,
|
||||
// network, … — to the Rust fabric/dev CLI (resolved by fabricCLI, installed as
|
||||
// `hanzo-node`), so the single `hanzo` name is a SUPERSET: Go verbs served natively,
|
||||
// everything else handed through unchanged. `hanzo node up` (the fabric `link`
|
||||
// itself composes) works for users too. It runs the delegate to completion with
|
||||
// inherited stdio and exits with its code; it returns false only when no fabric CLI
|
||||
// is resolvable, so the caller can report unknown-subcommand.
|
||||
func Passthrough(args []string) bool {
|
||||
bin := fabricCLI()
|
||||
if bin == "" {
|
||||
return false
|
||||
}
|
||||
c := exec.Command(bin, args...)
|
||||
c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
if err := c.Run(); err != nil {
|
||||
var ee *exec.ExitError
|
||||
if errors.As(err, &ee) {
|
||||
os.Exit(ee.ExitCode())
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "hanzo: delegating %v to %s: %v\n", args, bin, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
return true
|
||||
}
|
||||
|
||||
// startFabric starts hanzod by invoking `hanzo node up` — the one canonical way to
|
||||
// join the fabric. Best-effort by design: a missing CLI or a missing hanzod prints
|
||||
// a clear note and the node still joins the compute fleet. `--no-fabric` skips it.
|
||||
func startFabric(cmd *cobra.Command, skip bool) {
|
||||
out := cmd.OutOrStdout()
|
||||
if skip {
|
||||
fmt.Fprintln(out, "fabric: skipped (--no-fabric); joining the compute fleet only")
|
||||
return
|
||||
}
|
||||
bin := fabricCLI()
|
||||
if bin == "" {
|
||||
fmt.Fprintln(out, "fabric: hanzo node CLI not found — joining the compute fleet only")
|
||||
fmt.Fprintln(out, " (install the `hanzo` node CLI or set HANZO_FABRIC_CLI to start hanzod)")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(cmd.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
c := exec.CommandContext(ctx, bin, "node", "up")
|
||||
c.Stdout, c.Stderr = out, cmd.ErrOrStderr()
|
||||
if err := c.Run(); err != nil {
|
||||
fmt.Fprintf(out, "fabric: `%s node up` did not start hanzod (%v) — joining the compute fleet only\n", bin, err)
|
||||
}
|
||||
}
|
||||
|
||||
// stopFabric stops the hanzod this box started, via the canonical `hanzo node stop`.
|
||||
// Best-effort — nothing to stop is not an error.
|
||||
func stopFabric(cmd *cobra.Command) {
|
||||
out := cmd.OutOrStdout()
|
||||
bin := fabricCLI()
|
||||
if bin == "" {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
c := exec.CommandContext(ctx, bin, "node", "stop")
|
||||
c.Stdout, c.Stderr = out, cmd.ErrOrStderr()
|
||||
_ = c.Run()
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// TestUnlinkIdempotent — a repeat `hanzo unlink` is a no-op. The deregister POST
|
||||
// hitting an already-terminal (409) or absent (404) fleet row is the desired end
|
||||
// state, so runDisconnect returns nil (not an error) and says so, letting `unlink`
|
||||
// be run twice safely.
|
||||
func TestUnlinkIdempotent(t *testing.T) {
|
||||
for _, code := range []int{http.StatusConflict, http.StatusNotFound} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write([]byte(`{"error":"activity terminal"}`))
|
||||
}))
|
||||
|
||||
t.Setenv("HANZO_TOKEN", "test-token") // ensureToken honors this; no login needed
|
||||
var out bytes.Buffer
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(context.Background())
|
||||
cmd.SetOut(&out)
|
||||
|
||||
if err := runDisconnect(cmd, &Env{CloudURL: srv.URL}); err != nil {
|
||||
t.Errorf("HTTP %d: runDisconnect should be idempotent (nil), got %v", code, err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "already unlinked") {
|
||||
t.Errorf("HTTP %d: want 'already unlinked' notice, got %q", code, out.String())
|
||||
}
|
||||
srv.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnlinkDeregisterErrorSurfaces — a non-terminal deregister failure (e.g. 500)
|
||||
// is a real error and must be returned, not swallowed as idempotent success.
|
||||
func TestUnlinkDeregisterErrorSurfaces(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"error":"boom"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
t.Setenv("HANZO_TOKEN", "test-token")
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(context.Background())
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
|
||||
if err := runDisconnect(cmd, &Env{CloudURL: srv.URL}); err == nil {
|
||||
t.Fatal("a 500 deregister must surface an error, got nil")
|
||||
}
|
||||
}
|
||||
+110
-132
@@ -12,11 +12,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Platform is a thin client over the platform.hanzo.ai /v1 control plane. That
|
||||
// surface is machine-to-machine (service-token, "No OIDC" — it cannot validate
|
||||
// IAM user tokens), so the token here is the platform service token, resolved
|
||||
// from flag/env/credential store by the caller; the build endpoint takes its
|
||||
// own token per call.
|
||||
// Platform is a thin client over the LIVE Hanzo Cloud control plane
|
||||
// (platform.hanzo.ai / api.hanzo.ai → svc `cloud`, the Go binary). Every route it
|
||||
// calls is served by that one binary and authorized off ONE IAM identity: after
|
||||
// `hanzo login` the CLI sends the IAM access token as the bearer, and the cloud's
|
||||
// identity middleware (SanitizeIdentity) validates the JWT and org-scopes the
|
||||
// caller — no separate platform/service token. A purpose-minted machine token
|
||||
// still works (flag > env > credential store > IAM login) for automation.
|
||||
type Platform struct {
|
||||
baseURL string
|
||||
token string
|
||||
@@ -45,8 +47,8 @@ func (e *apiError) Error() string {
|
||||
msg = http.StatusText(e.status)
|
||||
}
|
||||
hint := ""
|
||||
if e.status == http.StatusUnauthorized {
|
||||
hint = " (set the platform service token: --platform-token, HANZO_PLATFORM_TOKEN, or `hanzo login --platform-token`)"
|
||||
if e.status == http.StatusUnauthorized || e.status == http.StatusForbidden {
|
||||
hint = " (run `hanzo login` — your IAM identity authorizes the platform; admin ops need an org-admin or superadmin identity)"
|
||||
}
|
||||
return fmt.Sprintf("platform %s: HTTP %d: %s%s", e.path, e.status, msg, hint)
|
||||
}
|
||||
@@ -55,7 +57,7 @@ func (e *apiError) Error() string {
|
||||
// into out (when non-nil) and mapping a non-2xx into an *apiError.
|
||||
func (p *Platform) do(ctx context.Context, method, path, token string, body, out any) error {
|
||||
if token == "" {
|
||||
return fmt.Errorf("no platform token: pass --platform-token, set HANZO_PLATFORM_TOKEN, or run `hanzo login --platform-token <tok>`")
|
||||
return fmt.Errorf("not authenticated: run `hanzo login` (an IAM login now authorizes the platform; a --platform-token / HANZO_PLATFORM_TOKEN still works for machine automation)")
|
||||
}
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
@@ -94,8 +96,8 @@ func (p *Platform) do(ctx context.Context, method, path, token string, body, out
|
||||
return nil
|
||||
}
|
||||
|
||||
// serverMessage pulls the `{ "message": … }` field platform errors use, falling
|
||||
// back to the raw (truncated) body.
|
||||
// serverMessage pulls the `{ "message": … }` / `{ "error": … }` field the cloud's
|
||||
// errors use, falling back to the raw (truncated) body.
|
||||
func serverMessage(raw []byte) string {
|
||||
var e struct {
|
||||
Message string `json:"message"`
|
||||
@@ -117,33 +119,35 @@ func serverMessage(raw []byte) string {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Apps board — GET /v1/apps, GET /v1/apps/{id}, POST /v1/apps/sync.
|
||||
// Apps board — GET /v1/paas/apps, GET /v1/paas/apps/{app}. The live Go cloud's
|
||||
// fleet drift board (clients/paas): the operator App CRs across the platform
|
||||
// namespaces, declared/running/latest tags + health + the drift verdict. It is
|
||||
// org-confined server-side (a SuperAdmin sees the fleet; an OrgAdmin only its own
|
||||
// org), so the CLI sends NO org filter — identity scopes the view.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// AppView mirrors the platform apps-lifecycle DTO. Nullable columns are *string
|
||||
// so JSON null round-trips; Drift is kept raw so --json is byte-faithful and
|
||||
// the drift schema can evolve without a client bump.
|
||||
// AppView mirrors clients/paas.AppView (the LIVE board DTO). Tags/health are plain
|
||||
// strings ("" == unknown, rendered "-"); Drift is kept raw so --json is
|
||||
// byte-faithful and the drift schema can evolve without a client bump.
|
||||
type AppView struct {
|
||||
ID string `json:"id"`
|
||||
Org string `json:"org"`
|
||||
App string `json:"app"`
|
||||
Env string `json:"env"`
|
||||
Repo string `json:"repo"`
|
||||
Registry string `json:"registry"`
|
||||
DeclaredTag *string `json:"declaredTag"`
|
||||
RunningTag *string `json:"runningTag"`
|
||||
LatestTag *string `json:"latestTag"`
|
||||
ReleaseURL *string `json:"releaseUrl"`
|
||||
ReleaseAssets int `json:"releaseAssets"`
|
||||
Health *string `json:"health"`
|
||||
Cluster *string `json:"cluster"`
|
||||
Namespace *string `json:"namespace"`
|
||||
LastObserved *string `json:"lastObserved"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
Drift json.RawMessage `json:"drift"`
|
||||
ID string `json:"id"` // <org>/<app>/<env>, e.g. hanzoai/iam/main
|
||||
Org string `json:"org"` // image namespace, e.g. hanzoai
|
||||
App string `json:"app"`
|
||||
Env string `json:"env"`
|
||||
Repo string `json:"repo"`
|
||||
Registry string `json:"registry"`
|
||||
DeclaredTag string `json:"declaredTag"`
|
||||
RunningTag string `json:"runningTag"`
|
||||
LatestTag string `json:"latestTag"`
|
||||
Health string `json:"health"`
|
||||
Phase string `json:"phase"`
|
||||
Cluster string `json:"cluster"`
|
||||
Namespace string `json:"namespace"`
|
||||
Endpoints []string `json:"endpoints"`
|
||||
Drift json.RawMessage `json:"drift"`
|
||||
}
|
||||
|
||||
// AppsList is the /v1/apps envelope: ordered rows + a drift summary.
|
||||
// AppsList is the /v1/paas/apps envelope: ordered rows + a drift summary.
|
||||
type AppsList struct {
|
||||
Apps []AppView `json:"apps"`
|
||||
Summary struct {
|
||||
@@ -152,9 +156,10 @@ type AppsList struct {
|
||||
} `json:"summary"`
|
||||
}
|
||||
|
||||
// AppsQuery are the optional /v1/apps filters.
|
||||
// AppsQuery are the optional /v1/paas/apps filters (server-honored). Env/Health/
|
||||
// Drift narrow the board; there is deliberately no org filter — the board is
|
||||
// confined to the caller's org by the validated identity, never a client value.
|
||||
type AppsQuery struct {
|
||||
Org string
|
||||
Env string
|
||||
Health string
|
||||
Drift bool
|
||||
@@ -162,9 +167,6 @@ type AppsQuery struct {
|
||||
|
||||
func (p *Platform) Apps(ctx context.Context, q AppsQuery) (*AppsList, error) {
|
||||
v := url.Values{}
|
||||
if q.Org != "" {
|
||||
v.Set("org", q.Org)
|
||||
}
|
||||
if q.Env != "" {
|
||||
v.Set("env", q.Env)
|
||||
}
|
||||
@@ -174,7 +176,7 @@ func (p *Platform) Apps(ctx context.Context, q AppsQuery) (*AppsList, error) {
|
||||
if q.Drift {
|
||||
v.Set("drift", "1")
|
||||
}
|
||||
path := "/v1/apps"
|
||||
path := "/v1/paas/apps"
|
||||
if len(v) > 0 {
|
||||
path += "?" + v.Encode()
|
||||
}
|
||||
@@ -182,17 +184,11 @@ func (p *Platform) Apps(ctx context.Context, q AppsQuery) (*AppsList, error) {
|
||||
return out, p.do(ctx, http.MethodGet, path, p.token, nil, out)
|
||||
}
|
||||
|
||||
func (p *Platform) App(ctx context.Context, id, org string) (*AppView, error) {
|
||||
path := "/v1/apps/" + id
|
||||
if org != "" {
|
||||
path += "?org=" + url.QueryEscape(org)
|
||||
}
|
||||
// App gets one app row by its <app> CR name (production by default; the server
|
||||
// scans the caller's authorized namespaces main→test→dev).
|
||||
func (p *Platform) App(ctx context.Context, app string) (*AppView, error) {
|
||||
out := &AppView{}
|
||||
return out, p.do(ctx, http.MethodGet, path, p.token, nil, out)
|
||||
}
|
||||
|
||||
func (p *Platform) SyncApps(ctx context.Context) error {
|
||||
return p.do(ctx, http.MethodPost, "/v1/apps/sync", p.token, nil, nil)
|
||||
return out, p.do(ctx, http.MethodGet, "/v1/paas/apps/"+url.PathEscape(app), p.token, nil, out)
|
||||
}
|
||||
|
||||
// driftSeverity extracts the severity string from the raw drift object.
|
||||
@@ -207,110 +203,92 @@ func driftSeverity(raw json.RawMessage) string {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dedicated clusters — /v1/org/{org}/cluster[ /select | /{id}/install-baseline ].
|
||||
// Clusters — GET /v1/clusters. The live Go cloud's compute fleet (clients/visor):
|
||||
// Visor-managed node pools + the org's BYO clusters, tenant-scoped server-side by
|
||||
// the validated org (?owner is the caller's IAM org). No org in the path.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Cluster mirrors a doks_cluster record. `status` is DigitalOcean state; `phase`
|
||||
// is the platform provisioning lifecycle — orthogonal (a DO-running cluster is
|
||||
// not a usable target until phase=ready).
|
||||
// NodePool mirrors clients/visor.nodePoolView.
|
||||
type NodePool struct {
|
||||
PoolID string `json:"poolId"`
|
||||
Name string `json:"name"`
|
||||
Size string `json:"size"`
|
||||
Count int `json:"count"`
|
||||
MinNodes int `json:"minNodes"`
|
||||
MaxNodes int `json:"maxNodes"`
|
||||
AutoScale bool `json:"autoScale"`
|
||||
}
|
||||
|
||||
// Cluster mirrors clients/visor.clusterView — the LIVE cluster DTO. `kind` is
|
||||
// "managed" (Visor-provisioned) or "byo" (attached kubeconfig).
|
||||
type Cluster struct {
|
||||
DoksClusterID string `json:"doksClusterId"`
|
||||
Name string `json:"name"`
|
||||
DoClusterID *string `json:"doClusterId"`
|
||||
Region string `json:"region"`
|
||||
Status string `json:"status"`
|
||||
Endpoint *string `json:"endpoint"`
|
||||
K8sVersion *string `json:"k8sVersion"`
|
||||
HA bool `json:"ha"`
|
||||
Phase string `json:"phase"`
|
||||
OperatorInstalled bool `json:"operatorInstalled"`
|
||||
BaselineInstalled bool `json:"baselineInstalled"`
|
||||
Active bool `json:"active"`
|
||||
BaselineError *string `json:"baselineError"`
|
||||
OrganizationID string `json:"organizationId"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
Tags []string `json:"tags"`
|
||||
MaintenancePolicy json.RawMessage `json:"maintenancePolicy,omitempty"`
|
||||
DoksClusterID string `json:"doksClusterId"`
|
||||
DoClusterID string `json:"doClusterId"`
|
||||
Name string `json:"name"`
|
||||
Region string `json:"region"`
|
||||
Status string `json:"status"`
|
||||
NodePools []NodePool `json:"nodePools"`
|
||||
NodeSize string `json:"nodeSize"`
|
||||
NodeCount int `json:"nodeCount"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
Kind string `json:"kind"`
|
||||
NvidiaGPU int `json:"nvidiaGpu"`
|
||||
AmdGPU int `json:"amdGpu"`
|
||||
}
|
||||
|
||||
// ProvisionReq is the dedicated-cluster provisioning body (org forced by path).
|
||||
type ProvisionReq struct {
|
||||
Region string `json:"region,omitempty"`
|
||||
HA bool `json:"ha,omitempty"`
|
||||
NodeSize string `json:"nodeSize,omitempty"`
|
||||
NodeCount int `json:"nodeCount,omitempty"`
|
||||
// ID is the stable cluster identifier for display/lookup: the DOKS id when managed,
|
||||
// else the name (a BYO cluster keys on its attached name).
|
||||
func (c Cluster) ID() string {
|
||||
if c.DoksClusterID != "" {
|
||||
return c.DoksClusterID
|
||||
}
|
||||
return c.Name
|
||||
}
|
||||
|
||||
// Target is the redacted ClusterTargetView — the kubeconfig is never present.
|
||||
type Target struct {
|
||||
Cluster string `json:"cluster"`
|
||||
Namespaces map[string]string `json:"namespaces"`
|
||||
Dedicated bool `json:"dedicated"`
|
||||
}
|
||||
|
||||
func (p *Platform) Clusters(ctx context.Context, org string) ([]Cluster, error) {
|
||||
func (p *Platform) Clusters(ctx context.Context) ([]Cluster, error) {
|
||||
var out struct {
|
||||
Clusters []Cluster `json:"clusters"`
|
||||
}
|
||||
err := p.do(ctx, http.MethodGet, "/v1/org/"+url.PathEscape(org)+"/cluster", p.token, nil, &out)
|
||||
err := p.do(ctx, http.MethodGet, "/v1/clusters", p.token, nil, &out)
|
||||
return out.Clusters, err
|
||||
}
|
||||
|
||||
func (p *Platform) ProvisionCluster(ctx context.Context, org string, req ProvisionReq) (*Cluster, error) {
|
||||
var out struct {
|
||||
Cluster Cluster `json:"cluster"`
|
||||
}
|
||||
err := p.do(ctx, http.MethodPost, "/v1/org/"+url.PathEscape(org)+"/cluster", p.token, req, &out)
|
||||
return &out.Cluster, err
|
||||
}
|
||||
|
||||
func (p *Platform) Target(ctx context.Context, org string) (*Target, error) {
|
||||
var out struct {
|
||||
Target Target `json:"target"`
|
||||
}
|
||||
err := p.do(ctx, http.MethodGet, "/v1/org/"+url.PathEscape(org)+"/cluster/select", p.token, nil, &out)
|
||||
return &out.Target, err
|
||||
}
|
||||
|
||||
// SelectTarget activates a dedicated cluster as the org's deploy target, or
|
||||
// reverts to the shared cluster when clusterID is nil.
|
||||
func (p *Platform) SelectTarget(ctx context.Context, org string, clusterID *string) (*Target, error) {
|
||||
var out struct {
|
||||
Target Target `json:"target"`
|
||||
}
|
||||
body := map[string]any{"doksClusterId": clusterID}
|
||||
err := p.do(ctx, http.MethodPost, "/v1/org/"+url.PathEscape(org)+"/cluster/select", p.token, body, &out)
|
||||
return &out.Target, err
|
||||
}
|
||||
|
||||
func (p *Platform) InstallBaseline(ctx context.Context, org, clusterID string) error {
|
||||
path := "/v1/org/" + url.PathEscape(org) + "/cluster/" + url.PathEscape(clusterID) + "/install-baseline"
|
||||
return p.do(ctx, http.MethodPost, path, p.token, nil, nil)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Deploy — POST …/container/{id}/redeploy (rolling restart, zero-downtime).
|
||||
// Deploy — POST /v1/paas/apps/{app}/deploy: a zero-downtime ROLLING RESTART of the
|
||||
// app's Deployment (re-pulls the declared image, recreates pods). Org-confined
|
||||
// server-side; an optional env selects the lifecycle namespace (main|test|dev).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Redeploy triggers a rolling restart of the container's k8s Deployment. The
|
||||
// coordinates are exact (the platform validates org+project+env+container scope).
|
||||
func (p *Platform) Redeploy(ctx context.Context, org, project, env, container string) error {
|
||||
path := fmt.Sprintf("/v1/org/%s/project/%s/env/%s/container/%s/redeploy",
|
||||
url.PathEscape(org), url.PathEscape(project), url.PathEscape(env), url.PathEscape(container))
|
||||
var out struct {
|
||||
OK bool `json:"ok"`
|
||||
// Redeploy triggers a rolling restart of the named app. env is optional
|
||||
// (main|test|dev); empty targets production (the first match, main→test→dev).
|
||||
func (p *Platform) Redeploy(ctx context.Context, app, env string) (*DeployResult, error) {
|
||||
path := "/v1/paas/apps/" + url.PathEscape(app) + "/deploy"
|
||||
if env != "" {
|
||||
path += "?env=" + url.QueryEscape(env)
|
||||
}
|
||||
if err := p.do(ctx, http.MethodPost, path, p.token, nil, &out); err != nil {
|
||||
return err
|
||||
out := &DeployResult{}
|
||||
if err := p.do(ctx, http.MethodPost, path, p.token, nil, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !out.OK {
|
||||
return fmt.Errorf("redeploy did not report ok")
|
||||
return nil, fmt.Errorf("redeploy did not report ok")
|
||||
}
|
||||
return nil
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DeployResult is the /deploy acceptance (202): the restarted app + its namespace.
|
||||
type DeployResult struct {
|
||||
OK bool `json:"ok"`
|
||||
App string `json:"app"`
|
||||
Namespace string `json:"namespace"`
|
||||
Env string `json:"env"`
|
||||
RestartedAt string `json:"restartedAt"`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Build — POST /v1/runner (platform-native CI, no GitHub builders).
|
||||
// Build — POST /v1/runner (platform-native CI, no GitHub builders). Authorized off
|
||||
// the IAM login exactly like the surfaces above (or a dedicated build token for
|
||||
// machine automation). Unchanged wire contract.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// BuildReq is the direct-enqueue body. Repo/SHA/Image are required.
|
||||
@@ -337,11 +315,11 @@ type BuildJob struct {
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// EnqueueBuild enqueues a native build. It authenticates with the dedicated
|
||||
// build-callback token, not the service token.
|
||||
// EnqueueBuild enqueues a native build. buildToken is resolved by the caller (IAM
|
||||
// login is the final fallback; a dedicated build token wins when present).
|
||||
func (p *Platform) EnqueueBuild(ctx context.Context, req BuildReq, buildToken string) (*BuildJob, error) {
|
||||
if buildToken == "" {
|
||||
return nil, fmt.Errorf("no build token: set HANZO_BUILD_TOKEN / PLATFORM_BUILD_CALLBACK_TOKEN or `hanzo login --build-token <tok>`")
|
||||
return nil, fmt.Errorf("not authenticated: run `hanzo login` (an IAM login now authorizes builds; HANZO_BUILD_TOKEN / --build-token still works for machine automation)")
|
||||
}
|
||||
out := &BuildJob{}
|
||||
return out, p.do(ctx, http.MethodPost, "/v1/runner", buildToken, req, out)
|
||||
|
||||
+47
-91
@@ -18,17 +18,22 @@ func platformStub(t *testing.T, token string, h http.HandlerFunc) (*Platform, fu
|
||||
return newPlatform(srv.URL, token), srv.Close
|
||||
}
|
||||
|
||||
// Apps hits the LIVE board /v1/paas/apps with the IAM bearer; it sends NO org
|
||||
// filter (the board is org-confined server-side by the validated identity).
|
||||
func TestPlatformAuthHeaderAndApps(t *testing.T) {
|
||||
p, done := platformStub(t, "svc-tok", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer svc-tok" {
|
||||
t.Errorf("auth header = %q", got)
|
||||
}
|
||||
if r.URL.Path != "/v1/apps" {
|
||||
t.Errorf("path = %s", r.URL.Path)
|
||||
if r.URL.Path != "/v1/paas/apps" {
|
||||
t.Errorf("path = %s, want /v1/paas/apps", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("env") != "main" || r.URL.Query().Get("drift") != "1" {
|
||||
t.Errorf("query = %s", r.URL.RawQuery)
|
||||
}
|
||||
if r.URL.Query().Has("org") {
|
||||
t.Errorf("client must NOT send an org filter (identity confines the board): %s", r.URL.RawQuery)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(AppsList{
|
||||
Apps: []AppView{{ID: "hanzoai/iam/main", Org: "hanzoai", App: "iam", Env: "main", Drift: json.RawMessage(`{"severity":"red"}`)}},
|
||||
})
|
||||
@@ -47,126 +52,75 @@ func TestPlatformAuthHeaderAndApps(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// App hits /v1/paas/apps/{app}; no org query (identity scopes it).
|
||||
func TestPlatformApp(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/apps/hanzoai/iam/main" {
|
||||
t.Errorf("path = %s", r.URL.Path)
|
||||
if r.URL.Path != "/v1/paas/apps/iam" {
|
||||
t.Errorf("path = %s, want /v1/paas/apps/iam", r.URL.Path)
|
||||
}
|
||||
if r.URL.Query().Get("org") != "hanzoai" {
|
||||
t.Errorf("org query = %s", r.URL.RawQuery)
|
||||
if r.URL.RawQuery != "" {
|
||||
t.Errorf("app get must carry no query, got %s", r.URL.RawQuery)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(AppView{ID: "hanzoai/iam/main", App: "iam"})
|
||||
_ = json.NewEncoder(w).Encode(AppView{ID: "hanzoai/iam/main", App: "iam", Phase: "Running"})
|
||||
})
|
||||
defer done()
|
||||
a, err := p.App(context.Background(), "hanzoai/iam/main", "hanzoai")
|
||||
a, err := p.App(context.Background(), "iam")
|
||||
if err != nil || a.App != "iam" {
|
||||
t.Fatalf("App: %v %+v", err, a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformSyncApps(t *testing.T) {
|
||||
// Clusters hits the LIVE /v1/clusters (org from identity, not the path).
|
||||
func TestPlatformClusters(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/v1/apps/sync" {
|
||||
t.Errorf("sync = %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
defer done()
|
||||
if err := p.SyncApps(context.Background()); err != nil {
|
||||
t.Fatalf("SyncApps: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformClustersAndProvision(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/v1/org/acme/cluster":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"clusters": []Cluster{{DoksClusterID: "c1", Name: "hanzo-acme", Region: "sfo3", Status: "running", Phase: "ready", Active: true}}})
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/v1/org/acme/cluster":
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var req ProvisionReq
|
||||
_ = json.Unmarshal(body, &req)
|
||||
if req.Region != "sfo3" || !req.HA {
|
||||
t.Errorf("provision body = %+v", req)
|
||||
}
|
||||
w.WriteHeader(201)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"cluster": Cluster{DoksClusterID: "c2", Name: "new", Phase: "requested"}})
|
||||
default:
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/v1/clusters" {
|
||||
t.Errorf("clusters = %s %s, want GET /v1/clusters", r.Method, r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"clusters": []Cluster{
|
||||
{DoksClusterID: "c1", Name: "hanzo-acme", Region: "sfo3", Status: "running", Kind: "managed", NodeCount: 3},
|
||||
}})
|
||||
})
|
||||
defer done()
|
||||
|
||||
cs, err := p.Clusters(context.Background(), "acme")
|
||||
if err != nil || len(cs) != 1 || cs[0].DoksClusterID != "c1" {
|
||||
cs, err := p.Clusters(context.Background())
|
||||
if err != nil || len(cs) != 1 || cs[0].ID() != "c1" || cs[0].Kind != "managed" {
|
||||
t.Fatalf("Clusters: %v %+v", err, cs)
|
||||
}
|
||||
c, err := p.ProvisionCluster(context.Background(), "acme", ProvisionReq{Region: "sfo3", HA: true})
|
||||
if err != nil || c.DoksClusterID != "c2" {
|
||||
t.Fatalf("ProvisionCluster: %v %+v", err, c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformTargetAndSelect(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/org/acme/cluster/select" {
|
||||
t.Errorf("path = %s", r.URL.Path)
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var m map[string]any
|
||||
_ = json.Unmarshal(body, &m)
|
||||
if m["doksClusterId"] != "c1" {
|
||||
t.Errorf("select body = %v", m)
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"target": Target{Cluster: "hanzo-acme", Dedicated: true, Namespaces: map[string]string{"acme": "main"}}})
|
||||
})
|
||||
defer done()
|
||||
|
||||
tg, err := p.Target(context.Background(), "acme")
|
||||
if err != nil || tg.Cluster != "hanzo-acme" || !tg.Dedicated {
|
||||
t.Fatalf("Target: %v %+v", err, tg)
|
||||
}
|
||||
id := "c1"
|
||||
if _, err := p.SelectTarget(context.Background(), "acme", &id); err != nil {
|
||||
t.Fatalf("SelectTarget: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformInstallBaseline(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/v1/org/acme/cluster/c1/install-baseline" {
|
||||
t.Errorf("install-baseline = %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
})
|
||||
defer done()
|
||||
if err := p.InstallBaseline(context.Background(), "acme", "c1"); err != nil {
|
||||
t.Fatalf("InstallBaseline: %v", err)
|
||||
// A BYO cluster with no DOKS id keys on its name via ID().
|
||||
func TestClusterIDFallsBackToName(t *testing.T) {
|
||||
c := Cluster{Name: "byo-1", Kind: "byo"}
|
||||
if c.ID() != "byo-1" {
|
||||
t.Fatalf("ID() = %q, want byo-1", c.ID())
|
||||
}
|
||||
}
|
||||
|
||||
// Redeploy hits /v1/paas/apps/{app}/deploy (rolling restart), org from identity.
|
||||
func TestPlatformRedeploy(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, r *http.Request) {
|
||||
want := "/v1/org/acme/project/p1/env/e1/container/app-x/redeploy"
|
||||
if r.Method != http.MethodPost || r.URL.Path != want {
|
||||
t.Errorf("redeploy path = %s %s", r.Method, r.URL.Path)
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/v1/paas/apps/app-x/deploy" {
|
||||
t.Errorf("redeploy = %s %s, want POST /v1/paas/apps/app-x/deploy", r.Method, r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
|
||||
if r.URL.Query().Get("env") != "test" {
|
||||
t.Errorf("env query = %s", r.URL.RawQuery)
|
||||
}
|
||||
w.WriteHeader(202)
|
||||
_ = json.NewEncoder(w).Encode(DeployResult{OK: true, App: "app-x", Namespace: "hanzo-testnet", Env: "test", RestartedAt: "2026-07-18T00:00:00Z"})
|
||||
})
|
||||
defer done()
|
||||
if err := p.Redeploy(context.Background(), "acme", "p1", "e1", "app-x"); err != nil {
|
||||
t.Fatalf("Redeploy: %v", err)
|
||||
res, err := p.Redeploy(context.Background(), "app-x", "test")
|
||||
if err != nil || res.Namespace != "hanzo-testnet" {
|
||||
t.Fatalf("Redeploy: %v %+v", err, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformRedeployNotOK(t *testing.T) {
|
||||
p, done := platformStub(t, "t", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]bool{"ok": false})
|
||||
_ = json.NewEncoder(w).Encode(DeployResult{OK: false})
|
||||
})
|
||||
defer done()
|
||||
if err := p.Redeploy(context.Background(), "o", "p", "e", "c"); err == nil {
|
||||
if _, err := p.Redeploy(context.Background(), "c", ""); err == nil {
|
||||
t.Fatalf("expected error when ok=false")
|
||||
}
|
||||
}
|
||||
@@ -207,14 +161,16 @@ func TestPlatformError401Hint(t *testing.T) {
|
||||
})
|
||||
defer done()
|
||||
_, err := p.Apps(context.Background(), AppsQuery{})
|
||||
if err == nil || !strings.Contains(err.Error(), "HTTP 401") || !strings.Contains(err.Error(), "platform service token") {
|
||||
t.Fatalf("401 error should carry a token hint, got %v", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "HTTP 401") || !strings.Contains(err.Error(), "hanzo login") {
|
||||
t.Fatalf("401 error should point at `hanzo login`, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformNoTokenError(t *testing.T) {
|
||||
p := newPlatform("https://platform.hanzo.ai", "")
|
||||
if _, err := p.Apps(context.Background(), AppsQuery{}); err == nil || !strings.Contains(err.Error(), "no platform token") {
|
||||
t.Fatalf("expected no-token error, got %v", err)
|
||||
// After unify-infra, the "no credential" error points at `hanzo login` — the one
|
||||
// identity that authorizes the platform — not a separate platform token.
|
||||
if _, err := p.Apps(context.Background(), AppsQuery{}); err == nil || !strings.Contains(err.Error(), "hanzo login") {
|
||||
t.Fatalf("expected a `hanzo login` hint, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ package cli
|
||||
// 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.
|
||||
// `link` shares compute, `runner` claims CI — one binary, one org login.
|
||||
|
||||
import (
|
||||
"os/signal"
|
||||
|
||||
+86
-10
@@ -1,5 +1,5 @@
|
||||
// studio.go — local Hanzo Studio render-backend supervision for `hanzo gpu
|
||||
// connect --studio-dir <checkout>`. The gpu-jobs claim loop renders on the
|
||||
// studio.go — local Hanzo Studio render-backend supervision for `hanzo link
|
||||
// --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.
|
||||
@@ -12,6 +12,7 @@ package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
@@ -65,9 +67,22 @@ func launchStudio(dir string) (*exec.Cmd, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// --listen 127.0.0.1 (loopback only) + --worker-mode: the render backend serves
|
||||
// the fleet worker on this box and nothing else. The worker dials loopback
|
||||
// (localComfyUI) so binding wider bought nothing but an open, unauthenticated
|
||||
// /prompt — the hidden-run hole. --worker-mode makes the studio gate its submit
|
||||
// seam (/v1/worker/execute + X-Worker-Token) so only the worker can start a render.
|
||||
// VRAM mode: default --normalvram (safe for smaller BYO GPUs); override with
|
||||
// HANZO_STUDIO_VRAM (e.g. "--highvram") on big-memory boxes (GB10 128G unified) so
|
||||
// the Qwen text-encoder stays resident on-GPU instead of non-deterministically
|
||||
// offloading to CPU — offload makes renders CPU-bound and ~8x slower.
|
||||
vramMode := os.Getenv("HANZO_STUDIO_VRAM")
|
||||
if vramMode == "" {
|
||||
vramMode = "--normalvram"
|
||||
}
|
||||
cmd := exec.Command(studioPython(dir), "main.py",
|
||||
"--listen", "0.0.0.0", "--port", "8188",
|
||||
"--normalvram", "--disable-auto-launch",
|
||||
"--listen", "127.0.0.1", "--port", "8188", "--worker-mode",
|
||||
vramMode, "--disable-auto-launch",
|
||||
"--output-directory", filepath.Join(dir, "output"))
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(),
|
||||
@@ -107,6 +122,48 @@ func stopStudio(cmd *exec.Cmd) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// staging guards the claim-to-submit window: a claimed job is real work the
|
||||
// engine queue cannot see yet, so the supervisor must never recycle over it
|
||||
// (observed: jobs claimed during a recycle failed staging on a dead engine
|
||||
// and were consumed).
|
||||
var staging atomic.Int32
|
||||
|
||||
func requestStudioRecycle() {
|
||||
select {
|
||||
case studioRecycle <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// studioBusy reports whether the engine holds queued or running prompts.
|
||||
// A generous timeout: a saturated GB10 answers slowly mid-render — slow is
|
||||
// alive, and killing a live render costs 8-70 minutes of GPU work.
|
||||
func studioBusy(ctx context.Context) (busy, ok bool) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+studioAddr+"/queue", nil)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var q struct {
|
||||
Running []json.RawMessage `json:"queue_running"`
|
||||
Pending []json.RawMessage `json:"queue_pending"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(&q); err != nil {
|
||||
return false, false
|
||||
}
|
||||
return len(q.Running)+len(q.Pending) > 0, true
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -138,6 +195,12 @@ func superviseStudio(ctx context.Context, dir string, out io.Writer) {
|
||||
|
||||
tick := time.NewTicker(studioProbeEvery)
|
||||
defer tick.Stop()
|
||||
// recyclePending defers the post-render recycle until the queue is EMPTY:
|
||||
// short jobs complete while a long render is mid-sample, and recycling on
|
||||
// their completion killed the live render (observed: every direct render
|
||||
// died within ~6 minutes while probe jobs cycled).
|
||||
recyclePending := false
|
||||
unhealthy := 0
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -145,19 +208,32 @@ func superviseStudio(ctx context.Context, dir string, out io.Writer) {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
|
||||
}
|
||||
return
|
||||
case <-studioRecycle:
|
||||
recyclePending = true
|
||||
case <-tick.C:
|
||||
busy, ok := studioBusy(ctx)
|
||||
if recyclePending && ok && !busy && staging.Load() == 0 {
|
||||
recyclePending = false
|
||||
unhealthy = 0
|
||||
restart("recycle")
|
||||
continue
|
||||
}
|
||||
if studioHealthy(ctx) {
|
||||
unhealthy = 0
|
||||
continue
|
||||
}
|
||||
// Grace re-check: it may be momentarily busy mid-render.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if ok && busy {
|
||||
// Alive-busy: slow health under render load is not death.
|
||||
unhealthy = 0
|
||||
continue
|
||||
case <-time.After(studioGraceWait):
|
||||
}
|
||||
if !studioHealthy(ctx) {
|
||||
restart("unresponsive")
|
||||
// Sustained silence with an idle or unreadable queue = actually dead.
|
||||
unhealthy++
|
||||
if unhealthy < 3 {
|
||||
continue
|
||||
}
|
||||
unhealthy = 0
|
||||
restart("unresponsive")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+67
-11
@@ -30,6 +30,7 @@ package account
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -39,6 +40,7 @@ import (
|
||||
"github.com/hanzoai/account"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
@@ -107,6 +109,7 @@ var billingForwardable = map[string][]string{
|
||||
"subscriptions",
|
||||
"payment-methods",
|
||||
"spend-alerts",
|
||||
"spend-alerts/authorize", // the S2S cap-verdict read (metering gate); 2 segments need their own entry
|
||||
"payment-config",
|
||||
"plans",
|
||||
"payouts",
|
||||
@@ -241,9 +244,26 @@ func commerceCreds() (base, token string) {
|
||||
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).
|
||||
// Auth. A browser caller is the VALIDATED principal (customer path — subject-pinned
|
||||
// below). An IN-PROC S2S caller carries the verified COMMERCE_SERVICE_TOKEN (the
|
||||
// metering cap-gate's authorize + the SuperAdmin cap-oversight Forward). The gateway
|
||||
// 401s a public Bearer that is not an IAM JWT / hk-|pk-|sk- key (the 64-hex service
|
||||
// token fails JWT parse at the edge), so an EXTERNAL client can NEVER present it here —
|
||||
// an unauthenticated caller still hits the 403 below. On the S2S path the caller
|
||||
// legitimately names its own subject, so its query is forwarded as-is (no pin), scoped
|
||||
// only by the EdgeAuth-controlled X-Org-Id.
|
||||
cr, ok := resolveCaller(c, true)
|
||||
s2s := false
|
||||
owner := cr.owner
|
||||
if !ok {
|
||||
return zip.ErrForbidden("sign in to view billing")
|
||||
if !s2sBillingCall(c) {
|
||||
return zip.ErrForbidden("sign in to view billing")
|
||||
}
|
||||
owner = strings.TrimSpace(c.Org()) // trusted X-Org-Id (never a client value on a public call)
|
||||
if owner == "" {
|
||||
return zip.ErrForbidden("sign in to view billing")
|
||||
}
|
||||
s2s = true
|
||||
}
|
||||
|
||||
method := c.Method()
|
||||
@@ -277,20 +297,32 @@ func billingData(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
|
||||
// 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()
|
||||
// subject comes from the ONE rule (ai/object.Payer), fed the account the
|
||||
// credential NAMES (the validated `billing_account` claim) — the same claim the
|
||||
// ai gate reads, so a top-up credits the SAME account the gate debits. Feeding
|
||||
// Payer a different credential here than the gate gets is the modern shape of
|
||||
// the old split: money landing in an account the gate never reads.
|
||||
inQuery, _ := url.ParseQuery(string(c.Fiber().Request().URI().QueryString()))
|
||||
q := scopedBillingSearch(inQuery, subject)
|
||||
|
||||
var q url.Values
|
||||
var body []byte
|
||||
if method == http.MethodPost {
|
||||
body = scopedBillingBody(c.Body(), subject)
|
||||
if s2s {
|
||||
// Trusted S2S caller: forward its query/body VERBATIM — it legitimately names the
|
||||
// subject (e.g. the metering gate's ?user=<org>&amount=). Scoped by X-Org-Id.
|
||||
q = inQuery
|
||||
if method == http.MethodPost {
|
||||
body = c.Body()
|
||||
}
|
||||
} else {
|
||||
// Browser customer: pin EVERY subject key to the caller's OWN account so commerce's
|
||||
// per-tenant isolation can never be crossed from the client.
|
||||
subject := account.Payer(account.Credential{Owner: cr.owner, Name: cr.username, Account: principal.BillingAccount(c)}).Subject()
|
||||
q = scopedBillingSearch(inQuery, subject)
|
||||
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)
|
||||
raw, status, err := commerceDo(c.Context(), base, token, method, "/v1/billing/"+sub, q, owner, body)
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusBadGateway, "billing upstream unreachable: %v", err)
|
||||
}
|
||||
@@ -300,3 +332,27 @@ func billingData(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
c.SetHeader("Cache-Control", "no-store, must-revalidate")
|
||||
return c.Bytes(status, raw)
|
||||
}
|
||||
|
||||
// s2sBillingCall reports whether the request carries the verified COMMERCE_SERVICE_TOKEN
|
||||
// as its Bearer — a trusted IN-PROC service-to-service caller (the metering cap-gate's
|
||||
// authorize, the SuperAdmin cap-oversight Forward). It is the SAME secret this bridge
|
||||
// already forwards WITH, so admitting a caller who already holds it grants no authority it
|
||||
// could not otherwise wield. Safety rests on the edge: the gateway 401s a public Bearer
|
||||
// that is not an IAM JWT / hk-|pk-|sk- API key (the 64-hex service token is a JWT
|
||||
// candidate that fails to parse), so an EXTERNAL client can never reach this handler
|
||||
// holding it — only in-proc commerceinproc dispatch does. Constant-time compare; the token
|
||||
// is never logged.
|
||||
func s2sBillingCall(c *zip.Ctx) bool {
|
||||
_, token := commerceCreds()
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
bearer := strings.TrimSpace(strings.TrimPrefix(c.Header("Authorization"), "Bearer "))
|
||||
return bearer != "" && subtle.ConstantTimeCompare([]byte(bearer), []byte(token)) == 1
|
||||
}
|
||||
|
||||
// IsServiceToken is the exported view of s2sBillingCall — whether the request is a trusted
|
||||
// in-proc S2S caller bearing the verified COMMERCE_SERVICE_TOKEN. Used by co-resident route
|
||||
// gates (e.g. the spend-alert admin gate) that must admit the metering cap-gate and the
|
||||
// SuperAdmin cap-oversight Forward alongside org admins, while refusing a plain member.
|
||||
func IsServiceToken(c *zip.Ctx) bool { return s2sBillingCall(c) }
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// billing_coresident.go — PinBillingSubject, the subject-pinning middleware that lets
|
||||
// commerce's OWN billing READ handlers serve co-resident in the unified cloud binary.
|
||||
//
|
||||
// WHY IT EXISTS. Co-resident, commerce is EMBEDDED (apps/commerce.go mountCommerce →
|
||||
// commerce.Embed on the shared zip app), and in prod there is NO standalone commerce
|
||||
// backend — the in-cluster `commerce` Service selects the cloud pods themselves. So the
|
||||
// /v1/billing/* bridge (billing.go), which forwards to COMMERCE_URL, has nowhere to send
|
||||
// a read but back into cloud: the default base (the public api.hanzo.ai edge) re-enters
|
||||
// the same bridge in an unbounded self-dispatch loop that surfaces as a 502
|
||||
// ("billing upstream unreachable: Get https://api.hanzo.ai/v1/billing/<path>"). The fix
|
||||
// is to serve those reads co-resident from the embedded commerce — the same co-resident
|
||||
// move mountCommerce already makes for GET /v1/billing/plans — so the specific route
|
||||
// shadows the bridge wildcard (order 100 < 122) and never leaves the process.
|
||||
//
|
||||
// WHAT IT GUARANTEES. commerce's read handlers scope to the org by NAMESPACE (from the
|
||||
// gateway-validated X-Org-Id via iammiddleware) but filter finer scope (the billing
|
||||
// subject) only from a query param — an UNPINNED ListInvoices returns every user's rows
|
||||
// in the org namespace. The /v1/billing/* bridge is what pins that subject today; this
|
||||
// middleware carries the SAME pin onto the co-resident route so the isolation is
|
||||
// byte-for-byte the shipped behavior. It is the ONE subject rule (account.Payer, the same
|
||||
// function the ai spend-gate and the top-up resolve), fed the account the credential NAMES
|
||||
// — so a read scopes to exactly the account the gate debits, never wider.
|
||||
package account
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
"github.com/hanzoai/account"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// PinBillingSubject pins every billing subject key in the request query to the VALIDATED
|
||||
// caller's own subject (dropping ?org), so a co-resident commerce read handler downstream
|
||||
// can only ever return the caller's OWN rows. It is the co-resident twin of billingData's
|
||||
// subject-pinning, reusing the SAME resolveCaller → account.Payer rule and the SAME
|
||||
// scopedBillingSearch, so the two paths scope identically.
|
||||
//
|
||||
// Three cases, mirroring billingData exactly:
|
||||
// - Browser customer (a validated principal with an org): OVERWRITE the subject keys
|
||||
// with the caller's own subject and drop ?org. The client cannot widen scope.
|
||||
// - Trusted in-proc S2S (the verified COMMERCE_SERVICE_TOKEN bearer, carrying its own
|
||||
// X-Org-Id): pass the query through VERBATIM — it legitimately names its own subject,
|
||||
// scoped by the EdgeAuth-controlled org.
|
||||
// - Neither: refuse. A bearer-less request with a forged X-Org-Id has no validated
|
||||
// principal and is fail-closed here, before the read handler runs.
|
||||
//
|
||||
// The pin rewrites the request URI's query string in place; fasthttp's SetQueryString
|
||||
// resets the parsed-args cache, so the handler's later c.Query() reads the pinned values.
|
||||
func PinBillingSubject() zip.Handler {
|
||||
return func(c *zip.Ctx) error {
|
||||
inQuery, _ := url.ParseQuery(string(c.Fiber().Request().URI().QueryString()))
|
||||
|
||||
cr, ok := resolveCaller(c, true)
|
||||
if !ok {
|
||||
// Not a validated customer — admit ONLY a trusted in-proc S2S caller that
|
||||
// names its own org (same admission billingData makes), leaving its query
|
||||
// untouched. Everything else is refused before the read runs.
|
||||
if s2sBillingCall(c) && c.Org() != "" {
|
||||
return c.Next()
|
||||
}
|
||||
return zip.ErrForbidden("sign in to view billing")
|
||||
}
|
||||
|
||||
subject := account.Payer(account.Credential{
|
||||
Owner: cr.owner,
|
||||
Name: cr.username,
|
||||
Account: principal.BillingAccount(c),
|
||||
}).Subject()
|
||||
|
||||
c.Fiber().Request().URI().SetQueryString(scopedBillingSearch(inQuery, subject).Encode())
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
luxlog "github.com/luxfi/log"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// billing_coresident_test.go — proves PinBillingSubject carries the SAME tenant scoping
|
||||
// onto a co-resident commerce read handler that billingData applies on the bridge: the
|
||||
// caller's own subject is pinned into the query (dropping ?org), an unvalidated caller is
|
||||
// refused before the handler runs, and a trusted in-proc S2S caller passes through
|
||||
// verbatim. This is what lets commerce's ListInvoices/ListBillingSubscriptions/... serve
|
||||
// in-process without leaking another subject's rows.
|
||||
|
||||
// echoQuery is the downstream stand-in for a commerce read handler: it reports exactly the
|
||||
// query it observes AFTER the pin, so a test can assert the subject the handler would filter on.
|
||||
func echoQuery(c *zip.Ctx) error {
|
||||
return c.JSON(200, map[string]any{
|
||||
"user": c.Query("user"),
|
||||
"userId": c.Query("userId"),
|
||||
"customerId": c.Query("customerId"),
|
||||
"org": c.Query("org"),
|
||||
"status": c.Query("status"),
|
||||
})
|
||||
}
|
||||
|
||||
func pinApp(t *testing.T) *zip.App {
|
||||
t.Helper()
|
||||
app := zip.New(zip.Config{Logger: luxlog.New("test")})
|
||||
// MountAccount installs the identity middleware PinBillingSubject relies on; mounting
|
||||
// it keeps the probe on the same trust plane as the real co-resident registration.
|
||||
if err := MountAccount(app, cloud.Deps{Logger: luxlog.New("test"), Brand: "hanzo"}); err != nil {
|
||||
t.Fatalf("MountAccount: %v", err)
|
||||
}
|
||||
app.Get("/probe", PinBillingSubject(), echoQuery)
|
||||
return app
|
||||
}
|
||||
|
||||
// TestPinBillingSubject_PinsCallerAndDropsOrg — a validated customer's forged subject
|
||||
// keys are overwritten with its OWN subject and ?org is dropped, exactly like the bridge.
|
||||
func TestPinBillingSubject_PinsCallerAndDropsOrg(t *testing.T) {
|
||||
app := pinApp(t)
|
||||
code, body := callH(t, app, http.MethodGet,
|
||||
"/probe?userId=victim&customerId=victim&user=victim&org=othercorp&status=open", alice, "")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("want 200, got %d (%s)", code, body)
|
||||
}
|
||||
var got map[string]string
|
||||
if err := json.Unmarshal(body, &got); err != nil {
|
||||
t.Fatalf("bad body: %s", body)
|
||||
}
|
||||
for _, k := range billingSubjectKeys {
|
||||
if got[k] != "acme" { // alice/acme resolves to the org subject "acme"
|
||||
t.Fatalf("handler must see %s=acme (caller's own subject), got %q", k, got[k])
|
||||
}
|
||||
}
|
||||
if got["org"] != "" {
|
||||
t.Fatalf("org must be dropped, handler saw org=%q", got["org"])
|
||||
}
|
||||
if got["status"] != "open" {
|
||||
t.Fatalf("non-subject filter must survive, got status=%q", got["status"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinBillingSubject_RefusesUnvalidated — a forged X-Org-Id with NO validated
|
||||
// X-User-Id (and no service token) is refused before the read handler runs: no
|
||||
// cross-tenant billing read is possible.
|
||||
func TestPinBillingSubject_RefusesUnvalidated(t *testing.T) {
|
||||
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
|
||||
app := pinApp(t)
|
||||
code, _ := callH(t, app, http.MethodGet, "/probe?userId=victim",
|
||||
map[string]string{"X-Org-Id": "victim"}, "")
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("unvalidated caller: want 403, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinBillingSubject_S2SForwardsVerbatim — the trusted in-proc S2S caller (verified
|
||||
// COMMERCE_SERVICE_TOKEN + its own X-Org-Id, no validated user) is admitted and its query
|
||||
// is left UNTOUCHED, so it can name its own subject (the cap-gate's authorize read).
|
||||
func TestPinBillingSubject_S2SForwardsVerbatim(t *testing.T) {
|
||||
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
|
||||
app := pinApp(t)
|
||||
code, body := callH(t, app, http.MethodGet, "/probe?user=acme&status=open",
|
||||
map[string]string{"Authorization": "Bearer svc-tok", "X-Org-Id": "acme"}, "")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("S2S: want 200, got %d (%s)", code, body)
|
||||
}
|
||||
var got map[string]string
|
||||
_ = json.Unmarshal(body, &got)
|
||||
if got["user"] != "acme" || got["status"] != "open" {
|
||||
t.Fatalf("S2S query must pass through verbatim, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinBillingSubject_S2SNoOrgRefused — the service token with NO X-Org-Id has no org
|
||||
// to scope the privileged read and is refused (matches billingData's s2s org requirement).
|
||||
func TestPinBillingSubject_S2SNoOrgRefused(t *testing.T) {
|
||||
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
|
||||
app := pinApp(t)
|
||||
code, _ := callH(t, app, http.MethodGet, "/probe",
|
||||
map[string]string{"Authorization": "Bearer svc-tok"}, "")
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("S2S without X-Org-Id: want 403, got %d", code)
|
||||
}
|
||||
}
|
||||
@@ -232,3 +232,65 @@ func TestBilling_RejectsTraversalSegment(t *testing.T) {
|
||||
t.Fatalf("a traversal must never reach commerce, but upstream saw %q", f.path)
|
||||
}
|
||||
}
|
||||
|
||||
// ── S2S service-token admission (the auth fix; 4 security invariants) ─────────
|
||||
|
||||
// Invariant #4 — THE SECURITY GATE: a public/unauthenticated caller (no validated
|
||||
// principal AND not the service token) STILL gets 403 on the spend-alert routes, incl.
|
||||
// a WRONG bearer. The fix must NEVER open billing to the world.
|
||||
func TestBilling_S2S_PublicStill403(t *testing.T) {
|
||||
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
|
||||
app := mountApp(t, "http://iam.invalid", "", "")
|
||||
for _, path := range []string{
|
||||
"/v1/billing/spend-alerts",
|
||||
"/v1/billing/spend-alerts/authorize?user=acme&amount=1",
|
||||
} {
|
||||
// forged X-Org-Id, no validated principal, no service token
|
||||
if code, body := callH(t, app, http.MethodGet, path, map[string]string{"X-Org-Id": "victim"}, ""); code != http.StatusForbidden {
|
||||
t.Fatalf("public caller to %s: want 403, got %d (%s)", path, code, body)
|
||||
}
|
||||
}
|
||||
// a WRONG bearer is still just a public caller → 403
|
||||
if code, _ := callH(t, app, http.MethodGet, "/v1/billing/spend-alerts/authorize?user=acme&amount=1",
|
||||
map[string]string{"X-Org-Id": "acme", "Authorization": "Bearer not-the-token"}, ""); code != http.StatusForbidden {
|
||||
t.Fatalf("wrong bearer: want 403")
|
||||
}
|
||||
}
|
||||
|
||||
// The trusted in-proc S2S caller (verified COMMERCE_SERVICE_TOKEN + X-Org-Id) is admitted
|
||||
// and its authorize query is forwarded to commerce VERBATIM (a trusted caller names its
|
||||
// own subject), scoped by X-Org-Id — this is what lets the cap gate reach AuthorizeSpendCap.
|
||||
func TestBilling_S2S_ServiceTokenForwardsVerbatim(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, http.MethodGet,
|
||||
"/v1/billing/spend-alerts/authorize?user=acme&amount=100&project=P",
|
||||
map[string]string{"Authorization": "Bearer svc-tok", "X-Org-Id": "acme"}, "")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("S2S authorize: want 200, got %d (%s)", code, body)
|
||||
}
|
||||
if f.path != "/v1/billing/spend-alerts/authorize" {
|
||||
t.Fatalf("forwarded path = %q", f.path)
|
||||
}
|
||||
// VERBATIM: the S2S caller's ?user/?amount/?project reach commerce un-pinned.
|
||||
if f.query.Get("user") != "acme" || f.query.Get("amount") != "100" || f.query.Get("project") != "P" {
|
||||
t.Fatalf("S2S query must forward verbatim, got %v", f.query)
|
||||
}
|
||||
if f.org != "acme" || f.auth != "Bearer svc-tok" {
|
||||
t.Fatalf("S2S must send X-Org-Id=acme + service token, got org=%q auth=%q", f.org, f.auth)
|
||||
}
|
||||
}
|
||||
|
||||
// S2S with the verified token but NO X-Org-Id → 403 (no org to scope the privileged
|
||||
// forward to; never fall back to a client value).
|
||||
func TestBilling_S2S_NoOrg403(t *testing.T) {
|
||||
t.Setenv("COMMERCE_SERVICE_TOKEN", "svc-tok")
|
||||
app := mountApp(t, "http://iam.invalid", "", "")
|
||||
if code, _ := callH(t, app, http.MethodGet, "/v1/billing/spend-alerts/authorize?user=acme&amount=1",
|
||||
map[string]string{"Authorization": "Bearer svc-tok"}, ""); code != http.StatusForbidden {
|
||||
t.Fatalf("S2S without X-Org-Id: want 403")
|
||||
}
|
||||
}
|
||||
|
||||
+39
-22
@@ -38,7 +38,10 @@ import (
|
||||
"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/invoices"
|
||||
"github.com/hanzoai/cloud/clients/admin/metrics"
|
||||
"github.com/hanzoai/cloud/clients/admin/revenue"
|
||||
"github.com/hanzoai/cloud/clients/admin/subscriptions"
|
||||
"github.com/hanzoai/cloud/clients/commerceinproc"
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/zap-proto/zip"
|
||||
@@ -87,42 +90,56 @@ func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
// 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]) {
|
||||
g := app.Group("/v1/admin")
|
||||
// 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))
|
||||
g.Get("/me", core.GuardScoped(s, me))
|
||||
g.Get("/overview", core.GuardScoped(s, overview))
|
||||
g.Get("/orgs", core.GuardScoped(s, orgs))
|
||||
g.Get("/users", core.GuardScoped(s, users))
|
||||
g.Get("/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))
|
||||
g.Get("/roles", core.Guard(s, roles))
|
||||
g.Get("/applications", core.Guard(s, applications))
|
||||
g.Get("/products", core.Guard(s, products))
|
||||
g.Get("/compute", core.Guard(s, compute))
|
||||
g.Get("/o11y", core.Guard(s, o11y))
|
||||
g.Get("/aimetrics", core.Guard(s, aimetrics))
|
||||
g.Post("/sync", core.Guard(s, syncNow))
|
||||
|
||||
// Credit grants — the ONE admin mint surface (SuperAdmin only). Thin, audited
|
||||
// relay to commerce's mint-gated POST /v1/billing/credit-grants; commerce is the
|
||||
// sole ledger. See creditgrant.go.
|
||||
g.Post("/credit-grants", core.Guard(s, createCreditGrant))
|
||||
|
||||
// Product analytics — org-scoped (SuperAdmin: all-orgs; org admin: their own org).
|
||||
app.Get("/v1/admin/analytics", core.GuardScoped(s, analytics))
|
||||
g.Get("/analytics", core.GuardScoped(s, analytics))
|
||||
// Bases — the tenant Base-instance panel, org-scoped (bases.go).
|
||||
app.Get("/v1/admin/bases", core.GuardScoped(s, bases))
|
||||
g.Get("/bases", core.GuardScoped(s, bases))
|
||||
|
||||
// ── 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))
|
||||
g.Get("/flags", core.Guard(s, flagsBoard))
|
||||
g.Put("/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))
|
||||
// of /v1/admin/flags), reading the registry + decide the admission gate owns.
|
||||
g.Get("/services", core.Guard(s, services))
|
||||
g.Post("/services", core.Guard(s, upsertService))
|
||||
g.Post("/services/:service/mode", core.Guard(s, setServiceMode))
|
||||
g.Get("/waitlist", core.Guard(s, waitlist))
|
||||
g.Post("/waitlist/boost", core.Guard(s, waitlistBoost))
|
||||
|
||||
// ── Carved-out domains own their routes (audit/customer/revenue/finance). ──
|
||||
// Usage-cap + promo control plane (promos platform-only; spend-caps org-scoped).
|
||||
limitRoutes(app, s)
|
||||
|
||||
// ── Carved-out domains own their routes (audit/customer/revenue/finance +
|
||||
// the billing fleet views metrics/invoices/subscriptions). ──
|
||||
audit.Routes(app, s)
|
||||
customer.Routes(app, s)
|
||||
revenue.Routes(app, s)
|
||||
finance.Routes(app, s)
|
||||
metrics.Routes(app, s)
|
||||
invoices.Routes(app, s)
|
||||
subscriptions.Routes(app, s)
|
||||
}
|
||||
|
||||
// ── /v1/admin/me — operator identity (AdminMe) ───────────────────────────────
|
||||
|
||||
@@ -24,16 +24,16 @@ import (
|
||||
// mount builds a zip app with admin mounted against the given upstream bases,
|
||||
// and returns a `do` helper that issues test requests through the whole app.
|
||||
func mount(t *testing.T, iamURL, commerceURL, healthURL string) func(method, path string, hdr map[string]string) (*http.Response, []byte) {
|
||||
do, _, _ := mountSvc(t, iamURL, commerceURL, healthURL)
|
||||
do, _, _ := mountService(t, iamURL, commerceURL, healthURL)
|
||||
return do
|
||||
}
|
||||
|
||||
// mountSvc is mount but also returns the underlying cloud.Service[state] (so finance tests can swap
|
||||
// mountService 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), *cloud.Service[core.State], *fiber.App) {
|
||||
func mountService(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 := &cloud.Service[core.State]{State: core.State{
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
// Copyright 2023-2026 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 admin
|
||||
|
||||
// aimetrics — GET /v1/admin/aimetrics, the GLOBAL fleet-wide AI / training / eval
|
||||
// read that powers the operator's AI-metrics board on admin.hanzo.ai. It is the
|
||||
// AI-and-eval-focused companion to o11y (o11y.go): where o11y answers "how is the
|
||||
// FLEET behaving" (RED metrics, logs, usage), this answers "how are the MODELS and
|
||||
// EVALS doing" — LLM generations, per-model spend, and eval-run quality/progress —
|
||||
// over the SAME ONE datastore (Datastore), the SAME shared client
|
||||
// (aiobject.DatastoreQuery), no second connection.
|
||||
//
|
||||
// Signals, each from its canonical table in the one datastore:
|
||||
// - LLM generations → langfuse.observations : generations, cost (USD), latency
|
||||
// (fleet-wide; honest-empty until the
|
||||
// Langfuse ingest lands rows)
|
||||
// - Per-model usage → hanzo.cloud_usage : requests, tokens, cost per model
|
||||
// (the live usage ledger the ai gateway
|
||||
// writes — populated today)
|
||||
// - Eval runs → hanzo.eval_traces : traces, runs, datasets, models under
|
||||
// test, per-trace latency
|
||||
// - Eval progress → hanzo.eval_scores : score count, avg score, per-score-name
|
||||
// distribution, recent-run averages, and
|
||||
// the avg-score-over-time TREND — the
|
||||
// training/eval progress signal
|
||||
//
|
||||
// The eval_traces / eval_scores tables are OWNED and written by the eval telemetry
|
||||
// store (clients/eval/telemetry.go) — the SAME warehouse, same db ("hanzo"), same
|
||||
// shared aiobject client. admin only READS them here. There is deliberately no
|
||||
// "training_progress" table: the router's per-request training events live in the ai
|
||||
// OLTP Postgres (object.RoutingEvent), NOT the OLAP warehouse, so the honest
|
||||
// warehouse-side progress signal is the eval-score trend, not a routing table.
|
||||
//
|
||||
// SUPERADMIN ONLY (the core.Guard wrap in admin.go), all-orgs, no org filter — the
|
||||
// one place a fleet operator crosses tenants for AI/eval metrics; a non-admin bearer
|
||||
// is refused 403 before a single row is read. Fail-closed.
|
||||
//
|
||||
// Honest by construction, exactly like o11y/compute: no datastore connected → the
|
||||
// real empty aggregate, never a fabricated fleet; and every signal degrades
|
||||
// INDEPENDENTLY — a table that is absent or a column that differs contributes its
|
||||
// zero-value (the enclosing `if err == nil`), never a failure, so the board always
|
||||
// renders what the datastore actually holds. admin READS only; it owns and creates
|
||||
// NO table. Money from cloud_usage is USD cents, from langfuse is USD; latency is
|
||||
// milliseconds; time bounds are POSITIONAL parameters (never interpolated), and the
|
||||
// bucket interval is a server-side constant — injection-safe.
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// Fully-qualified datastore tables. admin only READS these — the ai gateway owns
|
||||
// hanzo.cloud_usage, Langfuse owns langfuse.observations, and the eval telemetry
|
||||
// store (clients/eval) owns hanzo.eval_traces / hanzo.eval_scores.
|
||||
const (
|
||||
aimUsageTable = "hanzo.cloud_usage"
|
||||
aimLangfuseObs = "langfuse.observations"
|
||||
aimEvalTraces = "hanzo.eval_traces"
|
||||
aimEvalScores = "hanzo.eval_scores"
|
||||
aimTopN = 12
|
||||
)
|
||||
|
||||
// aiMetrics is the whole AI-metrics board payload.
|
||||
type aiMetrics struct {
|
||||
Range string `json:"range"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Langfuse aimLangfuse `json:"langfuse"`
|
||||
Usage aimUsage `json:"usage"`
|
||||
Evals aimEvals `json:"evals"`
|
||||
TopModels []aimModelStat `json:"topModels"` // cloud_usage per-model (populated today)
|
||||
LangfuseModels []aimLfModelStat `json:"langfuseModels"` // langfuse per-model (honest-empty today)
|
||||
ScoreNames []aimScoreStat `json:"scoreNames"` // eval_scores per score-name
|
||||
EvalRuns []aimRunStat `json:"evalRuns"` // recent eval runs (progress)
|
||||
ScoreSeries []aimScorePoint `json:"scoreSeries"` // avg eval score over time (progress trend)
|
||||
}
|
||||
|
||||
// aimLangfuse is the fleet-wide Langfuse generation rollup (honest-empty today).
|
||||
// Cost is USD (Langfuse's native unit); latency is milliseconds (end_time-start_time).
|
||||
type aimLangfuse struct {
|
||||
Generations int64 `json:"generations"`
|
||||
CostUsd float64 `json:"costUsd"`
|
||||
LatencyMsAvg float64 `json:"latencyMsAvg"`
|
||||
LatencyMsP95 float64 `json:"latencyMsP95"`
|
||||
}
|
||||
|
||||
// aimUsage is the fleet LLM-usage KPI band from the live cloud_usage ledger.
|
||||
type aimUsage struct {
|
||||
Requests int64 `json:"requests"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
PromptTokens int64 `json:"promptTokens"`
|
||||
CompletionTokens int64 `json:"completionTokens"`
|
||||
CostCents int64 `json:"costCents"`
|
||||
Models int64 `json:"models"`
|
||||
}
|
||||
|
||||
// aimEvals is the fleet eval KPI band: the trace half (eval_traces) and the score
|
||||
// half (eval_scores). LatencyMsAvg is the mean model-under-test call window.
|
||||
type aimEvals struct {
|
||||
Runs int64 `json:"runs"`
|
||||
Traces int64 `json:"traces"`
|
||||
Datasets int64 `json:"datasets"`
|
||||
Models int64 `json:"models"`
|
||||
LatencyMsAvg float64 `json:"latencyMsAvg"`
|
||||
Scores int64 `json:"scores"`
|
||||
ScoreNames int64 `json:"scoreNames"`
|
||||
AvgScore float64 `json:"avgScore"`
|
||||
}
|
||||
|
||||
// aimModelStat is one row of the per-model usage leaderboard (cloud_usage).
|
||||
type aimModelStat struct {
|
||||
Model string `json:"model"`
|
||||
Requests int64 `json:"requests"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
CostCents int64 `json:"costCents"`
|
||||
}
|
||||
|
||||
// aimLfModelStat is one row of the per-model Langfuse leaderboard (honest-empty today).
|
||||
type aimLfModelStat struct {
|
||||
Model string `json:"model"`
|
||||
Generations int64 `json:"generations"`
|
||||
CostUsd float64 `json:"costUsd"`
|
||||
}
|
||||
|
||||
// aimScoreStat is one row of the per-score-name eval leaderboard (eval_scores).
|
||||
type aimScoreStat struct {
|
||||
Name string `json:"name"`
|
||||
Count int64 `json:"count"`
|
||||
AvgValue float64 `json:"avgValue"`
|
||||
MinValue float64 `json:"minValue"`
|
||||
MaxValue float64 `json:"maxValue"`
|
||||
}
|
||||
|
||||
// aimRunStat is one recent eval run: its dataset, how many scores it recorded, its
|
||||
// mean score, and when it last ran — the run-level eval-progress row.
|
||||
type aimRunStat struct {
|
||||
RunName string `json:"runName"`
|
||||
Dataset string `json:"dataset"`
|
||||
Scores int64 `json:"scores"`
|
||||
AvgValue float64 `json:"avgValue"`
|
||||
LastTs string `json:"lastTs"`
|
||||
}
|
||||
|
||||
// aimScorePoint is one bucket of the avg-eval-score-over-time trend.
|
||||
type aimScorePoint struct {
|
||||
Ts string `json:"ts"`
|
||||
AvgValue float64 `json:"avgValue"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// aimetrics answers GET /v1/admin/aimetrics. ?range=24h|7d|30d bounds the window
|
||||
// (default 30d). SUPERADMIN ONLY (core.Guard). Every signal degrades independently:
|
||||
// a table that is absent or errors contributes its zero-value, never a failure — the
|
||||
// board always renders what the datastore actually holds.
|
||||
func aimetrics(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
ctx := c.Context()
|
||||
rangeLabel := o11yRange(c.Query("range"))
|
||||
since := computeSince(rangeLabel)
|
||||
payload := aiMetrics{
|
||||
Range: rangeLabel,
|
||||
Start: since.Format(time.RFC3339),
|
||||
End: time.Now().UTC().Format(time.RFC3339),
|
||||
TopModels: []aimModelStat{},
|
||||
LangfuseModels: []aimLfModelStat{},
|
||||
ScoreNames: []aimScoreStat{},
|
||||
EvalRuns: []aimRunStat{},
|
||||
ScoreSeries: []aimScorePoint{},
|
||||
}
|
||||
|
||||
// Honest-empty when the warehouse is not connected: the board renders its zero
|
||||
// state, never a fabricated fleet.
|
||||
if !aiobject.DatastoreEnabled() {
|
||||
return core.OK(c, payload)
|
||||
}
|
||||
|
||||
sinceTS := chTS(since) // DateTime literal — cloud_usage.timestamp, langfuse.start_time, eval_*.ts
|
||||
interval := o11yBucket(rangeLabel)
|
||||
|
||||
// ── Langfuse generations (fleet) — honest-empty until ingest lands rows ──
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimLangfuseTotalsSQL(), sinceTS); err == nil {
|
||||
r := firstRowOr(rows)
|
||||
payload.Langfuse.Generations = chInt64(r["gens"])
|
||||
payload.Langfuse.CostUsd = chFloat64(r["cost"])
|
||||
}
|
||||
// Langfuse latency (separate query so a Nullable end_time / column mismatch never
|
||||
// zeroes the proven generations+cost number above).
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimLangfuseLatencySQL(), sinceTS); err == nil {
|
||||
r := firstRowOr(rows)
|
||||
payload.Langfuse.LatencyMsAvg = chFloat64(r["lat_avg"])
|
||||
payload.Langfuse.LatencyMsP95 = chFloat64(r["lat_p95"])
|
||||
}
|
||||
// Langfuse per-model.
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimLangfuseModelsSQL(), sinceTS); err == nil {
|
||||
payload.LangfuseModels = lfModelsFromRows(rows)
|
||||
}
|
||||
|
||||
// ── Per-model usage (fleet) from the live cloud_usage ledger ──
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimUsageTotalsSQL(), sinceTS); err == nil {
|
||||
fillAimUsage(&payload.Usage, firstRowOr(rows))
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimTopModelsSQL(), sinceTS); err == nil {
|
||||
payload.TopModels = aimModelsFromRows(rows)
|
||||
}
|
||||
|
||||
// ── Evals (fleet): traces + scores + progress ──
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimEvalTracesSQL(), sinceTS); err == nil {
|
||||
fillAimEvalTraces(&payload.Evals, firstRowOr(rows))
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimEvalScoresSQL(), sinceTS); err == nil {
|
||||
fillAimEvalScores(&payload.Evals, firstRowOr(rows))
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimScoreNamesSQL(), sinceTS); err == nil {
|
||||
payload.ScoreNames = scoreNamesFromRows(rows)
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimEvalRunsSQL(), sinceTS); err == nil {
|
||||
payload.EvalRuns = evalRunsFromRows(rows)
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, aimScoreSeriesSQL(interval), sinceTS); err == nil {
|
||||
payload.ScoreSeries = scoreSeriesFromRows(rows)
|
||||
}
|
||||
|
||||
return core.OK(c, payload)
|
||||
}
|
||||
|
||||
// ── pure SQL builders (static SQL + one positional time bound; unit-tested) ──
|
||||
|
||||
func aimLangfuseTotalsSQL() string {
|
||||
return "SELECT count() AS gens, toFloat64(sum(total_cost)) AS cost FROM " + aimLangfuseObs +
|
||||
" WHERE type = 'GENERATION' AND start_time >= ?"
|
||||
}
|
||||
|
||||
func aimLangfuseLatencySQL() string {
|
||||
lat := "(toUnixTimestamp64Milli(end_time) - toUnixTimestamp64Milli(start_time))"
|
||||
return "SELECT round(avg(" + lat + "), 2) AS lat_avg, round(quantile(0.95)(" + lat + "), 2) AS lat_p95 " +
|
||||
"FROM " + aimLangfuseObs + " WHERE type = 'GENERATION' AND start_time >= ? AND end_time > start_time"
|
||||
}
|
||||
|
||||
func aimLangfuseModelsSQL() string {
|
||||
return "SELECT provided_model_name AS model, count() AS gens, toFloat64(sum(total_cost)) AS cost " +
|
||||
"FROM " + aimLangfuseObs + " WHERE type = 'GENERATION' AND start_time >= ? AND provided_model_name != '' " +
|
||||
"GROUP BY model ORDER BY gens DESC LIMIT " + strconv.Itoa(aimTopN)
|
||||
}
|
||||
|
||||
func aimUsageTotalsSQL() string {
|
||||
return "SELECT count() AS requests, sum(total_tokens) AS tokens, " +
|
||||
"sum(prompt_tokens) AS prompt_tokens, sum(completion_tokens) AS completion_tokens, " +
|
||||
"sum(cost_cents) AS cost_cents, uniqExact(model) AS models " +
|
||||
"FROM " + aimUsageTable + " WHERE timestamp >= ?"
|
||||
}
|
||||
|
||||
func aimTopModelsSQL() string {
|
||||
return "SELECT model, count() AS requests, sum(total_tokens) AS tokens, " +
|
||||
"sum(cost_cents) AS cost_cents FROM " + aimUsageTable +
|
||||
" WHERE timestamp >= ? AND model != '' GROUP BY model ORDER BY requests DESC LIMIT " + strconv.Itoa(aimTopN)
|
||||
}
|
||||
|
||||
func aimEvalTracesSQL() string {
|
||||
lat := "(toUnixTimestamp64Milli(end_time) - toUnixTimestamp64Milli(start_time))"
|
||||
return "SELECT count() AS traces, uniqExact(run_name) AS runs, uniqExact(dataset) AS datasets, " +
|
||||
"uniqExact(model) AS models, round(avgIf(" + lat + ", end_time > start_time), 2) AS lat_avg " +
|
||||
"FROM " + aimEvalTraces + " WHERE ts >= ?"
|
||||
}
|
||||
|
||||
func aimEvalScoresSQL() string {
|
||||
return "SELECT count() AS scores, round(avg(value), 4) AS avg_value, uniqExact(name) AS score_names " +
|
||||
"FROM " + aimEvalScores + " WHERE ts >= ?"
|
||||
}
|
||||
|
||||
func aimScoreNamesSQL() string {
|
||||
return "SELECT name, count() AS n, round(avg(value), 4) AS avg_value, " +
|
||||
"round(min(value), 4) AS min_value, round(max(value), 4) AS max_value " +
|
||||
"FROM " + aimEvalScores + " WHERE ts >= ? AND name != '' GROUP BY name ORDER BY n DESC LIMIT " + strconv.Itoa(aimTopN)
|
||||
}
|
||||
|
||||
func aimEvalRunsSQL() string {
|
||||
return "SELECT run_name, any(dataset) AS dataset, count() AS scores, round(avg(value), 4) AS avg_value, " +
|
||||
"max(ts) AS last_ts FROM " + aimEvalScores + " WHERE ts >= ? AND run_name != '' " +
|
||||
"GROUP BY run_name ORDER BY last_ts DESC LIMIT " + strconv.Itoa(aimTopN)
|
||||
}
|
||||
|
||||
func aimScoreSeriesSQL(interval string) string {
|
||||
return "SELECT toStartOfInterval(ts, INTERVAL " + interval + ") AS ts, " +
|
||||
"round(avg(value), 4) AS avg_value, count() AS n FROM " + aimEvalScores +
|
||||
" WHERE ts >= ? GROUP BY ts ORDER BY ts"
|
||||
}
|
||||
|
||||
// ── pure row parsers (unit-tested) ──
|
||||
|
||||
func fillAimUsage(u *aimUsage, r map[string]any) {
|
||||
u.Requests = chInt64(r["requests"])
|
||||
u.Tokens = chInt64(r["tokens"])
|
||||
u.PromptTokens = chInt64(r["prompt_tokens"])
|
||||
u.CompletionTokens = chInt64(r["completion_tokens"])
|
||||
u.CostCents = chInt64(r["cost_cents"])
|
||||
u.Models = chInt64(r["models"])
|
||||
}
|
||||
|
||||
func fillAimEvalTraces(e *aimEvals, r map[string]any) {
|
||||
e.Traces = chInt64(r["traces"])
|
||||
e.Runs = chInt64(r["runs"])
|
||||
e.Datasets = chInt64(r["datasets"])
|
||||
e.Models = chInt64(r["models"])
|
||||
e.LatencyMsAvg = chFloat64(r["lat_avg"])
|
||||
}
|
||||
|
||||
func fillAimEvalScores(e *aimEvals, r map[string]any) {
|
||||
e.Scores = chInt64(r["scores"])
|
||||
e.AvgScore = chFloat64(r["avg_value"])
|
||||
e.ScoreNames = chInt64(r["score_names"])
|
||||
}
|
||||
|
||||
func aimModelsFromRows(rows []map[string]any) []aimModelStat {
|
||||
out := make([]aimModelStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, aimModelStat{
|
||||
Model: chStr(r["model"]),
|
||||
Requests: chInt64(r["requests"]),
|
||||
Tokens: chInt64(r["tokens"]),
|
||||
CostCents: chInt64(r["cost_cents"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func lfModelsFromRows(rows []map[string]any) []aimLfModelStat {
|
||||
out := make([]aimLfModelStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, aimLfModelStat{
|
||||
Model: chStr(r["model"]),
|
||||
Generations: chInt64(r["gens"]),
|
||||
CostUsd: chFloat64(r["cost"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func scoreNamesFromRows(rows []map[string]any) []aimScoreStat {
|
||||
out := make([]aimScoreStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, aimScoreStat{
|
||||
Name: chStr(r["name"]),
|
||||
Count: chInt64(r["n"]),
|
||||
AvgValue: chFloat64(r["avg_value"]),
|
||||
MinValue: chFloat64(r["min_value"]),
|
||||
MaxValue: chFloat64(r["max_value"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func evalRunsFromRows(rows []map[string]any) []aimRunStat {
|
||||
out := make([]aimRunStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, aimRunStat{
|
||||
RunName: chStr(r["run_name"]),
|
||||
Dataset: chStr(r["dataset"]),
|
||||
Scores: chInt64(r["scores"]),
|
||||
AvgValue: chFloat64(r["avg_value"]),
|
||||
LastTs: chTime(r["last_ts"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func scoreSeriesFromRows(rows []map[string]any) []aimScorePoint {
|
||||
out := make([]aimScorePoint, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, aimScorePoint{
|
||||
Ts: chTime(r["ts"]),
|
||||
AvgValue: chFloat64(r["avg_value"]),
|
||||
Count: chInt64(r["n"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// Copyright 2023-2026 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 admin
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAimSQL_ReadsCanonicalTables proves every AI-metrics query reads the ONE
|
||||
// datastore's canonical table, binds the time bound as a POSITIONAL param (one
|
||||
// `?`), and never interpolates user input. The bucket interval is the only rendered
|
||||
// value in the series query and it is a server-side constant.
|
||||
func TestAimSQL_ReadsCanonicalTables(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, sql, table string
|
||||
wantQMarks int
|
||||
}{
|
||||
{"langfuseTotals", aimLangfuseTotalsSQL(), "langfuse.observations", 1},
|
||||
{"langfuseLatency", aimLangfuseLatencySQL(), "langfuse.observations", 1},
|
||||
{"langfuseModels", aimLangfuseModelsSQL(), "langfuse.observations", 1},
|
||||
{"usageTotals", aimUsageTotalsSQL(), "hanzo.cloud_usage", 1},
|
||||
{"topModels", aimTopModelsSQL(), "hanzo.cloud_usage", 1},
|
||||
{"evalTraces", aimEvalTracesSQL(), "hanzo.eval_traces", 1},
|
||||
{"evalScores", aimEvalScoresSQL(), "hanzo.eval_scores", 1},
|
||||
{"scoreNames", aimScoreNamesSQL(), "hanzo.eval_scores", 1},
|
||||
{"evalRuns", aimEvalRunsSQL(), "hanzo.eval_scores", 1},
|
||||
{"scoreSeries", aimScoreSeriesSQL("1 DAY"), "hanzo.eval_scores", 1},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if !strings.Contains(c.sql, "FROM "+c.table) {
|
||||
t.Errorf("%s must read %s; got %q", c.name, c.table, c.sql)
|
||||
}
|
||||
if n := strings.Count(c.sql, "?"); n != c.wantQMarks {
|
||||
t.Errorf("%s: %d bind params, want %d (time bound only) — no interpolation; got %q", c.name, n, c.wantQMarks, c.sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAimLangfuseScopedToGeneration proves the Langfuse lens is scoped to
|
||||
// generations only (not spans/events), matching the o11y LLM lens.
|
||||
func TestAimLangfuseScopedToGeneration(t *testing.T) {
|
||||
for _, sql := range []string{aimLangfuseTotalsSQL(), aimLangfuseLatencySQL(), aimLangfuseModelsSQL()} {
|
||||
if !strings.Contains(sql, "type = 'GENERATION'") {
|
||||
t.Errorf("langfuse lens must scope to GENERATION observations; got %q", sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAimTop_LimitAndOrder proves the leaderboards bound + order the result.
|
||||
func TestAimTop_LimitAndOrder(t *testing.T) {
|
||||
if !strings.Contains(aimTopModelsSQL(), "ORDER BY requests DESC LIMIT 12") {
|
||||
t.Errorf("topModels must order by requests desc, limit %d", aimTopN)
|
||||
}
|
||||
if !strings.Contains(aimScoreNamesSQL(), "GROUP BY name ORDER BY n DESC LIMIT 12") {
|
||||
t.Errorf("scoreNames must group+order+limit %d", aimTopN)
|
||||
}
|
||||
if !strings.Contains(aimEvalRunsSQL(), "ORDER BY last_ts DESC LIMIT 12") {
|
||||
t.Errorf("evalRuns must order by last_ts desc, limit %d", aimTopN)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAimScoreSeries_IntervalBound proves the (constant) bucket interval is
|
||||
// rendered into the score-trend series query and grouped/ordered by the bucket.
|
||||
func TestAimScoreSeries_IntervalBound(t *testing.T) {
|
||||
for _, iv := range []string{"1 HOUR", "6 HOUR", "1 DAY"} {
|
||||
s := aimScoreSeriesSQL(iv)
|
||||
if !strings.Contains(s, "INTERVAL "+iv) || !strings.Contains(s, "GROUP BY ts ORDER BY ts") {
|
||||
t.Errorf("score series must bucket by INTERVAL %s; got %q", iv, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAimEvalLatencyGuarded proves the latency expressions guard end_time>start_time
|
||||
// so a zero/default end_time never contributes a garbage (negative) latency.
|
||||
func TestAimEvalLatencyGuarded(t *testing.T) {
|
||||
if !strings.Contains(aimEvalTracesSQL(), "end_time > start_time") {
|
||||
t.Errorf("eval traces latency must guard end_time>start_time; got %q", aimEvalTracesSQL())
|
||||
}
|
||||
if !strings.Contains(aimLangfuseLatencySQL(), "end_time > start_time") {
|
||||
t.Errorf("langfuse latency must guard end_time>start_time; got %q", aimLangfuseLatencySQL())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillAimUsage reads a cloud_usage row into the KPI band across the numeric
|
||||
// variants the driver returns (uint64/int64/float64), honest zeros on an empty row.
|
||||
func TestFillAimUsage(t *testing.T) {
|
||||
var empty aimUsage
|
||||
fillAimUsage(&empty, map[string]any{})
|
||||
if empty.Requests != 0 || empty.Tokens != 0 || empty.Models != 0 {
|
||||
t.Fatalf("empty row must yield honest zeros; got %+v", empty)
|
||||
}
|
||||
var got aimUsage
|
||||
fillAimUsage(&got, map[string]any{
|
||||
"requests": uint64(274), "tokens": uint64(102597), "prompt_tokens": uint64(60000),
|
||||
"completion_tokens": uint64(42597), "cost_cents": uint64(216), "models": uint64(42),
|
||||
})
|
||||
if got.Requests != 274 || got.Tokens != 102597 || got.CostCents != 216 || got.Models != 42 {
|
||||
t.Fatalf("usage totals mis-parsed: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillAimEvals maps both eval halves (traces + scores) into the KPI band,
|
||||
// including the float latency/score columns (round()/avg() land as float64; a
|
||||
// Decimal-as-string is parsed).
|
||||
func TestFillAimEvals(t *testing.T) {
|
||||
var e aimEvals
|
||||
fillAimEvalTraces(&e, map[string]any{
|
||||
"traces": uint64(1280), "runs": uint64(16), "datasets": uint64(4),
|
||||
"models": uint64(6), "lat_avg": float64(842.5),
|
||||
})
|
||||
fillAimEvalScores(&e, map[string]any{
|
||||
"scores": uint64(1280), "avg_value": "0.8125", "score_names": uint64(3),
|
||||
})
|
||||
if e.Traces != 1280 || e.Runs != 16 || e.Datasets != 4 || e.Models != 6 || e.LatencyMsAvg != 842.5 {
|
||||
t.Fatalf("eval traces mis-parsed: %+v", e)
|
||||
}
|
||||
if e.Scores != 1280 || e.ScoreNames != 3 || e.AvgScore != 0.8125 { // string→float64 path
|
||||
t.Fatalf("eval scores mis-parsed: %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAimParsers map datastore rows into the view-models and preserve order (the
|
||||
// SQL already ORDER BYs; a parser must not reorder or drop rows), with empty input
|
||||
// yielding an empty (non-nil) slice rather than a panic.
|
||||
func TestAimParsers(t *testing.T) {
|
||||
models := aimModelsFromRows([]map[string]any{
|
||||
{"model": "glm-5.2", "requests": uint64(154), "tokens": uint64(38966), "cost_cents": uint64(114)},
|
||||
{"model": "deepseek-v4-flash", "requests": uint64(118), "tokens": uint64(61550), "cost_cents": uint64(101)},
|
||||
})
|
||||
if len(models) != 2 || models[0].Model != "glm-5.2" || models[1].Model != "deepseek-v4-flash" || models[0].Requests != 154 {
|
||||
t.Fatalf("top models mis-parsed/reordered: %+v", models)
|
||||
}
|
||||
lf := lfModelsFromRows([]map[string]any{
|
||||
{"model": "gpt-4o", "gens": uint64(42), "cost": float64(1.25)},
|
||||
})
|
||||
if len(lf) != 1 || lf[0].Model != "gpt-4o" || lf[0].Generations != 42 || lf[0].CostUsd != 1.25 {
|
||||
t.Fatalf("langfuse models mis-parsed: %+v", lf)
|
||||
}
|
||||
names := scoreNamesFromRows([]map[string]any{
|
||||
{"name": "accuracy", "n": uint64(320), "avg_value": float64(0.82), "min_value": float64(0), "max_value": float64(1)},
|
||||
})
|
||||
if len(names) != 1 || names[0].Name != "accuracy" || names[0].Count != 320 || names[0].AvgValue != 0.82 || names[0].MaxValue != 1 {
|
||||
t.Fatalf("score names mis-parsed: %+v", names)
|
||||
}
|
||||
runs := evalRunsFromRows([]map[string]any{
|
||||
{"run_name": "nightly-2026-07", "dataset": "gsm8k", "scores": uint64(200), "avg_value": float64(0.9), "last_ts": nil},
|
||||
})
|
||||
if len(runs) != 1 || runs[0].RunName != "nightly-2026-07" || runs[0].Dataset != "gsm8k" || runs[0].Scores != 200 || runs[0].AvgValue != 0.9 {
|
||||
t.Fatalf("eval runs mis-parsed: %+v", runs)
|
||||
}
|
||||
// Empty input → empty (non-nil) slices, never a panic.
|
||||
if got := scoreSeriesFromRows(nil); got == nil || len(got) != 0 {
|
||||
t.Errorf("nil rows must yield empty slice, got %v", got)
|
||||
}
|
||||
if got := aimModelsFromRows(nil); got == nil || len(got) != 0 {
|
||||
t.Errorf("nil rows must yield empty slice, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,9 @@ import (
|
||||
|
||||
// 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))
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/audit", core.Guard(s, Records))
|
||||
g.Get("/audit/verify", core.Guard(s, Verify))
|
||||
}
|
||||
|
||||
// Records answers GET /v1/admin/audit from cloud's local tamper-evident store when
|
||||
|
||||
@@ -203,7 +203,7 @@ func newCockpitFakes(t *testing.T) *cockpitFakes {
|
||||
}
|
||||
}))
|
||||
|
||||
_, s, fa := mountSvc(t, f.iam.URL, f.commerce.URL, "")
|
||||
_, s, fa := mountService(t, f.iam.URL, f.commerce.URL, "")
|
||||
f.service = s
|
||||
f.do = func(method, path string, hdr map[string]string, body string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/admin/money"
|
||||
"github.com/hanzoai/cloud/clients/commerceinproc"
|
||||
)
|
||||
|
||||
// errUnconfigured marks a write (Deposit) attempted against an unwired commerce.
|
||||
@@ -45,12 +46,17 @@ type Client struct {
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New builds a commerce client for base + admin S2S token.
|
||||
// New builds a commerce client for base + admin S2S token. The HTTP client uses the
|
||||
// commerceinproc self-routing transport: when commerce is CO-RESIDENT (base is the
|
||||
// commerce.inproc placeholder) it dispatches in-process — a plain http.Client would
|
||||
// instead DNS-resolve "commerce.inproc" and fail "no such host", silently breaking the
|
||||
// admin cost/finance god-view. For a split-deploy (a real commerce URL) it falls
|
||||
// through to plain HTTP unchanged.
|
||||
func New(base, token string) *Client {
|
||||
return &Client{
|
||||
base: strings.TrimRight(strings.TrimSpace(base), "/"),
|
||||
token: strings.TrimSpace(token),
|
||||
http: &http.Client{Timeout: 15 * time.Second},
|
||||
http: commerceinproc.Client(15 * time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,6 +301,18 @@ func (c *Client) Deposit(ctx context.Context, subject string, amount money.Cents
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CreateCreditGrant forwards a credit-grant request verbatim to commerce's
|
||||
// mint-gated POST /v1/billing/credit-grants (CreateCreditGrant), authenticated
|
||||
// by the admin service token, with subject as the target-org namespace selector.
|
||||
// Commerce is the sole credit-grant ledger; this relays its contract untouched
|
||||
// (the raw response is returned to the caller) so the admin surface stays thin.
|
||||
func (c *Client) CreateCreditGrant(ctx context.Context, subject string, body []byte, idempotencyKey string) ([]byte, error) {
|
||||
if !c.Ready() {
|
||||
return nil, errUnconfigured
|
||||
}
|
||||
return c.post(ctx, "/v1/billing/credit-grants", subject, body, idempotencyKey)
|
||||
}
|
||||
|
||||
// post performs one admin-authenticated commerce POST (JSON body) and returns the
|
||||
// raw response. The admin S2S service token is the bearer and X-Org-Id=<subject>
|
||||
// the per-org namespace selector commerce's EdgeAuth trusts only after verifying
|
||||
@@ -332,6 +350,48 @@ func (c *Client) post(ctx context.Context, path, subject string, body []byte, id
|
||||
return respBody, nil
|
||||
}
|
||||
|
||||
// Forward proxies an admin-authenticated request to commerce VERBATIM and returns
|
||||
// the raw body + status. It is the ONE seam a SuperAdmin surface drives commerce's
|
||||
// own endpoints through — the platform plan-promo config (/v1/platform/promo) and a
|
||||
// per-org spend-alert override (/v1/billing/spend-alerts) — without a typed method
|
||||
// per shape. subject is the X-Org-Id namespace selector (the target org for a cap
|
||||
// override, or the admin org for platform config); body is nil for GET/DELETE. The
|
||||
// status is returned so the caller surfaces commerce's OWN verdict (400 validation,
|
||||
// 403, 404) instead of flattening every non-2xx into one code.
|
||||
func (c *Client) Forward(ctx context.Context, method, path, subject string, body []byte) ([]byte, int, error) {
|
||||
if !c.Ready() {
|
||||
return nil, 0, errUnconfigured
|
||||
}
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
rdr = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base+path, rdr)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
if subject != "" {
|
||||
req.Header.Set("X-Org-Id", subject)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("commerce unreachable: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, resp.StatusCode, err
|
||||
}
|
||||
return raw, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// get performs one admin-authenticated commerce GET and returns the raw body.
|
||||
func (c *Client) get(ctx context.Context, path string, q url.Values, subject string) ([]byte, error) {
|
||||
u := c.base + path
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
// Copyright 2023-2026 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 core
|
||||
|
||||
// warehouse — the ONE-copy datastore-read kernel the billing FLEET views
|
||||
// (metrics/invoices/subscriptions) compose. They read commerce.events — the
|
||||
// single warehouse table the commerce analytics collector lands every
|
||||
// customer-activity event in (subscription/invoice/usage lifecycle) — over the
|
||||
// SAME shared client (aiobject.DatastoreQuery) the o11y/compute/analytics lenses
|
||||
// already use, no second connection. This mirrors compute.go's row-coercers and
|
||||
// EXISTS-TABLE probe, hoisted here so the three sibling domains share ONE copy
|
||||
// instead of each re-deriving it (DRY; the admin-package o11y/compute keep their
|
||||
// own private copies as the read template).
|
||||
//
|
||||
// Every read is honest by construction: no datastore connected, or the events
|
||||
// table not provisioned (the emitter is still being wired) → the real empty
|
||||
// aggregate, NEVER a fabricated fleet. admin READS only; it owns and creates NO
|
||||
// table (the collector owns commerce.events). Time bounds are POSITIONAL
|
||||
// parameters (never interpolated) so the reads are injection-safe; money is USD
|
||||
// cents; timestamps are RFC3339.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
)
|
||||
|
||||
// BillingEventsTable is the collector-owned warehouse table the commerce
|
||||
// customer-activity emitters land in (events/client.go → analytics-collector →
|
||||
// commerce.events). admin only READS it (never creates it — the collector owns
|
||||
// its writes), exactly as o11y reads hanzo.cloud_usage.
|
||||
const BillingEventsTable = "commerce.events"
|
||||
|
||||
// Canonical customer-activity event names — the CONTRACT with the commerce
|
||||
// emitters (events/client.go). These are server-side constants (never user
|
||||
// input), so rendering them into an IN (...) list is injection-safe.
|
||||
const (
|
||||
EvSubscriptionCreated = "subscription_created"
|
||||
EvSubscriptionRenewed = "subscription_renewed"
|
||||
EvSubscriptionPlanChanged = "subscription_plan_changed"
|
||||
EvSubscriptionCanceled = "subscription_canceled"
|
||||
EvInvoiceFinalized = "invoice_finalized"
|
||||
EvInvoicePaid = "invoice_paid"
|
||||
EvInvoiceVoid = "invoice_void"
|
||||
EvAPIUsageDebit = "api_usage_debit"
|
||||
)
|
||||
|
||||
// SubscriptionEvents / InvoiceEvents are the lifecycle sets each fleet view
|
||||
// folds over (latest-event-wins per entity). Closed server-side constants.
|
||||
var (
|
||||
SubscriptionEvents = []string{EvSubscriptionCreated, EvSubscriptionRenewed, EvSubscriptionPlanChanged, EvSubscriptionCanceled}
|
||||
InvoiceEvents = []string{EvInvoiceFinalized, EvInvoicePaid, EvInvoiceVoid}
|
||||
)
|
||||
|
||||
// WarehouseReady reports whether the shared datastore ledger is connected, the
|
||||
// gate every fleet read checks first (honest-empty when false).
|
||||
func WarehouseReady() bool { return aiobject.DatastoreEnabled() }
|
||||
|
||||
// BillingEventsReady reports whether the warehouse is connected AND the
|
||||
// collector's commerce.events table is provisioned — the two-part gate every
|
||||
// billing fleet view opens with, so an unwired collector degrades to an honest
|
||||
// empty aggregate rather than an error.
|
||||
func BillingEventsReady(ctx context.Context) bool {
|
||||
return aiobject.DatastoreEnabled() && CHTableExists(ctx, BillingEventsTable)
|
||||
}
|
||||
|
||||
// CHTableExists probes the datastore for a table's presence. The name is a
|
||||
// package constant (never user input), so EXISTS TABLE is safe. Any error →
|
||||
// false (honest "not available yet"), mirroring compute.computeTableExists.
|
||||
func CHTableExists(ctx context.Context, qualified string) bool {
|
||||
rows, err := aiobject.DatastoreQuery(ctx, "EXISTS TABLE "+qualified)
|
||||
if err != nil || len(rows) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, v := range rows[0] {
|
||||
return CHInt64(v) == 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SQLInList renders a set of server-side-constant strings as a datastore string
|
||||
// list ('a','b',…) for an IN (...) clause. ONLY for closed constant sets (the
|
||||
// event-name enums above) — never for user input; positional args carry all
|
||||
// caller-derived values.
|
||||
func SQLInList(vals []string) string {
|
||||
quoted := make([]string, len(vals))
|
||||
for i, v := range vals {
|
||||
quoted[i] = "'" + v + "'"
|
||||
}
|
||||
return strings.Join(quoted, ",")
|
||||
}
|
||||
|
||||
// WarehouseSince maps the ?range enum (24h|7d|30d, default 30d) to a lower time
|
||||
// bound, mirroring compute.computeSince so the fleet views share ONE window
|
||||
// grammar.
|
||||
func WarehouseSince(rangeLabel string) time.Time {
|
||||
now := time.Now().UTC()
|
||||
switch strings.TrimSpace(rangeLabel) {
|
||||
case "24h":
|
||||
return now.Add(-24 * time.Hour)
|
||||
case "7d":
|
||||
return now.Add(-7 * 24 * time.Hour)
|
||||
default:
|
||||
return now.Add(-30 * 24 * time.Hour)
|
||||
}
|
||||
}
|
||||
|
||||
// CHTimeLit formats a time as a datastore DateTime literal (UTC), bound as a
|
||||
// POSITIONAL string arg (never interpolated).
|
||||
func CHTimeLit(t time.Time) string { return t.UTC().Format("2006-01-02 15:04:05") }
|
||||
|
||||
// CHFirstRow returns the first row or an empty map (never nil), so a parser
|
||||
// reads honest zeros from an empty result instead of panicking.
|
||||
func CHFirstRow(rows []map[string]any) map[string]any {
|
||||
if len(rows) == 0 {
|
||||
return map[string]any{}
|
||||
}
|
||||
return rows[0]
|
||||
}
|
||||
|
||||
// ── map[string]any coercers (the DatastoreQuery row shape) ───────────────────
|
||||
//
|
||||
// The datastore driver decodes each column to its native Go type (uint64 for
|
||||
// count()/sum(UInt*), float64 for round()/JSON numerics, time.Time for DateTime,
|
||||
// string for String); these accept those natives so a driver/transport change
|
||||
// can't crash a read. Twins of the admin-package compute.go coercers.
|
||||
|
||||
func CHInt64(v any) int64 {
|
||||
switch n := v.(type) {
|
||||
case int:
|
||||
return int64(n)
|
||||
case int64:
|
||||
return n
|
||||
case int32:
|
||||
return int64(n)
|
||||
case uint:
|
||||
return int64(n)
|
||||
case uint64:
|
||||
return int64(n)
|
||||
case uint32:
|
||||
return int64(n)
|
||||
case uint16:
|
||||
return int64(n)
|
||||
case uint8:
|
||||
return int64(n)
|
||||
case float64:
|
||||
return int64(n)
|
||||
case float32:
|
||||
return int64(n)
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(n), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return int64(f)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func CHFloat64(v any) float64 {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return n
|
||||
case float32:
|
||||
return float64(n)
|
||||
case int:
|
||||
return float64(n)
|
||||
case int64:
|
||||
return float64(n)
|
||||
case int32:
|
||||
return float64(n)
|
||||
case uint64:
|
||||
return float64(n)
|
||||
case uint32:
|
||||
return float64(n)
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(n), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return f
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func CHStr(v any) string {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// CHTime coerces a datastore DateTime (time.Time) to an RFC3339 UTC string.
|
||||
func CHTime(v any) string {
|
||||
switch t := v.(type) {
|
||||
case time.Time:
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
case string:
|
||||
return t
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/audit"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// createCreditGrant is the admin mint surface: POST /v1/admin/credit-grants.
|
||||
//
|
||||
// SuperAdmin ONLY (wired through core.Guard). It does NOT mint in-process — it
|
||||
// forwards the request VERBATIM to commerce's already-mint-gated
|
||||
// POST /v1/billing/credit-grants (middleware.Mint → PlatformOnly), authenticated
|
||||
// by COMMERCE_SERVICE_TOKEN and scoped to the target org, and writes ONE
|
||||
// tamper-evident compliance record. Commerce stays the single credit-grant ledger;
|
||||
// this is a thin, audited relay so there is exactly one place credit is minted.
|
||||
//
|
||||
// The body is commerce's own CreateCreditGrant contract; the only field this layer
|
||||
// reads is the target org (`org`, or `user` as the org-pool alias) to select the
|
||||
// per-org namespace commerce's EdgeAuth trusts after verifying the service token.
|
||||
func createCreditGrant(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
if !s.State.Commerce.Ready() {
|
||||
return core.Fail(c, "commerce is not configured on this deployment")
|
||||
}
|
||||
|
||||
var req map[string]any
|
||||
if err := c.Bind(&req); err != nil {
|
||||
return core.Fail(c, "invalid request body")
|
||||
}
|
||||
|
||||
org, _ := req["org"].(string)
|
||||
if strings.TrimSpace(org) == "" {
|
||||
org, _ = req["user"].(string)
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
if org == "" {
|
||||
return core.Fail(c, "org is required")
|
||||
}
|
||||
idempotencyKey, _ := req["idempotencyKey"].(string)
|
||||
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return core.Fail(c, "invalid request body")
|
||||
}
|
||||
|
||||
raw, err := s.State.Commerce.CreateCreditGrant(c.Context(), org, body, idempotencyKey)
|
||||
if err != nil {
|
||||
core.EmitAudit(s, c, "admin.customer.credit-grant", "credit-grant", org,
|
||||
req, map[string]any{"error": err.Error()},
|
||||
audit.Outcome{Result: "error", Status: 502, Reason: "credit-grant failed"})
|
||||
return core.Fail(c, "credit-grant failed: "+err.Error())
|
||||
}
|
||||
|
||||
core.EmitAudit(s, c, "admin.customer.credit-grant", "credit-grant", org,
|
||||
nil, json.RawMessage(raw),
|
||||
audit.Outcome{Result: "success", Status: 200})
|
||||
return core.OK(c, json.RawMessage(raw))
|
||||
}
|
||||
@@ -10,11 +10,12 @@ import (
|
||||
// precedes the :org param route; the write actions are POST (distinct method), so none
|
||||
// collide. The grants ledger + the org-in-body issue-grant share the ONE credit path.
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
app.Get("/v1/admin/customers", core.Guard(s, Customers))
|
||||
app.Get("/v1/admin/customers/:org", core.Guard(s, CustomerDetail))
|
||||
app.Post("/v1/admin/customers/:org/credit", core.Guard(s, GrantCredit))
|
||||
app.Get("/v1/admin/grants", core.Guard(s, Grants))
|
||||
app.Post("/v1/admin/grants", core.Guard(s, IssueGrant))
|
||||
app.Post("/v1/admin/customers/:org/suspend", core.Guard(s, SuspendCustomer))
|
||||
app.Post("/v1/admin/customers/:org/reactivate", core.Guard(s, ReactivateCustomer))
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/customers", core.Guard(s, Customers))
|
||||
g.Get("/customers/:org", core.Guard(s, CustomerDetail))
|
||||
g.Post("/customers/:org/credit", core.Guard(s, GrantCredit))
|
||||
g.Get("/grants", core.Guard(s, Grants))
|
||||
g.Post("/grants", core.Guard(s, IssueGrant))
|
||||
g.Post("/customers/:org/suspend", core.Guard(s, SuspendCustomer))
|
||||
g.Post("/customers/:org/reactivate", core.Guard(s, ReactivateCustomer))
|
||||
}
|
||||
|
||||
@@ -28,16 +28,17 @@ var errUnconfigured = errors.New("not configured")
|
||||
|
||||
// Routes registers the finance dashboard (SuperAdmin only).
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
app.Get("/v1/admin/finance", core.Guard(s, Finance))
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/finance", core.Guard(s, Finance))
|
||||
// One-time commerce→finance balance cutover (SuperAdmin only). Idempotent per org.
|
||||
app.Post("/v1/admin/finance/backfill", core.Guard(s, Backfill))
|
||||
g.Post("/finance/backfill", core.Guard(s, Backfill))
|
||||
// Fund an ARBITRARY subject's native wallet — an org pool or a human ("hanzo/z").
|
||||
// SuperAdmin only; additive (grants stack).
|
||||
app.Post("/v1/admin/finance/deposit", core.Guard(s, Deposit))
|
||||
g.Post("/finance/deposit", core.Guard(s, Deposit))
|
||||
// Per-provider upstream credit ledger + usage funding split (multi-provider
|
||||
// credit-management). Same SuperAdmin guard, same cloud_usage warehouse.
|
||||
app.Get("/v1/admin/providers/credit", core.Guard(s, ProvidersCredit))
|
||||
app.Get("/v1/admin/usage/funding", core.Guard(s, UsageFunding))
|
||||
g.Get("/providers/credit", core.Guard(s, ProvidersCredit))
|
||||
g.Get("/usage/funding", core.Guard(s, UsageFunding))
|
||||
}
|
||||
|
||||
// FinanceData is the full /v1/admin/finance aggregate.
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
// The finance PURE-math derivation tests (ComputeFinance / AvgDailyBurnCents) live with
|
||||
// the handler in clients/admin/finance. These are the INTEGRATION tests that drive GET
|
||||
// /v1/admin/finance through the shared admin mount harness (mountSvc + fake IAM/commerce/DO).
|
||||
// /v1/admin/finance through the shared admin mount harness (mountService + fake IAM/commerce/DO).
|
||||
|
||||
// newFakeDO serves the DO billing API with fixed decimal-dollar strings so the
|
||||
// finance aggregation is deterministic. account_balance is NEGATIVE (credit held).
|
||||
@@ -49,7 +49,7 @@ func TestFinance_RealAggregation(t *testing.T) {
|
||||
do := newFakeDO()
|
||||
defer do.Close()
|
||||
|
||||
doReq, s, _ := mountSvc(t, iam.server.URL, commerce.URL, "")
|
||||
doReq, s, _ := mountService(t, iam.server.URL, commerce.URL, "")
|
||||
s.State.DO = digitalocean.NewWithBase(do.URL, "test-do-token") // configured DO client
|
||||
admin := map[string]string{
|
||||
"X-User-IsAdmin": "true", "X-Org-Id": "admin",
|
||||
@@ -151,7 +151,7 @@ func TestFinance_HonestUnconfiguredDO(t *testing.T) {
|
||||
commerce := newFakeCommerceFinance()
|
||||
defer commerce.Close()
|
||||
|
||||
doReq, _, _ := mountSvc(t, iam.server.URL, commerce.URL, "") // s.do already has empty token → unconfigured
|
||||
doReq, _, _ := mountService(t, iam.server.URL, commerce.URL, "") // s.do already has empty token → unconfigured
|
||||
admin := map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin"}
|
||||
|
||||
resp, body := doReq("GET", "/v1/admin/finance", admin)
|
||||
@@ -212,7 +212,7 @@ func TestFinance_RevenueSourceDown_NoFabrication(t *testing.T) {
|
||||
defer commerce.Close()
|
||||
|
||||
// IAM points nowhere reachable → listOrgs errors; commerce /v1/costs still 200s.
|
||||
doReq, _, _ := mountSvc(t, "http://127.0.0.1:0", commerce.URL, "")
|
||||
doReq, _, _ := mountService(t, "http://127.0.0.1:0", commerce.URL, "")
|
||||
admin := map[string]string{"X-User-IsAdmin": "true", "X-Org-Id": "admin"}
|
||||
|
||||
resp, body := doReq("GET", "/v1/admin/finance", admin)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// Package invoices is the fleet INVOICE view (/v1/admin/invoices) — every issued
|
||||
// invoice across every tenant: number, org, amount, status, issue + due date, plus the
|
||||
// id a future detail view fetches /v1/billing/invoices/:id with. SuperAdmin only
|
||||
// (core.Guard).
|
||||
//
|
||||
// It reads the ONE shared warehouse (commerce.events) — the table the commerce
|
||||
// analytics collector lands every invoice-lifecycle event in — over the SAME client
|
||||
// (aiobject.DatastoreQuery) the o11y/compute lenses use, with ZERO per-org fan-out:
|
||||
// one GROUP BY resolves each invoice's LATEST lifecycle state (argMax by timestamp),
|
||||
// so the whole fleet is one query, not N per-org commerce reads. Honest by
|
||||
// construction: no datastore connected or the collector's table not provisioned yet →
|
||||
// the real empty list, never a fabricated row. Optional ?org= scopes to one tenant,
|
||||
// ?status= filters the LATEST status, ?limit= caps the list.
|
||||
package invoices
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// defaultLimit caps the fleet invoice list when the caller sends none.
|
||||
const defaultLimit = 500
|
||||
|
||||
// InvoiceRow is one row of GET /v1/admin/invoices — an issued invoice at a glance,
|
||||
// tagged with its owning org. Money is USD cents; timestamps are RFC3339 strings.
|
||||
type InvoiceRow struct {
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Org string `json:"org"`
|
||||
Display string `json:"display"`
|
||||
Status string `json:"status"`
|
||||
AmountCents int64 `json:"amountCents"`
|
||||
Currency string `json:"currency"`
|
||||
Issued string `json:"issued"`
|
||||
Due string `json:"due"`
|
||||
}
|
||||
|
||||
// Invoices answers GET /v1/admin/invoices.
|
||||
//
|
||||
// GET /v1/admin/invoices?org=&status=&limit=
|
||||
func Invoices(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
ctx := c.Context()
|
||||
status := strings.ToLower(strings.TrimSpace(c.Query("status")))
|
||||
wantOrg := strings.TrimSpace(c.Query("org"))
|
||||
limit := parseLimit(c.Query("limit"))
|
||||
|
||||
// Honest-empty when the warehouse is not connected or the collector's events
|
||||
// table is not provisioned yet (the emitter is still being wired).
|
||||
if !core.BillingEventsReady(ctx) {
|
||||
return core.OKList(c, []InvoiceRow{}, 0)
|
||||
}
|
||||
|
||||
rows, err := aiobject.DatastoreQuery(ctx, invoicesSQL())
|
||||
if err != nil {
|
||||
return core.Fail(c, "invoices query: "+err.Error())
|
||||
}
|
||||
all := invoiceRowsFromRows(rows)
|
||||
|
||||
// Filter (latest status / org) then newest issued first, cap to limit.
|
||||
out := make([]InvoiceRow, 0, len(all))
|
||||
for _, r := range all {
|
||||
if wantOrg != "" && r.Org != wantOrg {
|
||||
continue
|
||||
}
|
||||
if status != "" && strings.ToLower(r.Status) != status {
|
||||
continue
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Issued > out[j].Issued })
|
||||
total := len(out)
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return core.OKList(c, out, total)
|
||||
}
|
||||
|
||||
// invoicesSQL resolves each invoice's LATEST lifecycle state from commerce.events
|
||||
// (argMax by timestamp). Static SQL over a closed event-name set (SQLInList of
|
||||
// server constants) — no user input is interpolated, so it is injection-safe.
|
||||
func invoicesSQL() string {
|
||||
return "SELECT JSONExtractString(properties, 'invoice_id') AS id, " +
|
||||
"argMax(JSONExtractString(properties, 'number'), timestamp) AS number, " +
|
||||
"argMax(organization_id, timestamp) AS org, " +
|
||||
"argMax(JSONExtractString(properties, 'status'), timestamp) AS status, " +
|
||||
"argMax(JSONExtractInt(properties, 'amount_cents'), timestamp) AS amount_cents, " +
|
||||
"argMax(JSONExtractString(properties, 'currency'), timestamp) AS currency, " +
|
||||
"argMax(JSONExtractString(properties, 'issued'), timestamp) AS issued, " +
|
||||
"argMax(JSONExtractString(properties, 'due'), timestamp) AS due, " +
|
||||
"argMax(event, timestamp) AS last_event " +
|
||||
"FROM " + core.BillingEventsTable + " " +
|
||||
"WHERE event IN (" + core.SQLInList(core.InvoiceEvents) + ") " +
|
||||
"AND JSONExtractString(properties, 'invoice_id') != '' " +
|
||||
"GROUP BY id"
|
||||
}
|
||||
|
||||
// invoiceRowsFromRows maps the datastore rows onto []InvoiceRow (pure). Display is
|
||||
// the org slug — the warehouse holds no friendly name and admin does no per-org IAM
|
||||
// fan-out here (honest, not fabricated). Status folds the lifecycle from the latest
|
||||
// event so a paid/voided invoice reads correctly regardless of the status snapshot.
|
||||
func invoiceRowsFromRows(rows []map[string]any) []InvoiceRow {
|
||||
out := make([]InvoiceRow, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
org := core.CHStr(r["org"])
|
||||
out = append(out, InvoiceRow{
|
||||
ID: core.CHStr(r["id"]),
|
||||
Number: core.CHStr(r["number"]),
|
||||
Org: org,
|
||||
Display: org,
|
||||
Status: foldInvoiceStatus(core.CHStr(r["last_event"]), core.CHStr(r["status"])),
|
||||
AmountCents: core.CHInt64(r["amount_cents"]),
|
||||
Currency: core.CHStr(r["currency"]),
|
||||
Issued: core.CHStr(r["issued"]),
|
||||
Due: core.CHStr(r["due"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// foldInvoiceStatus resolves the effective status from the latest lifecycle event
|
||||
// (paid / void terminal), falling back to the last-emitted status snapshot (open
|
||||
// for a finalized invoice) when the event is a finalize.
|
||||
func foldInvoiceStatus(lastEvent, snapshot string) string {
|
||||
switch lastEvent {
|
||||
case core.EvInvoicePaid:
|
||||
return "paid"
|
||||
case core.EvInvoiceVoid:
|
||||
return "void"
|
||||
}
|
||||
if s := strings.TrimSpace(snapshot); s != "" {
|
||||
return s
|
||||
}
|
||||
return "open"
|
||||
}
|
||||
|
||||
// parseLimit clamps the fleet-list cap to [1,5000], defaulting to defaultLimit.
|
||||
func parseLimit(s string) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(s))
|
||||
if err != nil || n <= 0 {
|
||||
return defaultLimit
|
||||
}
|
||||
if n > 5000 {
|
||||
return 5000
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package invoices
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
)
|
||||
|
||||
// TestInvoiceRowsFromRows proves the warehouse-row → InvoiceRow mapping (JSON-shape
|
||||
// contract): amount coerced from driver ints, status folded from the latest event,
|
||||
// display honestly the org slug (no fan-out).
|
||||
func TestInvoiceRowsFromRows(t *testing.T) {
|
||||
rows := []map[string]any{
|
||||
{
|
||||
"id": "inv_1", "number": "INV-0042", "org": "acme",
|
||||
"status": "open", "amount_cents": int64(4900), "currency": "usd",
|
||||
"issued": "2026-07-01T00:00:00Z", "due": "2026-07-15T00:00:00Z",
|
||||
"last_event": core.EvInvoicePaid,
|
||||
},
|
||||
{
|
||||
"id": "inv_2", "number": "INV-0043", "org": "beta",
|
||||
"status": "open", "amount_cents": uint64(1200), "currency": "usd",
|
||||
"issued": "2026-07-02T00:00:00Z", "due": "",
|
||||
"last_event": core.EvInvoiceVoid,
|
||||
},
|
||||
}
|
||||
out := invoiceRowsFromRows(rows)
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("got %d rows, want 2", len(out))
|
||||
}
|
||||
if out[0].ID != "inv_1" || out[0].Number != "INV-0042" || out[0].Org != "acme" || out[0].Display != "acme" {
|
||||
t.Fatalf("row0 identity wrong: %+v", out[0])
|
||||
}
|
||||
if out[0].AmountCents != 4900 || out[0].Currency != "usd" {
|
||||
t.Fatalf("row0 amount/currency wrong: %+v", out[0])
|
||||
}
|
||||
if out[0].Status != "paid" {
|
||||
t.Fatalf("row0 status = %q, want paid (paid event folds)", out[0].Status)
|
||||
}
|
||||
if out[0].Issued != "2026-07-01T00:00:00Z" || out[0].Due != "2026-07-15T00:00:00Z" {
|
||||
t.Fatalf("row0 dates wrong: %+v", out[0])
|
||||
}
|
||||
if out[1].Status != "void" {
|
||||
t.Fatalf("row1 status = %q, want void", out[1].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldInvoiceStatus(t *testing.T) {
|
||||
if got := foldInvoiceStatus(core.EvInvoicePaid, "open"); got != "paid" {
|
||||
t.Fatalf("paid fold = %q", got)
|
||||
}
|
||||
if got := foldInvoiceStatus(core.EvInvoiceVoid, "open"); got != "void" {
|
||||
t.Fatalf("void fold = %q", got)
|
||||
}
|
||||
if got := foldInvoiceStatus(core.EvInvoiceFinalized, "open"); got != "open" {
|
||||
t.Fatalf("finalized snapshot = %q", got)
|
||||
}
|
||||
if got := foldInvoiceStatus(core.EvInvoiceFinalized, ""); got != "open" {
|
||||
t.Fatalf("finalized default = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoicesSQLInjectionSafe(t *testing.T) {
|
||||
sql := invoicesSQL()
|
||||
if !strings.Contains(sql, core.BillingEventsTable) {
|
||||
t.Fatalf("query must read %s: %q", core.BillingEventsTable, sql)
|
||||
}
|
||||
for _, ev := range core.InvoiceEvents {
|
||||
if !strings.Contains(sql, "'"+ev+"'") {
|
||||
t.Fatalf("query missing event %q", ev)
|
||||
}
|
||||
}
|
||||
if strings.Contains(sql, "?") {
|
||||
t.Fatalf("invoices state query takes no positional args: %q", sql)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package invoices
|
||||
|
||||
import (
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// Routes registers the fleet invoice view (SuperAdmin only, cross-tenant).
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/invoices", core.Guard(s, Invoices))
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// The SuperAdmin usage-cap + promo control plane, twinning /v1/admin/flags. It owns
|
||||
// no store: it FORWARDS to commerce (the billing source of truth) over the ONE
|
||||
// service-token seam —
|
||||
//
|
||||
// promos → commerce /v1/platform/promo (the admin-configured plan promo)
|
||||
// spend-caps → commerce /v1/billing/spend-alerts (a per-org usage cap override)
|
||||
//
|
||||
// so admin.hanzo.ai configures the 50%-off promo and oversees/overrides any org's
|
||||
// caps without a parallel model. Promo routes are platform-only (core.Guard); cap
|
||||
// routes are org-scoped (core.GuardScoped) so a SuperAdmin targets any org via ?org=
|
||||
// while a lesser admin is hard-pinned to their own.
|
||||
|
||||
// limitRoutes registers the promo + cap control plane. Called from routes().
|
||||
func limitRoutes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
g := app.Group("/v1/admin")
|
||||
// Platform plan promo — SuperAdmin only.
|
||||
g.Get("/promos", core.Guard(s, getPromo))
|
||||
g.Put("/promos", core.Guard(s, putPromo))
|
||||
|
||||
// Per-org usage-cap oversight/override — SuperAdmin (any org via ?org=) or an org
|
||||
// admin (own org only). Reuses the customer's OWN self-service spend-alert CRUD,
|
||||
// so a platform override and a customer edit are the same rows.
|
||||
g.Get("/spend-caps", core.GuardScoped(s, listSpendCaps))
|
||||
g.Post("/spend-caps", core.GuardScoped(s, createSpendCap))
|
||||
g.Patch("/spend-caps/:id", core.GuardScoped(s, updateSpendCap))
|
||||
g.Delete("/spend-caps/:id", core.GuardScoped(s, deleteSpendCap))
|
||||
}
|
||||
|
||||
// getPromo returns the current platform plan promo. X-Org-Id is the admin org —
|
||||
// commerce stores the singleton in the reserved platform namespace regardless, and
|
||||
// the service token is what passes commerce's RequirePlatformAdmin.
|
||||
func getPromo(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodGet, "/v1/platform/promo", s.State.AdminOrg, nil)
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// putPromo upserts the platform plan promo from the SuperAdmin's {percentOff,start,
|
||||
// end,plans,active} body — the ONE place the 50%-off offer is configured.
|
||||
func putPromo(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodPut, "/v1/platform/promo", s.State.AdminOrg, c.Body())
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// listSpendCaps returns a target org's usage caps (spend-alerts + derived period
|
||||
// spend/over/warn/resetsAt). The org is the SuperAdmin's ?org= or, for a scoped
|
||||
// admin, their own — never a client-widened scope.
|
||||
func listSpendCaps(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
org, ok := targetOrg(s, c)
|
||||
if !ok {
|
||||
return core.Fail(c, "org required")
|
||||
}
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodGet, "/v1/billing/spend-alerts", org, nil)
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// createSpendCap sets a cap on a target org (platform override of a customer budget).
|
||||
func createSpendCap(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
org, ok := targetOrg(s, c)
|
||||
if !ok {
|
||||
return core.Fail(c, "org required")
|
||||
}
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodPost, "/v1/billing/spend-alerts", org, c.Body())
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// updateSpendCap edits a target org's cap by id (raise/lower the ceiling, flip enforce).
|
||||
func updateSpendCap(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
org, ok := targetOrg(s, c)
|
||||
if !ok {
|
||||
return core.Fail(c, "org required")
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
if id == "" {
|
||||
return core.Fail(c, "cap id required")
|
||||
}
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodPatch, "/v1/billing/spend-alerts/"+url.PathEscape(id), org, c.Body())
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// deleteSpendCap removes a target org's cap by id.
|
||||
func deleteSpendCap(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
org, ok := targetOrg(s, c)
|
||||
if !ok {
|
||||
return core.Fail(c, "org required")
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
if id == "" {
|
||||
return core.Fail(c, "cap id required")
|
||||
}
|
||||
raw, status, err := s.State.Commerce.Forward(c.Context(), http.MethodDelete, "/v1/billing/spend-alerts/"+url.PathEscape(id), org, nil)
|
||||
return relay(c, raw, status, err)
|
||||
}
|
||||
|
||||
// targetOrg resolves which org a cap operation acts on: a SuperAdmin names it with
|
||||
// ?org=; a scoped admin is hard-pinned to their own subtree (?org= ignored). Empty
|
||||
// (false) when unresolvable, so the handler fails closed rather than acting on a
|
||||
// guessed tenant.
|
||||
func targetOrg(s *cloud.Service[core.State], c *zip.Ctx) (string, bool) {
|
||||
sc := core.ResolveScope(s, c)
|
||||
if sc.Super {
|
||||
if org := strings.TrimSpace(c.Query("org")); org != "" {
|
||||
return org, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if len(sc.Orgs) > 0 && strings.TrimSpace(sc.Orgs[0]) != "" {
|
||||
return sc.Orgs[0], true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// relay surfaces commerce's OWN verdict in the /v1 envelope: a 2xx passes the raw
|
||||
// JSON through as data (so the console decodes the exact SpendAlert/Promo shape), a
|
||||
// non-2xx becomes an honest failure carrying commerce's status + message rather than
|
||||
// masking a 400 validation as success.
|
||||
func relay(c *zip.Ctx, raw []byte, status int, err error) error {
|
||||
if err != nil {
|
||||
return core.Fail(c, err.Error())
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
msg := strings.TrimSpace(string(raw))
|
||||
if msg == "" {
|
||||
msg = http.StatusText(status)
|
||||
}
|
||||
return core.Fail(c, msg)
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return core.OK(c, map[string]any{"ok": true})
|
||||
}
|
||||
return core.OKRaw(c, json.RawMessage(raw), 0)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// recCommerce records the X-Org-Id + method + path of the last forwarded request so a
|
||||
// test can prove the /v1/admin control plane targets the RIGHT tenant namespace, and
|
||||
// serves the promo + spend-alert shapes verbatim.
|
||||
type recCommerce struct {
|
||||
server *httptest.Server
|
||||
mu sync.Mutex
|
||||
lastOrg string
|
||||
lastMethod string
|
||||
lastPath string
|
||||
}
|
||||
|
||||
func newRecCommerce() *recCommerce {
|
||||
f := &recCommerce{}
|
||||
f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
f.lastOrg = r.Header.Get("X-Org-Id")
|
||||
f.lastMethod = r.Method
|
||||
f.lastPath = r.URL.Path
|
||||
f.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/platform/promo"):
|
||||
io.WriteString(w, `{"percentOff":50,"plans":["pro"],"active":true}`)
|
||||
case strings.HasSuffix(r.URL.Path, "/spend-alerts"):
|
||||
io.WriteString(w, `[{"id":"a1","threshold":10000,"enforce":true,"period":"2026-07","resetsAt":"2026-08-01T00:00:00Z"}]`)
|
||||
default:
|
||||
io.WriteString(w, `{}`)
|
||||
}
|
||||
}))
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *recCommerce) seen() (string, string, string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.lastMethod, f.lastPath, f.lastOrg
|
||||
}
|
||||
|
||||
func envStatus(t *testing.T, body []byte) string {
|
||||
t.Helper()
|
||||
var e struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &e)
|
||||
return e.Status
|
||||
}
|
||||
|
||||
// The promo control plane is SuperAdmin-only (core.Guard) and forwards to commerce's
|
||||
// platform-promo endpoint.
|
||||
func TestLimits_Promo_SuperOnly(t *testing.T) {
|
||||
iam := newScopeIAM()
|
||||
defer iam.server.Close()
|
||||
com := newRecCommerce()
|
||||
defer com.server.Close()
|
||||
do := mount(t, iam.server.URL, com.server.URL, "")
|
||||
|
||||
// SuperAdmin GET → 200 ok, forwarded to /v1/platform/promo.
|
||||
resp, body := do("GET", "/v1/admin/promos", superHdr)
|
||||
if resp.StatusCode != http.StatusOK || envStatus(t, body) != "ok" {
|
||||
t.Fatalf("super GET promos = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if m, p, _ := com.seen(); m != "GET" || !strings.HasSuffix(p, "/platform/promo") {
|
||||
t.Fatalf("forwarded %s %s, want GET .../platform/promo", m, p)
|
||||
}
|
||||
|
||||
// SuperAdmin PUT → forwarded as PUT.
|
||||
if resp, _ := do("PUT", "/v1/admin/promos", superHdr); resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("super PUT promos = %d", resp.StatusCode)
|
||||
}
|
||||
if m, _, _ := com.seen(); m != "PUT" {
|
||||
t.Fatalf("promo PUT forwarded as %s, want PUT", m)
|
||||
}
|
||||
|
||||
// A non-super org admin is REFUSED at the platform gate (403), never reaching commerce.
|
||||
if resp, _ := do("GET", "/v1/admin/promos", orgAdminHdr); resp.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("org-admin GET promos = %d, want 403 (platform-only)", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Cap oversight is org-scoped: a SuperAdmin targets any org via ?org=; a scoped admin
|
||||
// is hard-pinned to their OWN org (a client ?org= is ignored — the escalation line).
|
||||
func TestLimits_SpendCaps_OrgScoped(t *testing.T) {
|
||||
iam := newScopeIAM()
|
||||
defer iam.server.Close()
|
||||
com := newRecCommerce()
|
||||
defer com.server.Close()
|
||||
do := mount(t, iam.server.URL, com.server.URL, "")
|
||||
|
||||
// SuperAdmin with ?org=maxpower → forwards X-Org-Id=maxpower.
|
||||
resp, body := do("GET", "/v1/admin/spend-caps?org=maxpower", superHdr)
|
||||
if resp.StatusCode != http.StatusOK || envStatus(t, body) != "ok" {
|
||||
t.Fatalf("super spend-caps = %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if _, p, org := com.seen(); org != "maxpower" || !strings.HasSuffix(p, "/spend-alerts") {
|
||||
t.Fatalf("forwarded org=%q path=%q, want maxpower .../spend-alerts", org, p)
|
||||
}
|
||||
|
||||
// SuperAdmin WITHOUT ?org → org required (honest error, no guessed tenant).
|
||||
if _, body := do("GET", "/v1/admin/spend-caps", superHdr); envStatus(t, body) != "error" {
|
||||
t.Fatalf("super spend-caps without org must be an error envelope, got %s", body)
|
||||
}
|
||||
|
||||
// A scoped org admin naming a FOREIGN ?org=hanzo is hard-pinned to their OWN org.
|
||||
do("GET", "/v1/admin/spend-caps?org=hanzo", orgAdminHdr)
|
||||
if _, _, org := com.seen(); org != "maxpower" {
|
||||
t.Fatalf("scoped admin forwarded org=%q, want maxpower (client ?org= must be ignored)", org)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
// Package metrics is the fleet SaaS-operations god-view (/v1/admin/metrics) — the
|
||||
// operator's business dashboard: MRR/ARR, net-new vs churned MRR, the plan/category
|
||||
// mix, the top customers, and the recent subscription movements. SuperAdmin only
|
||||
// (core.Guard).
|
||||
//
|
||||
// It reads the ONE shared warehouse (commerce.events) — the table the commerce
|
||||
// analytics collector lands every subscription/invoice/usage-lifecycle event in —
|
||||
// over the SAME client (aiobject.DatastoreQuery) the o11y/compute lenses use, with
|
||||
// ZERO per-org fan-out. Each panel is ONE aggregate query that folds the whole fleet
|
||||
// (subscription state = latest-event-wins via argMax; new/churn/usage = windowed),
|
||||
// exactly the way o11y.go composes independent per-signal reads. An unconnected
|
||||
// warehouse — or the collector's events table not provisioned yet — degrades to an
|
||||
// honest empty snapshot (real zeros, `[]` not null) with a not-ok source, never a
|
||||
// fabricated number. Money is USD cents end to end; time bounds are POSITIONAL args.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/hanzoai/cloud/clients/admin/money"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// errUnconfigured marks the warehouse not connected on this deployment — core.SrcOf
|
||||
// reports it as a not-ok source so the console renders the honest not-configured state.
|
||||
var errUnconfigured = errors.New("billing warehouse not connected")
|
||||
|
||||
// defaultLimit caps the top-customers list; recentLimit caps the movement feed.
|
||||
const (
|
||||
defaultLimit = 20
|
||||
recentLimit = 20
|
||||
)
|
||||
|
||||
// ── response shapes (byte-identical to the operator contract in api.ts) ──────
|
||||
// These were formerly modeled on the commerce S2S client; they now live here (the
|
||||
// one consumer) since the read is a direct warehouse aggregate. Money is money.Cents
|
||||
// (int64 underlying → plain-integer JSON, unchanged on the wire).
|
||||
|
||||
// SaaSMetrics is the whole-business SaaS-operations aggregate.
|
||||
type SaaSMetrics struct {
|
||||
AsOf string `json:"asOf"`
|
||||
Currency string `json:"currency"`
|
||||
Window string `json:"window"`
|
||||
Revenue SaaSRevenue `json:"revenue"`
|
||||
Subs SaaSSubs `json:"subscriptions"`
|
||||
Usage SaaSUsage `json:"usage"`
|
||||
Customers []SaaSCustomer `json:"customers"`
|
||||
Orgs int `json:"orgs"`
|
||||
Gaps []string `json:"gaps"`
|
||||
}
|
||||
|
||||
// SaaSRevenue is the recurring-revenue headline (run-rate MRR/ARR + windowed movement).
|
||||
type SaaSRevenue struct {
|
||||
MRRCents money.Cents `json:"mrrCents"`
|
||||
ARRCents money.Cents `json:"arrCents"`
|
||||
ActiveSubscriptions int `json:"activeSubscriptions"`
|
||||
PayingCustomers int `json:"payingCustomers"`
|
||||
Trials int `json:"trials"`
|
||||
NewMRRCents money.Cents `json:"newMrrCents"`
|
||||
ChurnedMRRCents money.Cents `json:"churnedMrrCents"`
|
||||
NetNewMRRCents money.Cents `json:"netNewMrrCents"`
|
||||
ByCategory []SaaSCategory `json:"byCategory"`
|
||||
}
|
||||
|
||||
// SaaSCategory is one plan-category bucket of run-rate MRR (the plan mix).
|
||||
type SaaSCategory struct {
|
||||
Category string `json:"category"`
|
||||
MRRCents money.Cents `json:"mrrCents"`
|
||||
Subscriptions int `json:"subscriptions"`
|
||||
}
|
||||
|
||||
// SaaSSubs is the subscription-operations panel (per-plan mix, trials, new/canceled,
|
||||
// recent movements).
|
||||
type SaaSSubs struct {
|
||||
ByPlan []SaaSPlan `json:"byPlan"`
|
||||
TrialsActive int `json:"trialsActive"`
|
||||
New int `json:"new"`
|
||||
Canceled int `json:"canceled"`
|
||||
Recent []SaaSEvent `json:"recent"`
|
||||
}
|
||||
|
||||
// SaaSPlan is one plan's active/trialing counts, seats, and MRR contribution.
|
||||
type SaaSPlan struct {
|
||||
Plan string `json:"plan"`
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
Active int `json:"active"`
|
||||
Trialing int `json:"trialing"`
|
||||
Seats int `json:"seats"`
|
||||
MRRCents money.Cents `json:"mrrCents"`
|
||||
}
|
||||
|
||||
// SaaSEvent is one recent subscription movement ("created" or "canceled").
|
||||
type SaaSEvent struct {
|
||||
At string `json:"at"`
|
||||
Org string `json:"org"`
|
||||
Type string `json:"type"`
|
||||
Plan string `json:"plan"`
|
||||
Category string `json:"category"`
|
||||
MRRDeltaCents money.Cents `json:"mrrDeltaCents"`
|
||||
}
|
||||
|
||||
// SaaSUsage is the metered / pay-as-you-go revenue headline for the window.
|
||||
type SaaSUsage struct {
|
||||
Instrumented bool `json:"instrumented"`
|
||||
WindowUsageCents money.Cents `json:"windowUsageCents"`
|
||||
Requests int64 `json:"requests"`
|
||||
}
|
||||
|
||||
// SaaSCustomer is one top customer by MRR + windowed usage.
|
||||
type SaaSCustomer struct {
|
||||
Org string `json:"org"`
|
||||
Plan string `json:"plan"`
|
||||
Category string `json:"category"`
|
||||
Status string `json:"status"`
|
||||
MRRCents money.Cents `json:"mrrCents"`
|
||||
UsageCents money.Cents `json:"usageCents"`
|
||||
Seats int `json:"seats"`
|
||||
Since string `json:"since,omitempty"`
|
||||
}
|
||||
|
||||
// MetricsData is the GET /v1/admin/metrics payload: the SaaS snapshot, flat, plus the
|
||||
// admin read time and the upstream freshness strip every god-view carries.
|
||||
type MetricsData struct {
|
||||
SaaSMetrics
|
||||
GeneratedAt string `json:"generatedAt"`
|
||||
Sources []core.SourceStatus `json:"sources"`
|
||||
}
|
||||
|
||||
// Metrics answers GET /v1/admin/metrics by aggregating commerce.events directly
|
||||
// (fleet-wide, no per-org fan-out). SuperAdmin only.
|
||||
//
|
||||
// GET /v1/admin/metrics?window=30d&limit=20
|
||||
func Metrics(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
ctx := c.Context()
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
window := normalizeWindow(c.Query("window"))
|
||||
limit := parseLimit(c.Query("limit"))
|
||||
|
||||
// Honest not-configured snapshot when the warehouse/collector table is absent.
|
||||
if !core.BillingEventsReady(ctx) {
|
||||
return core.OK(c, empty(now, window, core.SrcOf("billing-warehouse", errUnconfigured, 0, now)))
|
||||
}
|
||||
|
||||
sinceTS := core.CHTimeLit(core.WarehouseSince(window))
|
||||
m := SaaSMetrics{AsOf: now, Currency: "usd", Window: window}
|
||||
|
||||
// Revenue headline + plan-mix (run-rate, latest-event-wins over active subs).
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, headlineSQL()); err == nil {
|
||||
fillHeadline(&m.Revenue, core.CHFirstRow(rows))
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, byCategorySQL()); err == nil {
|
||||
m.Revenue.ByCategory = byCategoryFromRows(rows)
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, byPlanSQL()); err == nil {
|
||||
m.Subs.ByPlan = byPlanFromRows(rows)
|
||||
}
|
||||
m.Subs.TrialsActive = m.Revenue.Trials
|
||||
|
||||
// Windowed movement: new vs churned MRR + counts.
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, movementSQL(), sinceTS); err == nil {
|
||||
r := core.CHFirstRow(rows)
|
||||
m.Revenue.NewMRRCents = money.Cents(core.CHInt64(r["new_mrr"]))
|
||||
m.Revenue.ChurnedMRRCents = money.Cents(core.CHInt64(r["churned_mrr"]))
|
||||
m.Revenue.NetNewMRRCents = m.Revenue.NewMRRCents - m.Revenue.ChurnedMRRCents
|
||||
m.Subs.New = int(core.CHInt64(r["new_count"]))
|
||||
m.Subs.Canceled = int(core.CHInt64(r["canceled_count"]))
|
||||
}
|
||||
// Recent movements feed.
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, recentSQL(), sinceTS); err == nil {
|
||||
m.Subs.Recent = recentFromRows(rows)
|
||||
}
|
||||
// Metered usage headline (window).
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, usageSQL(), sinceTS); err == nil {
|
||||
r := core.CHFirstRow(rows)
|
||||
m.Usage.Requests = core.CHInt64(r["requests"])
|
||||
m.Usage.WindowUsageCents = money.Cents(core.CHInt64(r["usage_cents"]))
|
||||
m.Usage.Instrumented = m.Usage.Requests > 0
|
||||
}
|
||||
// Fleet org count (any billing activity).
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, orgCountSQL()); err == nil {
|
||||
m.Orgs = int(core.CHInt64(core.CHFirstRow(rows)["orgs"]))
|
||||
}
|
||||
// Top customers by MRR + windowed usage (two reads merged, no fan-out).
|
||||
m.Customers = topCustomers(ctx, sinceTS, limit)
|
||||
|
||||
m.Gaps = gapsFor(m)
|
||||
return core.OK(c, MetricsData{
|
||||
SaaSMetrics: normalize(m),
|
||||
GeneratedAt: now,
|
||||
Sources: []core.SourceStatus{core.SrcOf("billing-warehouse", nil, m.Orgs, now)},
|
||||
})
|
||||
}
|
||||
|
||||
// ── active-subscription state subquery (latest-event-wins, non-canceled) ─────
|
||||
|
||||
// activeSubs is the fleet's current subscription state: one row per subscription,
|
||||
// its LATEST lifecycle values (argMax by timestamp), keeping only non-canceled
|
||||
// subs (HAVING on the latest event). Static SQL over a closed event-name set — no
|
||||
// user input interpolated. Reused by every run-rate panel so the definition of
|
||||
// "active" lives in ONE place.
|
||||
func activeSubs() string {
|
||||
return "(SELECT " +
|
||||
"argMax(organization_id, timestamp) AS org, " +
|
||||
"argMax(JSONExtractString(properties, 'plan'), timestamp) AS plan, " +
|
||||
"argMax(JSONExtractString(properties, 'plan_name'), timestamp) AS plan_name, " +
|
||||
"argMax(JSONExtractString(properties, 'category'), timestamp) AS category, " +
|
||||
"argMax(JSONExtractString(properties, 'status'), timestamp) AS status, " +
|
||||
"argMax(JSONExtractInt(properties, 'mrr_cents'), timestamp) AS mrr_cents, " +
|
||||
"argMax(JSONExtractInt(properties, 'seats'), timestamp) AS seats, " +
|
||||
"min(timestamp) AS first_ts " +
|
||||
"FROM " + core.BillingEventsTable + " " +
|
||||
"WHERE event IN (" + core.SQLInList(core.SubscriptionEvents) + ") " +
|
||||
"AND JSONExtractString(properties, 'subscription_id') != '' " +
|
||||
"GROUP BY JSONExtractString(properties, 'subscription_id') " +
|
||||
"HAVING argMax(event, timestamp) != '" + core.EvSubscriptionCanceled + "')"
|
||||
}
|
||||
|
||||
// ── pure SQL builders (static SQL + at most one positional time bound) ────────
|
||||
|
||||
// headlineSQL: run-rate MRR (paying, non-trial), active-sub count, paying-customer
|
||||
// count, and trial count — one pass over the active-subs state.
|
||||
func headlineSQL() string {
|
||||
return "SELECT sumIf(mrr_cents, status != 'trialing') AS mrr, " +
|
||||
"count() AS active_subs, " +
|
||||
"uniqExactIf(org, status != 'trialing' AND mrr_cents > 0) AS paying, " +
|
||||
"countIf(status = 'trialing') AS trials FROM " + activeSubs()
|
||||
}
|
||||
|
||||
func byCategorySQL() string {
|
||||
return "SELECT category, sumIf(mrr_cents, status != 'trialing') AS mrr, count() AS subs " +
|
||||
"FROM " + activeSubs() + " GROUP BY category ORDER BY mrr DESC"
|
||||
}
|
||||
|
||||
func byPlanSQL() string {
|
||||
return "SELECT plan, any(plan_name) AS name, any(category) AS category, " +
|
||||
"countIf(status = 'active') AS active, countIf(status = 'trialing') AS trialing, " +
|
||||
"sum(seats) AS seats, sumIf(mrr_cents, status != 'trialing') AS mrr " +
|
||||
"FROM " + activeSubs() + " GROUP BY plan ORDER BY mrr DESC"
|
||||
}
|
||||
|
||||
// movementSQL: windowed new vs churned MRR + counts (one positional since bound).
|
||||
func movementSQL() string {
|
||||
return "SELECT " +
|
||||
"sumIf(JSONExtractInt(properties, 'mrr_cents'), event = '" + core.EvSubscriptionCreated + "') AS new_mrr, " +
|
||||
"countIf(event = '" + core.EvSubscriptionCreated + "') AS new_count, " +
|
||||
"sumIf(JSONExtractInt(properties, 'mrr_cents'), event = '" + core.EvSubscriptionCanceled + "') AS churned_mrr, " +
|
||||
"countIf(event = '" + core.EvSubscriptionCanceled + "') AS canceled_count " +
|
||||
"FROM " + core.BillingEventsTable + " " +
|
||||
"WHERE event IN ('" + core.EvSubscriptionCreated + "','" + core.EvSubscriptionCanceled + "') AND timestamp >= ?"
|
||||
}
|
||||
|
||||
func recentSQL() string {
|
||||
return "SELECT timestamp AS at, organization_id AS org, event AS type, " +
|
||||
"JSONExtractString(properties, 'plan_name') AS plan, " +
|
||||
"JSONExtractString(properties, 'category') AS category, " +
|
||||
"JSONExtractInt(properties, 'mrr_cents') AS mrr_delta " +
|
||||
"FROM " + core.BillingEventsTable + " " +
|
||||
"WHERE event IN ('" + core.EvSubscriptionCreated + "','" + core.EvSubscriptionCanceled + "') AND timestamp >= ? " +
|
||||
"ORDER BY at DESC LIMIT " + strconv.Itoa(recentLimit)
|
||||
}
|
||||
|
||||
func usageSQL() string {
|
||||
return "SELECT count() AS requests, sum(JSONExtractInt(properties, 'amount_cents')) AS usage_cents " +
|
||||
"FROM " + core.BillingEventsTable + " WHERE event = '" + core.EvAPIUsageDebit + "' AND timestamp >= ?"
|
||||
}
|
||||
|
||||
func orgCountSQL() string {
|
||||
return "SELECT uniqExact(organization_id) AS orgs FROM " + core.BillingEventsTable +
|
||||
" WHERE event IN (" + core.SQLInList(allBillingEvents()) + ")"
|
||||
}
|
||||
|
||||
func perOrgSubsSQL() string {
|
||||
return "SELECT org, sumIf(mrr_cents, status != 'trialing') AS mrr, sum(seats) AS seats, " +
|
||||
"argMax(plan_name, mrr_cents) AS plan, argMax(category, mrr_cents) AS category, " +
|
||||
"argMax(status, mrr_cents) AS status, min(first_ts) AS since " +
|
||||
"FROM " + activeSubs() + " GROUP BY org"
|
||||
}
|
||||
|
||||
func perOrgUsageSQL() string {
|
||||
return "SELECT organization_id AS org, sum(JSONExtractInt(properties, 'amount_cents')) AS usage_cents " +
|
||||
"FROM " + core.BillingEventsTable + " WHERE event = '" + core.EvAPIUsageDebit + "' AND timestamp >= ? GROUP BY org"
|
||||
}
|
||||
|
||||
// allBillingEvents is the union of every customer-activity event the fleet counts
|
||||
// an org as "active" on (subscription + invoice + usage).
|
||||
func allBillingEvents() []string {
|
||||
out := append([]string{}, core.SubscriptionEvents...)
|
||||
out = append(out, core.InvoiceEvents...)
|
||||
return append(out, core.EvAPIUsageDebit)
|
||||
}
|
||||
|
||||
// ── pure row parsers ─────────────────────────────────────────────────────────
|
||||
|
||||
func fillHeadline(r *SaaSRevenue, row map[string]any) {
|
||||
r.MRRCents = money.Cents(core.CHInt64(row["mrr"]))
|
||||
r.ARRCents = r.MRRCents * 12
|
||||
r.ActiveSubscriptions = int(core.CHInt64(row["active_subs"]))
|
||||
r.PayingCustomers = int(core.CHInt64(row["paying"]))
|
||||
r.Trials = int(core.CHInt64(row["trials"]))
|
||||
}
|
||||
|
||||
func byCategoryFromRows(rows []map[string]any) []SaaSCategory {
|
||||
out := make([]SaaSCategory, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, SaaSCategory{
|
||||
Category: core.CHStr(r["category"]),
|
||||
MRRCents: money.Cents(core.CHInt64(r["mrr"])),
|
||||
Subscriptions: int(core.CHInt64(r["subs"])),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func byPlanFromRows(rows []map[string]any) []SaaSPlan {
|
||||
out := make([]SaaSPlan, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, SaaSPlan{
|
||||
Plan: core.CHStr(r["plan"]),
|
||||
Name: core.CHStr(r["name"]),
|
||||
Category: core.CHStr(r["category"]),
|
||||
Active: int(core.CHInt64(r["active"])),
|
||||
Trialing: int(core.CHInt64(r["trialing"])),
|
||||
Seats: int(core.CHInt64(r["seats"])),
|
||||
MRRCents: money.Cents(core.CHInt64(r["mrr"])),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func recentFromRows(rows []map[string]any) []SaaSEvent {
|
||||
out := make([]SaaSEvent, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
typ := "created"
|
||||
delta := money.Cents(core.CHInt64(r["mrr_delta"]))
|
||||
if core.CHStr(r["type"]) == core.EvSubscriptionCanceled {
|
||||
typ = "canceled"
|
||||
delta = -delta // churn reduces run-rate MRR
|
||||
}
|
||||
out = append(out, SaaSEvent{
|
||||
At: core.CHTime(r["at"]),
|
||||
Org: core.CHStr(r["org"]),
|
||||
Type: typ,
|
||||
Plan: core.CHStr(r["plan"]),
|
||||
Category: core.CHStr(r["category"]),
|
||||
MRRDeltaCents: delta,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// topCustomers folds per-org subscription state + per-org windowed usage into the
|
||||
// top-N customers by MRR (then usage). Two reads merged in Go by org — a union, so
|
||||
// a pay-as-you-go org with usage but no subscription still appears.
|
||||
func topCustomers(ctx context.Context, sinceTS string, limit int) []SaaSCustomer {
|
||||
byOrg := map[string]*SaaSCustomer{}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, perOrgSubsSQL()); err == nil {
|
||||
for _, r := range rows {
|
||||
org := core.CHStr(r["org"])
|
||||
if org == "" {
|
||||
continue
|
||||
}
|
||||
byOrg[org] = &SaaSCustomer{
|
||||
Org: org,
|
||||
Plan: core.CHStr(r["plan"]),
|
||||
Category: core.CHStr(r["category"]),
|
||||
Status: core.CHStr(r["status"]),
|
||||
MRRCents: money.Cents(core.CHInt64(r["mrr"])),
|
||||
Seats: int(core.CHInt64(r["seats"])),
|
||||
Since: core.CHTime(r["since"]),
|
||||
}
|
||||
}
|
||||
}
|
||||
if rows, err := aiobject.DatastoreQuery(ctx, perOrgUsageSQL(), sinceTS); err == nil {
|
||||
for _, r := range rows {
|
||||
org := core.CHStr(r["org"])
|
||||
if org == "" {
|
||||
continue
|
||||
}
|
||||
usage := money.Cents(core.CHInt64(r["usage_cents"]))
|
||||
if cust, ok := byOrg[org]; ok {
|
||||
cust.UsageCents = usage
|
||||
continue
|
||||
}
|
||||
byOrg[org] = &SaaSCustomer{Org: org, Plan: "pay-as-you-go", Status: "active", UsageCents: usage}
|
||||
}
|
||||
}
|
||||
out := make([]SaaSCustomer, 0, len(byOrg))
|
||||
for _, c := range byOrg {
|
||||
out = append(out, *c)
|
||||
}
|
||||
sortCustomers(out)
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ── small pure helpers ───────────────────────────────────────────────────────
|
||||
|
||||
// sortCustomers ranks by MRR desc, ties broken by windowed usage desc.
|
||||
func sortCustomers(cs []SaaSCustomer) {
|
||||
sort.SliceStable(cs, func(i, j int) bool { return lessCustomer(cs[i], cs[j]) })
|
||||
}
|
||||
|
||||
func lessCustomer(a, b SaaSCustomer) bool {
|
||||
if a.MRRCents != b.MRRCents {
|
||||
return a.MRRCents > b.MRRCents
|
||||
}
|
||||
return a.UsageCents > b.UsageCents
|
||||
}
|
||||
|
||||
// gapsFor lists honest not-yet-observed signals so the console can badge a partial
|
||||
// snapshot without fabricating data.
|
||||
func gapsFor(m SaaSMetrics) []string {
|
||||
gaps := []string{}
|
||||
if !m.Usage.Instrumented {
|
||||
gaps = append(gaps, "api-usage debits not yet observed")
|
||||
}
|
||||
if m.Revenue.ActiveSubscriptions == 0 {
|
||||
gaps = append(gaps, "no active subscriptions observed")
|
||||
}
|
||||
return gaps
|
||||
}
|
||||
|
||||
// empty is the honest not-connected snapshot: real zeros + empty slices (never
|
||||
// null, never fabricated) plus the not-ok source.
|
||||
func empty(now, window string, src core.SourceStatus) MetricsData {
|
||||
return MetricsData{
|
||||
SaaSMetrics: normalize(SaaSMetrics{AsOf: now, Currency: "usd", Window: window}),
|
||||
GeneratedAt: now,
|
||||
Sources: []core.SourceStatus{src},
|
||||
}
|
||||
}
|
||||
|
||||
// normalize replaces nil slices with empty ones so the JSON is honest arrays (`[]`,
|
||||
// not null) and the console never has to guard a missing collection.
|
||||
func normalize(m SaaSMetrics) SaaSMetrics {
|
||||
if m.Revenue.ByCategory == nil {
|
||||
m.Revenue.ByCategory = []SaaSCategory{}
|
||||
}
|
||||
if m.Subs.ByPlan == nil {
|
||||
m.Subs.ByPlan = []SaaSPlan{}
|
||||
}
|
||||
if m.Subs.Recent == nil {
|
||||
m.Subs.Recent = []SaaSEvent{}
|
||||
}
|
||||
if m.Customers == nil {
|
||||
m.Customers = []SaaSCustomer{}
|
||||
}
|
||||
if m.Gaps == nil {
|
||||
m.Gaps = []string{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// normalizeWindow clamps ?window to the supported set (default 30d) — mirrors the
|
||||
// warehouse window grammar (core.WarehouseSince).
|
||||
func normalizeWindow(v string) string {
|
||||
switch strings.TrimSpace(v) {
|
||||
case "24h":
|
||||
return "24h"
|
||||
case "7d":
|
||||
return "7d"
|
||||
default:
|
||||
return "30d"
|
||||
}
|
||||
}
|
||||
|
||||
// parseLimit clamps the top-N cap to [1,200], defaulting to defaultLimit.
|
||||
func parseLimit(s string) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(s))
|
||||
if err != nil || n <= 0 {
|
||||
return defaultLimit
|
||||
}
|
||||
if n > 200 {
|
||||
return 200
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
)
|
||||
|
||||
// TestFillHeadline proves the run-rate headline coercion (driver ints) + the
|
||||
// ARR = 12×MRR derivation.
|
||||
func TestFillHeadline(t *testing.T) {
|
||||
var rev SaaSRevenue
|
||||
fillHeadline(&rev, map[string]any{
|
||||
"mrr": int64(4900), "active_subs": uint64(3), "paying": uint64(2), "trials": uint64(1),
|
||||
})
|
||||
if rev.MRRCents != 4900 || rev.ARRCents != 4900*12 {
|
||||
t.Fatalf("mrr/arr wrong: %+v", rev)
|
||||
}
|
||||
if rev.ActiveSubscriptions != 3 || rev.PayingCustomers != 2 || rev.Trials != 1 {
|
||||
t.Fatalf("counts wrong: %+v", rev)
|
||||
}
|
||||
}
|
||||
|
||||
func TestByCategoryAndPlanFromRows(t *testing.T) {
|
||||
cats := byCategoryFromRows([]map[string]any{
|
||||
{"category": "cloud", "mrr": int64(9800), "subs": uint64(2)},
|
||||
})
|
||||
if len(cats) != 1 || cats[0].Category != "cloud" || cats[0].MRRCents != 9800 || cats[0].Subscriptions != 2 {
|
||||
t.Fatalf("category row wrong: %+v", cats)
|
||||
}
|
||||
plans := byPlanFromRows([]map[string]any{
|
||||
{"plan": "pro", "name": "Pro", "category": "cloud", "active": uint64(2), "trialing": uint64(1), "seats": uint64(5), "mrr": int64(9800)},
|
||||
})
|
||||
if len(plans) != 1 {
|
||||
t.Fatalf("want 1 plan, got %d", len(plans))
|
||||
}
|
||||
p := plans[0]
|
||||
if p.Plan != "pro" || p.Name != "Pro" || p.Category != "cloud" || p.Active != 2 || p.Trialing != 1 || p.Seats != 5 || p.MRRCents != 9800 {
|
||||
t.Fatalf("plan row wrong: %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecentFromRows proves the movement feed maps event→type and NEGATES churn MRR.
|
||||
func TestRecentFromRows(t *testing.T) {
|
||||
rows := []map[string]any{
|
||||
{"at": "2026-07-10T00:00:00Z", "org": "acme", "type": core.EvSubscriptionCreated, "plan": "Pro", "category": "cloud", "mrr_delta": int64(4900)},
|
||||
{"at": "2026-07-09T00:00:00Z", "org": "beta", "type": core.EvSubscriptionCanceled, "plan": "Team", "category": "cloud", "mrr_delta": int64(3000)},
|
||||
}
|
||||
out := recentFromRows(rows)
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("want 2, got %d", len(out))
|
||||
}
|
||||
if out[0].Type != "created" || out[0].MRRDeltaCents != 4900 {
|
||||
t.Fatalf("created row wrong: %+v", out[0])
|
||||
}
|
||||
if out[1].Type != "canceled" || out[1].MRRDeltaCents != -3000 {
|
||||
t.Fatalf("canceled row must negate mrr: %+v", out[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortCustomers(t *testing.T) {
|
||||
cs := []SaaSCustomer{
|
||||
{Org: "a", MRRCents: 100, UsageCents: 0},
|
||||
{Org: "b", MRRCents: 500, UsageCents: 0},
|
||||
{Org: "c", MRRCents: 500, UsageCents: 999}, // ties on MRR → usage breaks
|
||||
}
|
||||
sortCustomers(cs)
|
||||
if cs[0].Org != "c" || cs[1].Org != "b" || cs[2].Org != "a" {
|
||||
t.Fatalf("order wrong: %s,%s,%s", cs[0].Org, cs[1].Org, cs[2].Org)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateQueriesNoPositionalArgs: the run-rate (state) queries are fully static.
|
||||
func TestStateQueriesNoPositionalArgs(t *testing.T) {
|
||||
for name, sql := range map[string]string{
|
||||
"headline": headlineSQL(), "byCategory": byCategorySQL(), "byPlan": byPlanSQL(),
|
||||
"orgCount": orgCountSQL(), "perOrgSubs": perOrgSubsSQL(),
|
||||
} {
|
||||
if !strings.Contains(sql, core.BillingEventsTable) {
|
||||
t.Fatalf("%s must read %s", name, core.BillingEventsTable)
|
||||
}
|
||||
if strings.Contains(sql, "?") {
|
||||
t.Fatalf("%s (run-rate) must take no positional args: %q", name, sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWindowedQueriesOnePositionalArg: the windowed queries bind exactly ONE time
|
||||
// arg (injection-safe — the since bound is never interpolated).
|
||||
func TestWindowedQueriesOnePositionalArg(t *testing.T) {
|
||||
for name, sql := range map[string]string{
|
||||
"movement": movementSQL(), "recent": recentSQL(), "usage": usageSQL(), "perOrgUsage": perOrgUsageSQL(),
|
||||
} {
|
||||
if n := strings.Count(sql, "?"); n != 1 {
|
||||
t.Fatalf("%s must bind exactly ONE positional time arg, got %d: %q", name, n, sql)
|
||||
}
|
||||
if !strings.Contains(sql, "timestamp >= ?") {
|
||||
t.Fatalf("%s time bound must be positional: %q", name, sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAndEmpty(t *testing.T) {
|
||||
m := normalize(SaaSMetrics{})
|
||||
if m.Revenue.ByCategory == nil || m.Subs.ByPlan == nil || m.Subs.Recent == nil || m.Customers == nil || m.Gaps == nil {
|
||||
t.Fatal("normalize must replace nil slices with empty (honest [] not null)")
|
||||
}
|
||||
e := empty("now", "30d", core.SrcOf("billing-warehouse", errUnconfigured, 0, "now"))
|
||||
if e.Currency != "usd" || e.Window != "30d" || len(e.Sources) != 1 || e.Sources[0].OK {
|
||||
t.Fatalf("empty snapshot wrong: %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeWindow(t *testing.T) {
|
||||
for in, want := range map[string]string{"24h": "24h", "7d": "7d", "30d": "30d", "": "30d", "90d": "30d"} {
|
||||
if got := normalizeWindow(in); got != want {
|
||||
t.Fatalf("normalizeWindow(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// Routes registers the SaaS-metrics god-view (SuperAdmin only, cross-tenant business
|
||||
// aggregate).
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/metrics", core.Guard(s, Metrics))
|
||||
}
|
||||
@@ -22,7 +22,8 @@ import (
|
||||
|
||||
// Routes registers the fleet revenue board (SuperAdmin only, cross-tenant profitability).
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
app.Get("/v1/admin/revenue", core.Guard(s, Revenue))
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/revenue", core.Guard(s, Revenue))
|
||||
}
|
||||
|
||||
// RevenueCustomer is one row of the per-customer revenue table.
|
||||
|
||||
+15
-15
@@ -1,16 +1,16 @@
|
||||
package admin
|
||||
|
||||
// The /v1/admin/services board — the launch-control LENS on the ONE flag engine, twin
|
||||
// The /v1/admin/services board — the launch-control LENS over the waitlist gate, twin
|
||||
// of /v1/admin/flags. Every hosted service (studio/chat/console/app/api/team + runtime
|
||||
// onboards) with its LIVE waitlist mode — the switch waitlist.<svc> evaluated through
|
||||
// clients/flags. This is the "remove the waitlist one service at a time" toggle.
|
||||
// SuperAdmin only (core.Guard), like every platform /v1/admin/*.
|
||||
// onboards) with its LIVE waitlist mode — the switch waitlist.<svc>, evaluated through
|
||||
// clients/admission (which composes the flag engine one-way). This is the "remove the
|
||||
// waitlist one service at a time" toggle. SuperAdmin only (core.Guard), like every
|
||||
// platform /v1/admin/*.
|
||||
//
|
||||
// Formerly clients/featuregate owned its OWN SQLite mode store + this control plane;
|
||||
// both folded onto the flag engine so the platform has ONE decision plane. featuregate
|
||||
// now owns only the native Enforce middleware — a consumer of flags.WaitlistModeForHost.
|
||||
// Per-user approval (the second, orthogonal axis) stays IAM's, reached via the existing
|
||||
// admin IAM proxy — not re-served here.
|
||||
// The registry + mode decide + these admin control funcs live in clients/admission,
|
||||
// the complete launch-gate feature; flags is the pure engine underneath. Per-user
|
||||
// approval (the second, orthogonal axis) stays IAM's, reached via the existing admin IAM
|
||||
// proxy — not re-served here.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -19,13 +19,13 @@ import (
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/hanzoai/cloud/clients/flags"
|
||||
"github.com/hanzoai/cloud/clients/admission"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// services answers GET /v1/admin/services — the launch board (every service + live mode).
|
||||
func services(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
rows, err := flags.ListWaitlistServices(c.Context())
|
||||
rows, err := admission.ListWaitlistServices(c.Context())
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "list services: %v", err)
|
||||
}
|
||||
@@ -35,14 +35,14 @@ func services(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
// upsertService answers POST /v1/admin/services — onboard or edit a hosted service so a
|
||||
// new host is governed WITHOUT a redeploy. A re-register PRESERVES the live switch.
|
||||
func upsertService(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
var in flags.ServiceInput
|
||||
var in admission.ServiceInput
|
||||
if err := c.Bind(&in); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(in.Service) == "" {
|
||||
return zip.ErrBadRequest("service slug is required")
|
||||
}
|
||||
view, err := flags.UpsertWaitlistService(c.Context(), in, c.UserEmail())
|
||||
view, err := admission.UpsertWaitlistService(c.Context(), in, c.UserEmail())
|
||||
if err != nil {
|
||||
return zip.ErrBadRequest(err.Error())
|
||||
}
|
||||
@@ -62,9 +62,9 @@ func setServiceMode(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
view, err := flags.SetWaitlistMode(c.Context(), service, body.WaitlistMode, c.UserEmail())
|
||||
view, err := admission.SetWaitlistMode(c.Context(), service, body.WaitlistMode, c.UserEmail())
|
||||
if err != nil {
|
||||
if errors.Is(err, flags.ErrServiceNotFound) {
|
||||
if errors.Is(err, admission.ErrServiceNotFound) {
|
||||
return zip.ErrNotFound("service not found: " + service)
|
||||
}
|
||||
return zip.Errorf(http.StatusInternalServerError, "set mode: %v", err)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package subscriptions
|
||||
|
||||
import (
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// Routes registers the fleet subscription view (SuperAdmin only, cross-tenant).
|
||||
func Routes(app *zip.App, s *cloud.Service[core.State]) {
|
||||
g := app.Group("/v1/admin")
|
||||
g.Get("/subscriptions", core.Guard(s, Subscriptions))
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Package subscriptions is the fleet SUBSCRIPTION view (/v1/admin/subscriptions) —
|
||||
// every tenant's plan subscription: customer/org, plan, status, monthly-normalized
|
||||
// MRR, and the current-period start/renews. SuperAdmin only (core.Guard).
|
||||
//
|
||||
// It reads the ONE shared warehouse (commerce.events) — the table the commerce
|
||||
// analytics collector lands every subscription-lifecycle event in — over the SAME
|
||||
// client (aiobject.DatastoreQuery) the o11y/compute lenses use, with ZERO per-org
|
||||
// fan-out: one GROUP BY resolves each subscription's LATEST lifecycle state
|
||||
// (argMax by timestamp), so the whole fleet is one query, not N per-org commerce
|
||||
// reads. Honest by construction: no datastore connected or the collector's table
|
||||
// not provisioned yet → the real empty list, never a fabricated tenant. The MRR is
|
||||
// the monthly-normalized figure the emitter already computed (cents). Optional
|
||||
// ?org= scopes to one tenant, ?status= filters the LATEST status, ?limit= caps.
|
||||
package subscriptions
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// defaultLimit caps the fleet subscription list when the caller sends none.
|
||||
const defaultLimit = 500
|
||||
|
||||
// SubscriptionRow is one row of GET /v1/admin/subscriptions — a tenant's subscription at
|
||||
// a glance, tagged with its owning org. MRR is USD cents; timestamps are RFC3339 strings.
|
||||
type SubscriptionRow struct {
|
||||
ID string `json:"id"`
|
||||
Org string `json:"org"`
|
||||
Display string `json:"display"`
|
||||
User string `json:"user"`
|
||||
Plan string `json:"plan"`
|
||||
Status string `json:"status"`
|
||||
MRRCents int64 `json:"mrrCents"`
|
||||
Started string `json:"started"`
|
||||
Renews string `json:"renews"`
|
||||
}
|
||||
|
||||
// Subscriptions answers GET /v1/admin/subscriptions.
|
||||
//
|
||||
// GET /v1/admin/subscriptions?org=&status=&limit=
|
||||
func Subscriptions(s *cloud.Service[core.State], c *zip.Ctx) error {
|
||||
ctx := c.Context()
|
||||
status := strings.ToLower(strings.TrimSpace(c.Query("status")))
|
||||
wantOrg := strings.TrimSpace(c.Query("org"))
|
||||
limit := parseLimit(c.Query("limit"))
|
||||
|
||||
// Honest-empty when the warehouse is not connected or the collector's events
|
||||
// table is not provisioned yet (the emitter is still being wired).
|
||||
if !core.BillingEventsReady(ctx) {
|
||||
return core.OKList(c, []SubscriptionRow{}, 0)
|
||||
}
|
||||
|
||||
rows, err := aiobject.DatastoreQuery(ctx, subscriptionsSQL())
|
||||
if err != nil {
|
||||
return core.Fail(c, "subscriptions query: "+err.Error())
|
||||
}
|
||||
all := subscriptionRowsFromRows(rows)
|
||||
|
||||
// Filter (latest status / org) then sort highest-MRR first, cap to limit.
|
||||
out := make([]SubscriptionRow, 0, len(all))
|
||||
for _, r := range all {
|
||||
if wantOrg != "" && r.Org != wantOrg {
|
||||
continue
|
||||
}
|
||||
if status != "" && strings.ToLower(r.Status) != status {
|
||||
continue
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].MRRCents != out[j].MRRCents {
|
||||
return out[i].MRRCents > out[j].MRRCents
|
||||
}
|
||||
return out[i].Started > out[j].Started
|
||||
})
|
||||
total := len(out)
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return core.OKList(c, out, total)
|
||||
}
|
||||
|
||||
// subscriptionsSQL resolves each subscription's LATEST lifecycle state from
|
||||
// commerce.events (argMax by timestamp). Static SQL over a closed event-name set
|
||||
// (SQLInList of server constants) — no user input is interpolated, so it is
|
||||
// injection-safe. The emitted properties carry the plan/status/mrr/period fields.
|
||||
func subscriptionsSQL() string {
|
||||
return "SELECT JSONExtractString(properties, 'subscription_id') AS id, " +
|
||||
"argMax(organization_id, timestamp) AS org, " +
|
||||
"argMax(distinct_id, timestamp) AS user, " +
|
||||
"argMax(JSONExtractString(properties, 'plan_name'), timestamp) AS plan, " +
|
||||
"argMax(JSONExtractString(properties, 'status'), timestamp) AS status, " +
|
||||
"argMax(JSONExtractInt(properties, 'mrr_cents'), timestamp) AS mrr_cents, " +
|
||||
"argMax(event, timestamp) AS last_event, " +
|
||||
"min(timestamp) AS started, " +
|
||||
"argMax(JSONExtractString(properties, 'period_end'), timestamp) AS renews " +
|
||||
"FROM " + core.BillingEventsTable + " " +
|
||||
"WHERE event IN (" + core.SQLInList(core.SubscriptionEvents) + ") " +
|
||||
"AND JSONExtractString(properties, 'subscription_id') != '' " +
|
||||
"GROUP BY id"
|
||||
}
|
||||
|
||||
// subscriptionRowsFromRows maps the datastore rows onto []SubscriptionRow (pure).
|
||||
// Display is the org slug — the warehouse holds no friendly name and admin does
|
||||
// no per-org IAM fan-out here (honest, not fabricated). The final status folds
|
||||
// the lifecycle: a subscription whose LATEST event is a cancel reads "canceled"
|
||||
// regardless of the last-emitted status snapshot.
|
||||
func subscriptionRowsFromRows(rows []map[string]any) []SubscriptionRow {
|
||||
out := make([]SubscriptionRow, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
org := core.CHStr(r["org"])
|
||||
out = append(out, SubscriptionRow{
|
||||
ID: core.CHStr(r["id"]),
|
||||
Org: org,
|
||||
Display: org,
|
||||
User: core.CHStr(r["user"]),
|
||||
Plan: core.CHStr(r["plan"]),
|
||||
Status: foldStatus(core.CHStr(r["last_event"]), core.CHStr(r["status"])),
|
||||
MRRCents: core.CHInt64(r["mrr_cents"]),
|
||||
Started: core.CHTime(r["started"]),
|
||||
Renews: core.CHStr(r["renews"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// foldStatus resolves the effective status: a subscription whose latest event is
|
||||
// a cancel is "canceled"; otherwise the last-emitted status snapshot (falling
|
||||
// back to "active" when the emitter sent none).
|
||||
func foldStatus(lastEvent, snapshot string) string {
|
||||
if lastEvent == core.EvSubscriptionCanceled {
|
||||
return "canceled"
|
||||
}
|
||||
if s := strings.TrimSpace(snapshot); s != "" {
|
||||
return s
|
||||
}
|
||||
return "active"
|
||||
}
|
||||
|
||||
// parseLimit clamps the fleet-list cap to [1,5000], defaulting to defaultLimit.
|
||||
func parseLimit(s string) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(s))
|
||||
if err != nil || n <= 0 {
|
||||
return defaultLimit
|
||||
}
|
||||
if n > 5000 {
|
||||
return 5000
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package subscriptions
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/admin/core"
|
||||
)
|
||||
|
||||
// TestSubscriptionRowsFromRows proves the warehouse-row → SubscriptionRow mapping
|
||||
// (the JSON-shape contract) coerces the datastore driver's native types and folds
|
||||
// the lifecycle status; display honestly mirrors the org slug (no fan-out).
|
||||
func TestSubscriptionRowsFromRows(t *testing.T) {
|
||||
started := time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC)
|
||||
rows := []map[string]any{
|
||||
{ // active (mrr as driver int64), latest event renewed
|
||||
"id": "sub_1", "org": "acme", "user": "hanzo/alice",
|
||||
"plan": "Pro", "status": "active", "mrr_cents": int64(4900),
|
||||
"last_event": core.EvSubscriptionRenewed, "started": started,
|
||||
"renews": "2026-08-01T00:00:00Z",
|
||||
},
|
||||
{ // canceled wins over a stale "active" snapshot
|
||||
"id": "sub_2", "org": "beta", "user": "hanzo/bob",
|
||||
"plan": "Team", "status": "active", "mrr_cents": uint64(0),
|
||||
"last_event": core.EvSubscriptionCanceled, "started": started,
|
||||
"renews": "",
|
||||
},
|
||||
}
|
||||
out := subscriptionRowsFromRows(rows)
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("got %d rows, want 2", len(out))
|
||||
}
|
||||
r0 := out[0]
|
||||
if r0.ID != "sub_1" || r0.Org != "acme" || r0.Display != "acme" || r0.User != "hanzo/alice" {
|
||||
t.Fatalf("row0 identity wrong: %+v", r0)
|
||||
}
|
||||
if r0.Plan != "Pro" || r0.Status != "active" || r0.MRRCents != 4900 {
|
||||
t.Fatalf("row0 plan/status/mrr wrong: %+v", r0)
|
||||
}
|
||||
if r0.Started != "2026-07-01T12:00:00Z" {
|
||||
t.Fatalf("row0 started = %q", r0.Started)
|
||||
}
|
||||
if r0.Renews != "2026-08-01T00:00:00Z" {
|
||||
t.Fatalf("row0 renews = %q", r0.Renews)
|
||||
}
|
||||
if out[1].Status != "canceled" {
|
||||
t.Fatalf("row1 status = %q, want canceled (latest-event folds)", out[1].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldStatus(t *testing.T) {
|
||||
if got := foldStatus(core.EvSubscriptionCanceled, "active"); got != "canceled" {
|
||||
t.Fatalf("cancel fold = %q", got)
|
||||
}
|
||||
if got := foldStatus(core.EvSubscriptionRenewed, "trialing"); got != "trialing" {
|
||||
t.Fatalf("snapshot passthrough = %q", got)
|
||||
}
|
||||
if got := foldStatus(core.EvSubscriptionCreated, ""); got != "active" {
|
||||
t.Fatalf("empty-snapshot default = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubscriptionsSQLInjectionSafe asserts the query is fully static over the
|
||||
// closed event-name set — the warehouse table, no user-derived interpolation.
|
||||
func TestSubscriptionsSQLInjectionSafe(t *testing.T) {
|
||||
sql := subscriptionsSQL()
|
||||
if !strings.Contains(sql, core.BillingEventsTable) {
|
||||
t.Fatalf("query must read %s: %q", core.BillingEventsTable, sql)
|
||||
}
|
||||
for _, ev := range core.SubscriptionEvents {
|
||||
if !strings.Contains(sql, "'"+ev+"'") {
|
||||
t.Fatalf("query missing event %q", ev)
|
||||
}
|
||||
}
|
||||
if strings.Contains(sql, "?") {
|
||||
t.Fatalf("subscriptions state query takes no positional args: %q", sql)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLimitBounds(t *testing.T) {
|
||||
if parseLimit("") != defaultLimit || parseLimit("0") != defaultLimit || parseLimit("x") != defaultLimit {
|
||||
t.Fatal("bad/empty limit must default")
|
||||
}
|
||||
if parseLimit("10") != 10 {
|
||||
t.Fatal("valid limit must pass through")
|
||||
}
|
||||
if parseLimit("999999") != 5000 {
|
||||
t.Fatal("limit must clamp to 5000")
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package featuregate
|
||||
package admission
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
// approval is FAIL-OPEN: a user is approved unless properties.approvalStatus is
|
||||
// EXACTLY "pending" (absent / "approved" / "rejected" all read approved via
|
||||
// IsApproved). Only "pending" holds a user on the waitlist. Keeping the literal
|
||||
// here (not importing IAM) keeps featuregate self-contained.
|
||||
// here (not importing IAM) keeps admission self-contained.
|
||||
const approvalStatusPending = "pending"
|
||||
|
||||
// approvedHeader is the FORWARD-PERFECT path: once IAM carries approvalStatus in
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
package featuregate
|
||||
package admission
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -12,16 +12,24 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package featuregate is the launch-control ENFORCEMENT for Hanzo's hosted services:
|
||||
// the native middleware (Enforce) + the per-user approval predicate (Approvals, reused
|
||||
// from IAM). It is a CONSUMER of the ONE policy engine — the per-service waitlist MODE
|
||||
// and the host→service registry live in clients/flags (a service's mode IS the
|
||||
// switch waitlist.<svc>, evaluated through the native engine); the admin board is the
|
||||
// /v1/admin/services lens and the guard's runtime mode read is /v1/featuregate/mode,
|
||||
// both served there. This package owns only enforcement, decomplected into two axes:
|
||||
// Package admission is the launch-control GATE for Hanzo's hosted services — the
|
||||
// COMPLETE waitlist feature, COMPOSING the ONE flag engine (clients/flags) one-way. It
|
||||
// owns:
|
||||
//
|
||||
// - PER-SERVICE waitlist mode on|off — the flags switch waitlist.<svc>,
|
||||
// resolved for a request host via flags.WaitlistModeForHost (the decide).
|
||||
// - the host→service registry (registry.go) + the brand seed (waitlist.go),
|
||||
// - the per-service MODE decide WaitlistModeForHost — a service's mode IS the switch
|
||||
// waitlist.<svc>, evaluated through the flag engine (flags.Bool),
|
||||
// - the admin control funcs (List/Set/Upsert) the /v1/admin/services board calls,
|
||||
// - the guard's public mode read /v1/flags/waitlist, Mount,
|
||||
// - the native enforcement middleware (Enforce, this file),
|
||||
// - the per-user approval predicate (Approvals, reused from IAM — approval.go).
|
||||
//
|
||||
// flags NEVER imports admission; admission imports flags. The engine is the pure
|
||||
// (Principal, context) -> verdict primitive; this package is its first composed tenant.
|
||||
// Enforcement is decomplected into two orthogonal axes:
|
||||
//
|
||||
// - PER-SERVICE waitlist mode on|off — the switch waitlist.<svc>, resolved for a
|
||||
// request host via WaitlistModeForHost (the decide, waitlist.go).
|
||||
// - PER-USER approvalStatus pending|approved — owned by IAM (approval.go), REUSED.
|
||||
//
|
||||
// THE RULE, applied at ONE native enforcement point (Enforce):
|
||||
@@ -29,14 +37,13 @@
|
||||
// if waitlistMode[host] AND NOT user.approved → bounce to the waitlist
|
||||
// if approved OR mode=off → allow
|
||||
// unauthenticated → login first
|
||||
package featuregate
|
||||
package admission
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/flags"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
@@ -59,13 +66,13 @@ import (
|
||||
// INTEGRATION POINT — wire in serve.go RIGHT AFTER SanitizeIdentity:
|
||||
//
|
||||
// app.Use(IdentityMiddleware(cfg)) // establishes the validated principal
|
||||
// app.Use(featuregate.Enforce(featuregate.EnforceConfig{ WaitlistURL: … })) // ← here
|
||||
// app.Use(admission.Enforce(admission.EnforceConfig{ WaitlistURL: … })) // ← here
|
||||
//
|
||||
// It reads the sanitized X-User-Id / X-User-IsAdmin / X-User-Approved that
|
||||
// IdentityMiddleware minted, so it MUST run after it and (like BillingGate) before
|
||||
// the subsystem handlers. It is deliberately NOT wired here — the unified-binary
|
||||
// agent owns serve.go's boot chain; this package exposes Enforce so the one-line
|
||||
// app.Use lands without a merge collision. The decide (flags.WaitlistModeForHost) is
|
||||
// app.Use lands without a merge collision. The decide (WaitlistModeForHost) is
|
||||
// resolved PER REQUEST and fail-opens until the flags engine has mounted, so Enforce
|
||||
// can be constructed before Mount runs.
|
||||
//
|
||||
@@ -102,7 +109,7 @@ type EnforceConfig struct {
|
||||
ExemptPrefixes []string
|
||||
|
||||
// Gate is THE decide: it resolves whether a request host is in waitlist mode,
|
||||
// via the ONE policy engine. When nil it is flags.WaitlistModeForHost —
|
||||
// via the ONE policy engine. When nil it is WaitlistModeForHost —
|
||||
// host→service→waitlist.<svc>. Injected only in tests. Fail-open by contract:
|
||||
// known=false (unmounted / registry error / un-governed host) → not gated.
|
||||
Gate func(ctx context.Context, host string) (mode bool, service string, known bool)
|
||||
@@ -112,9 +119,9 @@ type EnforceConfig struct {
|
||||
// health, the auth/OIDC handshake, and the waitlist join API itself (so a gated
|
||||
// user can still submit the waitlist form).
|
||||
var defaultExemptPrefixes = []string{
|
||||
"/v1/featuregate/", // the mode read + the health route
|
||||
"/v1/iam/", // auth / OIDC / approval-status / get-account handshake
|
||||
"/v1/waitlist", // the waitlist join API (a gated user must reach it)
|
||||
"/v1/flags/waitlist", // the guard's public mode read (flags engine)
|
||||
"/v1/iam/", // auth / OIDC / approval-status / get-account handshake
|
||||
"/v1/waitlist", // the waitlist join API (a gated user must reach it)
|
||||
"/health",
|
||||
"/healthz",
|
||||
"/__guard/", // the @file guard's own callback surface (defense in depth)
|
||||
@@ -131,7 +138,7 @@ func Enforce(cfg EnforceConfig) zip.Handler {
|
||||
}
|
||||
gate := cfg.Gate
|
||||
if gate == nil {
|
||||
gate = flags.WaitlistModeForHost // the ONE decide: host→service→waitlist.<svc>
|
||||
gate = WaitlistModeForHost // the ONE decide: host→service→waitlist.<svc>
|
||||
}
|
||||
exempt := cfg.ExemptPrefixes
|
||||
if len(exempt) == 0 {
|
||||
@@ -199,7 +206,7 @@ func bounce(c *zip.Ctx, waitlistURL string) error {
|
||||
}
|
||||
|
||||
// apiKeyPrefixes are the Hanzo API-key prefixes. This MIRRORS cloud
|
||||
// auth_identity.go isAPIKey (the ONE authority) — kept local so featuregate stays
|
||||
// auth_identity.go isAPIKey (the ONE authority) — kept local so admission stays
|
||||
// self-contained (no cloud-internal import) while agreeing on the exact contract:
|
||||
// a token with one of these prefixes is a possession-gated API key, not a session
|
||||
// principal. If cloud adds a prefix there, add it here.
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
package featuregate
|
||||
package admission
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
// testGate is the injected decide (the flags engine's WaitlistModeForHost seam):
|
||||
// hanzo.chat is gated, api.hanzo.ai is open, everything else is un-governed. This is
|
||||
// exactly what flags.WaitlistModeForHost returns for the equivalent registry, without
|
||||
// exactly what WaitlistModeForHost returns for the equivalent registry, without
|
||||
// standing up the native flag engine (cgo) in a middleware unit test.
|
||||
func testGate(_ context.Context, host string) (mode bool, service string, known bool) {
|
||||
switch host {
|
||||
@@ -186,7 +186,7 @@ func TestRule_UngovernedHost_PassesThrough(t *testing.T) {
|
||||
|
||||
func TestRule_ExemptPaths_NeverGated(t *testing.T) {
|
||||
app := gateApp(t, "pending")
|
||||
for _, p := range []string{"/health", "/v1/iam/get-account", "/v1/waitlist/join", "/v1/featuregate/mode"} {
|
||||
for _, p := range []string{"/health", "/v1/iam/get-account", "/v1/waitlist/join", "/v1/flags/waitlist"} {
|
||||
code, _ := drive(t, app, greq{host: "hanzo.chat", path: p, user: "u", org: "acme", accept: html})
|
||||
if code != 200 {
|
||||
t.Fatalf("exempt path %q = %d, want 200 (never gated)", p, code)
|
||||
@@ -205,7 +205,7 @@ func TestRule_ForwardHeaderApproved_ThroughWithoutLookup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The DEFAULT gate (nil Gate → flags.WaitlistModeForHost) fail-opens before the flags
|
||||
// The DEFAULT gate (nil Gate → WaitlistModeForHost) fail-opens before the flag
|
||||
// engine has mounted: with no engine, WaitlistModeForHost returns known=false for every
|
||||
// host, so Enforce never gates pre-boot.
|
||||
func TestEnforce_DefaultGate_FailsOpenPreBoot(t *testing.T) {
|
||||
@@ -1,11 +1,11 @@
|
||||
package flags
|
||||
package admission
|
||||
|
||||
// The waitlist REGISTRY — the host→service map + service metadata folded in from
|
||||
// the former clients/featuregate SQLite store. It is deliberately MODE-FREE: a
|
||||
// service's waitlist mode is NOT a column here, it is the platform switch
|
||||
// waitlist.<svc> evaluated through the ONE native engine (waitlist.go). This store
|
||||
// answers only "which service owns this host, and what is its display metadata" —
|
||||
// the config the decide needs, with the decision itself owned by the flag engine.
|
||||
// The launch-registry — the host→service map + service display metadata. It is
|
||||
// deliberately MODE-FREE: a service's waitlist mode is NOT a column here, it is the
|
||||
// platform switch waitlist.<svc> evaluated through the ONE flag engine (clients/flags,
|
||||
// composed one-way from waitlist.go). This store answers only "which service owns this
|
||||
// host, and what is its display metadata" — the config the decide needs, with the
|
||||
// decision itself owned by the flag engine.
|
||||
//
|
||||
// It rides the SAME per-(org,project) OrgDB machinery as the flag defs (opened via
|
||||
// cloud.OrgStore, encrypted at rest via cek); the registry is PLATFORM-global, so it
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
// ErrServiceNotFound is returned when a service slug is not in the registry.
|
||||
var ErrServiceNotFound = errors.New("flags: waitlist service not found")
|
||||
var ErrServiceNotFound = errors.New("admission: waitlist service not found")
|
||||
|
||||
// ServiceRow is one hosted service in the registry (host→service + metadata). The
|
||||
// waitlist MODE is intentionally absent — it is the platform switch waitlist.<svc>,
|
||||
@@ -45,7 +45,7 @@ type waitlistStore struct {
|
||||
}
|
||||
|
||||
// openWaitlistStore migrates the registry schema over an already-opened (pragma'd,
|
||||
// cek-wrapped) OrgDB handle — the same open contract as openStore for flag defs.
|
||||
// cek-wrapped) OrgDB handle — the same open contract as flags' openStore for flag defs.
|
||||
func openWaitlistStore(db *sql.DB) (*waitlistStore, error) {
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS wl_services (
|
||||
@@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS wl_hosts (
|
||||
CREATE INDEX IF NOT EXISTS ix_wl_hosts_service ON wl_hosts(service);
|
||||
`
|
||||
if _, err := db.Exec(schema); err != nil {
|
||||
return nil, fmt.Errorf("flags: waitlist migrate: %w", err)
|
||||
return nil, fmt.Errorf("admission: waitlist migrate: %w", err)
|
||||
}
|
||||
return &waitlistStore{db: db}, nil
|
||||
}
|
||||
@@ -210,7 +210,7 @@ func (s *waitlistStore) Get(ctx context.Context, service string) (ServiceRow, er
|
||||
func (s *waitlistStore) Upsert(ctx context.Context, in ServiceRow, by string, now int64) (ServiceRow, error) {
|
||||
svc := strings.ToLower(strings.TrimSpace(in.Service))
|
||||
if svc == "" {
|
||||
return ServiceRow{}, fmt.Errorf("flags: waitlist service slug required")
|
||||
return ServiceRow{}, fmt.Errorf("admission: waitlist service slug required")
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
@@ -1,9 +1,9 @@
|
||||
package flags
|
||||
package admission
|
||||
|
||||
// Registry coverage for the folded host→service store. It drives the store over a raw
|
||||
// sqlite handle (the same driver OrgDB uses), so it exercises the fold WITHOUT the cek
|
||||
// Registry coverage for the host→service store. It drives the store over a raw sqlite
|
||||
// handle (the same driver OrgDB uses), so it exercises the registry WITHOUT the cek
|
||||
// at-rest layer — runnable under CGO=0. The MODE is out of scope here by design (it is
|
||||
// the waitlist.<svc> switch, evaluated by the native engine, covered separately).
|
||||
// the waitlist.<svc> switch, evaluated by the flag engine, covered separately).
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -1,19 +1,23 @@
|
||||
package flags
|
||||
package admission
|
||||
|
||||
// The waitlist LENS on the ONE flag engine — the launch-control plane folded in from
|
||||
// the former clients/featuregate. Decomplected into the two orthogonal axes it always
|
||||
// was, now with a single decision plane:
|
||||
// The launch-control gate — the COMPLETE waitlist feature, COMPOSING the ONE flag
|
||||
// engine (clients/flags) one-way. Decomplected into the two orthogonal axes it always
|
||||
// was, with a single decision plane:
|
||||
//
|
||||
// - MODE (per service): waitlist.<svc> IS a platform switch, evaluated through the
|
||||
// SAME native engine as every other platform flag. There is no second mode store.
|
||||
// - HOST MAP + metadata: the registry (waitlist_store.go) resolves a request host
|
||||
// to the service whose switch governs it, and carries display metadata.
|
||||
// flag engine (flags.Bool / flags.SetPlatformSwitch / flags.Register). There is no
|
||||
// second mode store.
|
||||
// - HOST MAP + metadata: the registry (registry.go) resolves a request host to the
|
||||
// service whose switch governs it, and carries display metadata.
|
||||
//
|
||||
// The decide is WaitlistModeForHost(host) → (mode, service, known): resolve host→svc,
|
||||
// then read waitlist.<svc>. featuregate.Enforce is now a CONSUMER of this decide, and
|
||||
// /v1/featuregate/mode + the /v1/admin/services board read it too. Per-user approval
|
||||
// (pending|approved) stays IAM's (featuregate/approval.go) — the second, orthogonal
|
||||
// axis, unchanged.
|
||||
// then read waitlist.<svc>. Enforce (middleware.go) consumes this decide; the admin
|
||||
// board (/v1/admin/services) and the guard's runtime mode read (/v1/flags/waitlist,
|
||||
// served here) read it too. Per-user approval (pending|approved) is the second,
|
||||
// orthogonal axis — IAM's, in approval.go.
|
||||
//
|
||||
// flags NEVER imports this package; this package imports flags. That one-way arrow is
|
||||
// the whole point of the decomplection: the engine is pure, the feature composes it.
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -25,10 +29,29 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/flags"
|
||||
luxlog "github.com/luxfi/log"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// The reserved platform tenant the launch registry rides in — the SAME reserved
|
||||
// (org, project) the flag engine uses for its platform switches, so the registry and
|
||||
// the waitlist.<svc> switches co-locate. One waitlist.db for the deployment.
|
||||
const (
|
||||
platformOrg = "platform"
|
||||
platformProject = "platform"
|
||||
)
|
||||
|
||||
// registryState is admission's process-wide launch state: the platform-tenant
|
||||
// host→service registry store + the deployment brand it was seeded for. Installed by
|
||||
// Mount, torn down by Shutdown.
|
||||
type registryState struct {
|
||||
store *cloud.OrgStore[*waitlistStore]
|
||||
brand string
|
||||
}
|
||||
|
||||
var mounted *registryState
|
||||
|
||||
// SeedService is one row of the launch registry (a hosted service + its hosts). Mode
|
||||
// is intentionally absent — the launch posture (gated) is waitlistDef's Default "true".
|
||||
type SeedService struct {
|
||||
@@ -60,17 +83,17 @@ func waitlistKey(svc string) string { return "waitlist." + strings.ToLower(strin
|
||||
|
||||
// waitlistDef is the platform switch for one service's mode. Default "true" = the
|
||||
// launch posture (gated until an admin opens it), so a deployment with no stored flag
|
||||
// behaves exactly as the old featuregate seed (waitlistMode ON).
|
||||
func waitlistDef(svc, display string) Def {
|
||||
// behaves exactly as the old admission seed (waitlistMode ON).
|
||||
func waitlistDef(svc, display string) flags.Def {
|
||||
if strings.TrimSpace(display) == "" {
|
||||
display = svc
|
||||
}
|
||||
return Def{
|
||||
return flags.Def{
|
||||
Key: waitlistKey(svc),
|
||||
Category: "Launch",
|
||||
Label: "Waitlist · " + display,
|
||||
Desc: "Waitlist mode for " + display + ": ON gates the service to APPROVED users; OFF opens it.",
|
||||
Type: TypeBool,
|
||||
Type: flags.TypeBool,
|
||||
Default: "true",
|
||||
}
|
||||
}
|
||||
@@ -78,9 +101,13 @@ func waitlistDef(svc, display string) Def {
|
||||
// ensureWaitlistDef registers a service's switch if it is not already registered
|
||||
// (Mount registers the seed set with nicer labels; this covers runtime onboards).
|
||||
func ensureWaitlistDef(svc, display string) {
|
||||
if _, ok := lookupDef(waitlistKey(svc)); !ok {
|
||||
Register(waitlistDef(svc, display))
|
||||
key := waitlistKey(svc)
|
||||
for _, d := range flags.Defs() {
|
||||
if d.Key == key {
|
||||
return
|
||||
}
|
||||
}
|
||||
flags.Register(waitlistDef(svc, display))
|
||||
}
|
||||
|
||||
// boolDef is the minimal PostHog flag definition for a boolean switch value.
|
||||
@@ -92,26 +119,24 @@ func boolDef(on bool) json.RawMessage {
|
||||
}
|
||||
|
||||
// requireRegistry resolves the platform-tenant registry store, or an error when the
|
||||
// engine is not mounted (writes need it; the decide fail-opens instead).
|
||||
// gate is not mounted (writes need it; the decide fail-opens instead).
|
||||
func requireRegistry() (*waitlistStore, error) {
|
||||
c := mounted
|
||||
if c == nil || c.registry == nil {
|
||||
return nil, fmt.Errorf("flags: waitlist registry not mounted")
|
||||
if mounted == nil || mounted.store == nil {
|
||||
return nil, fmt.Errorf("admission: waitlist registry not mounted")
|
||||
}
|
||||
return c.registry.For(platformOrg, platformProject)
|
||||
return mounted.store.For(platformOrg, platformProject)
|
||||
}
|
||||
|
||||
// WaitlistModeForHost is THE decide the Enforce consumer, /v1/featuregate/mode, and
|
||||
// WaitlistModeForHost is THE decide the Enforce consumer, /v1/flags/waitlist, and
|
||||
// the admin board call: resolve host→service, then read the waitlist.<svc> switch
|
||||
// through the engine. FAIL-OPEN by construction — an unmounted registry, a store
|
||||
// through the flag engine. FAIL-OPEN by construction — an unmounted registry, a store
|
||||
// error, or an un-governed host all return known=false, so a request is NEVER gated
|
||||
// pre-boot or on a registry fault (availability over a hard gate, matching the guard).
|
||||
func WaitlistModeForHost(ctx context.Context, host string) (mode bool, service string, known bool) {
|
||||
c := mounted
|
||||
if c == nil || c.registry == nil {
|
||||
if mounted == nil || mounted.store == nil {
|
||||
return false, "", false
|
||||
}
|
||||
st, err := c.registry.For(platformOrg, platformProject)
|
||||
st, err := mounted.store.For(platformOrg, platformProject)
|
||||
if err != nil {
|
||||
return false, "", false
|
||||
}
|
||||
@@ -119,7 +144,7 @@ func WaitlistModeForHost(ctx context.Context, host string) (mode bool, service s
|
||||
if err != nil || !known {
|
||||
return false, "", false
|
||||
}
|
||||
return Bool(waitlistKey(svc)), svc, true
|
||||
return flags.Bool(waitlistKey(svc)), svc, true
|
||||
}
|
||||
|
||||
// ListWaitlistServices returns the admin board: every registered service with its LIVE
|
||||
@@ -135,19 +160,19 @@ func ListWaitlistServices(ctx context.Context) ([]ServiceView, error) {
|
||||
}
|
||||
out := make([]ServiceView, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, ServiceView{ServiceRow: r, WaitlistMode: Bool(waitlistKey(r.Service))})
|
||||
out = append(out, ServiceView{ServiceRow: r, WaitlistMode: flags.Bool(waitlistKey(r.Service))})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SetWaitlistMode flips one service's waitlist switch — the launch lever — and returns
|
||||
// the updated view. It is the ONE write path (through SetPlatformSwitch, audited in the
|
||||
// flag activity log); the flip is hot (this pod applies immediately, peers converge
|
||||
// within the eval TTL). ErrServiceNotFound when the slug is unknown.
|
||||
// the updated view. It is the ONE write path (through flags.SetPlatformSwitch, audited
|
||||
// in the flag activity log); the flip is hot (this pod applies immediately, peers
|
||||
// converge within the eval TTL). ErrServiceNotFound when the slug is unknown.
|
||||
func SetWaitlistMode(ctx context.Context, service string, mode bool, actor string) (ServiceView, error) {
|
||||
service = strings.ToLower(strings.TrimSpace(service))
|
||||
if service == "" {
|
||||
return ServiceView{}, fmt.Errorf("flags: service is required")
|
||||
return ServiceView{}, fmt.Errorf("admission: service is required")
|
||||
}
|
||||
st, err := requireRegistry()
|
||||
if err != nil {
|
||||
@@ -158,10 +183,10 @@ func SetWaitlistMode(ctx context.Context, service string, mode bool, actor strin
|
||||
return ServiceView{}, err
|
||||
}
|
||||
ensureWaitlistDef(service, row.DisplayName)
|
||||
if err := SetPlatformSwitch(waitlistKey(service), boolDef(mode), actor); err != nil {
|
||||
if err := flags.SetPlatformSwitch(waitlistKey(service), boolDef(mode), actor); err != nil {
|
||||
return ServiceView{}, err
|
||||
}
|
||||
return ServiceView{ServiceRow: row, WaitlistMode: Bool(waitlistKey(service))}, nil
|
||||
return ServiceView{ServiceRow: row, WaitlistMode: flags.Bool(waitlistKey(service))}, nil
|
||||
}
|
||||
|
||||
// UpsertWaitlistService onboards or edits a hosted service so a new host is governed
|
||||
@@ -170,7 +195,7 @@ func SetWaitlistMode(ctx context.Context, service string, mode bool, actor strin
|
||||
func UpsertWaitlistService(ctx context.Context, in ServiceInput, actor string) (ServiceView, error) {
|
||||
svc := strings.ToLower(strings.TrimSpace(in.Service))
|
||||
if svc == "" {
|
||||
return ServiceView{}, fmt.Errorf("flags: service slug is required")
|
||||
return ServiceView{}, fmt.Errorf("admission: service slug is required")
|
||||
}
|
||||
st, err := requireRegistry()
|
||||
if err != nil {
|
||||
@@ -192,43 +217,44 @@ func UpsertWaitlistService(ctx context.Context, in ServiceInput, actor string) (
|
||||
}
|
||||
ensureWaitlistDef(svc, row.DisplayName)
|
||||
if isNew {
|
||||
if err := SetPlatformSwitch(waitlistKey(svc), boolDef(in.WaitlistMode), actor); err != nil {
|
||||
if err := flags.SetPlatformSwitch(waitlistKey(svc), boolDef(in.WaitlistMode), actor); err != nil {
|
||||
return ServiceView{}, err
|
||||
}
|
||||
}
|
||||
return ServiceView{ServiceRow: row, WaitlistMode: Bool(waitlistKey(svc))}, nil
|
||||
return ServiceView{ServiceRow: row, WaitlistMode: flags.Bool(waitlistKey(svc))}, nil
|
||||
}
|
||||
|
||||
// mountWaitlist seeds the registry and registers a waitlist.<svc> switch per known
|
||||
// service. Best-effort + fail-safe: a registry error (e.g. cek master key not yet
|
||||
// injected) degrades to the in-memory seed switches — the decide then fail-opens,
|
||||
// exactly the flag engine's own boot posture. Called from Mount.
|
||||
func mountWaitlist(c *Client, brand string, log luxlog.Logger) {
|
||||
// seedRegistry seeds the registry and registers a waitlist.<svc> switch per known
|
||||
// service, COMPOSING the flag engine (flags.Register). Best-effort + fail-safe: a
|
||||
// registry error (e.g. cek master key not yet injected) degrades to the in-memory seed
|
||||
// switches — the decide then fail-opens, exactly the flag engine's own boot posture.
|
||||
// Returns the number of seeded services (for the mount log). Called from Mount.
|
||||
func seedRegistry(brand string, log luxlog.Logger) int {
|
||||
seed := seedWaitlist(brand)
|
||||
for _, sv := range seed { // in-memory switches — always succeeds
|
||||
Register(waitlistDef(sv.Service, sv.DisplayName))
|
||||
flags.Register(waitlistDef(sv.Service, sv.DisplayName))
|
||||
}
|
||||
st, err := c.registry.For(platformOrg, platformProject)
|
||||
st, err := mounted.store.For(platformOrg, platformProject)
|
||||
if err != nil {
|
||||
log.Warn("waitlist registry unavailable — modes degrade to seed defaults", "err", err)
|
||||
return
|
||||
return len(seed)
|
||||
}
|
||||
if _, err := st.Seed(context.Background(), seed, time.Now().Unix()); err != nil {
|
||||
log.Warn("waitlist registry seed failed", "err", err)
|
||||
return
|
||||
return len(seed)
|
||||
}
|
||||
if rows, err := st.List(context.Background()); err == nil {
|
||||
for _, r := range rows { // register any persisted onboard beyond the seed
|
||||
ensureWaitlistDef(r.Service, r.DisplayName)
|
||||
}
|
||||
}
|
||||
return len(seed)
|
||||
}
|
||||
|
||||
// waitlistModeRoute answers GET /v1/featuregate/mode?host=<h> — the runtime lookup the
|
||||
// waitlistModeRoute answers GET /v1/flags/waitlist?host=<h> — the runtime lookup the
|
||||
// @file waitlist-guard caches. Public (in-cluster) read: it returns ONLY the boolean
|
||||
// mode for the ONE queried host, never an enumeration. Same wire shape as the former
|
||||
// featuregate route, so the interim guard ports 1:1.
|
||||
func waitlistModeRoute(_ *cloud.Service[state], c *zip.Ctx) error {
|
||||
// mode for the ONE queried host, never an enumeration.
|
||||
func waitlistModeRoute(c *zip.Ctx) error {
|
||||
host := strings.TrimSpace(c.Query("host"))
|
||||
if host == "" {
|
||||
host = c.Fiber().Hostname()
|
||||
@@ -242,7 +268,44 @@ func waitlistModeRoute(_ *cloud.Service[state], c *zip.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// ── brand seed (moved verbatim from the former featuregate/seed.go) ──────────────
|
||||
// ── lifecycle ────────────────────────────────────────────────────────────────
|
||||
|
||||
// Mount installs the launch-control gate: it opens the platform-tenant host→service
|
||||
// registry, seeds it for the deployment brand, registers a waitlist.<svc> switch per
|
||||
// service in the flag engine (flags.Register), and serves the guard's public mode read
|
||||
// at /v1/flags/waitlist. Fail-safe: a registry error (e.g. cek master key not yet
|
||||
// injected) degrades to the in-memory seed switches — WaitlistModeForHost then
|
||||
// fail-opens. Mounts AFTER flags so the engine's platform-switch plane is installed first.
|
||||
func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
if deps.Logger == nil {
|
||||
return fmt.Errorf("admission.Mount: nil deps.Logger")
|
||||
}
|
||||
if deps.DataDir == "" {
|
||||
return fmt.Errorf("admission.Mount: empty deps.DataDir")
|
||||
}
|
||||
log := deps.Logger.New("subsystem", "admission")
|
||||
mounted = ®istryState{
|
||||
store: cloud.NewOrgStore[*waitlistStore](deps.DataDir, "waitlist", openWaitlistStore),
|
||||
brand: deps.Brand,
|
||||
}
|
||||
n := seedRegistry(deps.Brand, log)
|
||||
// The guard's public runtime mode read (host→service→waitlist.<svc>), one namespace
|
||||
// under /v1/flags. Exempt from the Enforce gate (see defaultExemptPrefixes) so a
|
||||
// gated user can still resolve mode.
|
||||
app.Get("/v1/flags/waitlist", waitlistModeRoute)
|
||||
log.Info("admission gate ready", "services", n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Shutdown closes the launch registry's per-org store handles.
|
||||
func Shutdown() error {
|
||||
if mounted == nil || mounted.store == nil {
|
||||
return nil
|
||||
}
|
||||
return mounted.store.CloseAll()
|
||||
}
|
||||
|
||||
// ── brand seed (moved verbatim from the former flags/waitlist.go) ────────────────
|
||||
|
||||
// seedWaitlist returns the launch registry for a brand. White-labeled so a Lux/Zoo/Pars
|
||||
// deployment governs its OWN hosts. New hosted services onboard at runtime via
|
||||
+7
-6
@@ -106,13 +106,14 @@ func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
|
||||
// routes registers the ads surface: the campaign CRUD + the summary roll-up.
|
||||
func routes(app *zip.App, s *cloud.Service[state]) {
|
||||
app.Get("/v1/ads/summary", cloud.Handle(s, summary))
|
||||
g := app.Group("/v1/ads")
|
||||
g.Get("/summary", cloud.Handle(s, summary))
|
||||
|
||||
app.Get("/v1/ads/campaigns", cloud.Handle(s, listCampaigns))
|
||||
app.Post("/v1/ads/campaigns", cloud.Handle(s, createCampaign))
|
||||
app.Get("/v1/ads/campaigns/:id", cloud.Handle(s, getCampaign))
|
||||
app.Put("/v1/ads/campaigns/:id", cloud.Handle(s, updateCampaign))
|
||||
app.Delete("/v1/ads/campaigns/:id", cloud.Handle(s, deleteCampaign))
|
||||
g.Get("/campaigns", cloud.Handle(s, listCampaigns))
|
||||
g.Post("/campaigns", cloud.Handle(s, createCampaign))
|
||||
g.Get("/campaigns/:id", cloud.Handle(s, getCampaign))
|
||||
g.Put("/campaigns/:id", cloud.Handle(s, updateCampaign))
|
||||
g.Delete("/campaigns/:id", cloud.Handle(s, deleteCampaign))
|
||||
}
|
||||
|
||||
// ---- shared helpers (mirror clients/crm) ----
|
||||
|
||||
+27
-136
@@ -1,153 +1,44 @@
|
||||
package affiliates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/commerceinproc"
|
||||
"github.com/hanzoai/cloud/clients/payout"
|
||||
)
|
||||
|
||||
// commerce is the narrow money seam the affiliate loop needs: read a referred
|
||||
// org's metered spend (the accrual base) and grant a promo credit to a wallet (a
|
||||
// payout made in credits). It is an INTERFACE so the store/handler logic is
|
||||
// testable with a fake ledger — the HTTP impl below is the ONE production binding.
|
||||
// commerce is the narrow money seam the affiliate loop needs: read a referred org's
|
||||
// metered spend (the commission accrual base) and grant a promo credit to a wallet
|
||||
// (a payout made in credits, ledger tag grant:affiliate). It is an INTERFACE so the
|
||||
// store/handler logic is testable with a fake ledger; the production binding is
|
||||
// clients/payout, reached through the thin adapter below.
|
||||
//
|
||||
// This mirrors clients/referrals/commerce.go EXACTLY (which itself mirrors
|
||||
// clients/admin/commerce.go): the same COMMERCE_SERVICE_TOKEN S2S path, the same
|
||||
// X-Org-Id=<org> namespace + bare org `user` subject that admin.grantCredit uses —
|
||||
// so an affiliate payout-in-credits lands in precisely the wallet the balance
|
||||
// panel reads, indistinguishable from an admin grant except by its ledger tag
|
||||
// (grant:affiliate vs grant:referral / grant:admin, all → the commerce Credit/trial
|
||||
// bucket per DepositKind's grant:* rule).
|
||||
// The S2S impl (COMMERCE_SERVICE_TOKEN path, X-Org-Id=<org> namespace, bare-org
|
||||
// `user` subject) was three byte-identical commerce.go copies; it now lives ONCE in
|
||||
// clients/payout. An affiliate payout-in-credits still lands in precisely the wallet
|
||||
// the balance panel reads, indistinguishable from an admin grant except by its
|
||||
// grant:affiliate tag.
|
||||
type commerce interface {
|
||||
configured() bool
|
||||
// deposit grants amountCents to org's wallet (Credit/trial bucket via the
|
||||
// grant:affiliate tag) and returns the ledger transaction id.
|
||||
deposit(ctx context.Context, org, user string, amountCents int64, currency, notes, tags string) (txnID string, err error)
|
||||
// spendCents is a referred org's month-to-date metered consumption — the
|
||||
// commission accrual base (spend × the affiliate's rate).
|
||||
spendCents(ctx context.Context, org, user string) (int64, error)
|
||||
}
|
||||
|
||||
// errUnconfigured is returned by a deposit against an unwired commerce so the
|
||||
// caller records an honest failure rather than reporting a phantom payout.
|
||||
var errUnconfigured = errors.New("affiliates: commerce endpoint not configured")
|
||||
// errUnconfigured is the shared sentinel a deposit against an unwired commerce
|
||||
// returns, so the caller records an honest failure rather than a phantom payout.
|
||||
var errUnconfigured = payout.ErrUnconfigured
|
||||
|
||||
// httpCommerce is the production commerce binding (COMMERCE_SERVICE_TOKEN S2S).
|
||||
type httpCommerce struct {
|
||||
base string
|
||||
token string
|
||||
http *http.Client
|
||||
// commerceSeam adapts the shared payout.Client onto this program's lowercase seam
|
||||
// (Go package-scoped interface methods cannot cross packages). Zero logic — pure
|
||||
// delegation; the money path lives in clients/payout.
|
||||
type commerceSeam struct{ c *payout.Client }
|
||||
|
||||
func (s commerceSeam) configured() bool { return s.c.Configured() }
|
||||
func (s commerceSeam) deposit(ctx context.Context, org, user string, amountCents int64, currency, notes, tags string) (string, error) {
|
||||
return s.c.Deposit(ctx, org, user, amountCents, currency, notes, tags)
|
||||
}
|
||||
func (s commerceSeam) spendCents(ctx context.Context, org, user string) (int64, error) {
|
||||
return s.c.SpendCents(ctx, org, user)
|
||||
}
|
||||
|
||||
func newCommerceClient(base, token string) *httpCommerce {
|
||||
return &httpCommerce{
|
||||
base: strings.TrimRight(strings.TrimSpace(base), "/"),
|
||||
token: strings.TrimSpace(token),
|
||||
http: commerceinproc.Client(15 * time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *httpCommerce) configured() bool { return c != nil && c.base != "" && c.token != "" }
|
||||
|
||||
// deposit posts POST /v1/billing/deposit — the ONE money-in primitive (identical
|
||||
// to admin.commerceClient.deposit). Commerce's EdgeAuth pins the body `user` to
|
||||
// the X-Org-Id subject, so a payout can never be mis-targeted to another wallet.
|
||||
func (c *httpCommerce) deposit(ctx context.Context, org, user string, amountCents int64, currency, notes, tags string) (string, error) {
|
||||
if !c.configured() {
|
||||
return "", errUnconfigured
|
||||
}
|
||||
if currency == "" {
|
||||
currency = "usd"
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"user": user,
|
||||
"currency": currency,
|
||||
"amount": amountCents,
|
||||
"notes": notes,
|
||||
"tags": tags,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := c.do(ctx, http.MethodPost, "/v1/billing/deposit", nil, org, body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out struct {
|
||||
TransactionID string `json:"transactionId"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return "", fmt.Errorf("commerce deposit decode: %w", err)
|
||||
}
|
||||
return out.TransactionID, nil
|
||||
}
|
||||
|
||||
// spendCents reads GET /v1/billing/usage-rollup and returns consumedCents. Zero
|
||||
// (not an error) when commerce is unconfigured so a partial deploy degrades to
|
||||
// "no spend to accrue yet" rather than a 5xx.
|
||||
func (c *httpCommerce) spendCents(ctx context.Context, org, user string) (int64, error) {
|
||||
if !c.configured() {
|
||||
return 0, nil
|
||||
}
|
||||
q := url.Values{"user": {user}}
|
||||
raw, err := c.do(ctx, http.MethodGet, "/v1/billing/usage-rollup", q, org, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var out struct {
|
||||
ConsumedCents int64 `json:"consumedCents"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return 0, fmt.Errorf("commerce rollup decode: %w", err)
|
||||
}
|
||||
return out.ConsumedCents, nil
|
||||
}
|
||||
|
||||
// do performs one admin-S2S commerce request. X-Org-Id=<org> is the per-org
|
||||
// namespace selector commerce's EdgeAuth trusts only behind the service token.
|
||||
func (c *httpCommerce) do(ctx context.Context, method, path string, q url.Values, org string, body []byte) ([]byte, error) {
|
||||
u := c.base + path
|
||||
if enc := q.Encode(); enc != "" {
|
||||
u += "?" + enc
|
||||
}
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
r = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, u, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
if org != "" {
|
||||
req.Header.Set("X-Org-Id", org)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("commerce unreachable: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("commerce status %d", resp.StatusCode)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
// newCommerceClient builds the production binding, delegating to clients/payout.
|
||||
func newCommerceClient(base, token string) commerce { return commerceSeam{payout.NewClient(base, token)} }
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
hz "github.com/hanzoai/agent"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/tools"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
openai "github.com/hanzoai/go-openai"
|
||||
fiber "github.com/zap-proto/fiber/v3"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
+128
-23
@@ -28,7 +28,9 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
mrand "math/rand/v2"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -107,6 +109,13 @@ type state struct {
|
||||
// per subsystem. Empty only on a deployment that configured no default, in
|
||||
// which case create still requires an explicit model.
|
||||
defaultModel string
|
||||
// failoverModel is the reliable model a run falls over to when the agent's own
|
||||
// model stays throttled (429/overloaded) after bounded retries
|
||||
// (deps.AIFallbackModel, default "best"). It makes an autonomous bot reply
|
||||
// still land when the throttled default flash model is overloaded. Empty
|
||||
// disables failover (retry-only). Only the run path reads it — interactive
|
||||
// chat is untouched.
|
||||
failoverModel string
|
||||
// bill is the shared per-org gate+meter (reuses deps.Metering, the ONE
|
||||
// commerce client — the same object ml/provisioning use). Nil/!Enabled()
|
||||
// makes Gate allow and Meter a no-op, so an unconfigured deployment runs
|
||||
@@ -262,11 +271,12 @@ func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
s := &cloud.Service[state]{
|
||||
Base: cloud.NewBase(deps, "agents"),
|
||||
State: state{
|
||||
store: store,
|
||||
ai: deps.AI,
|
||||
defaultModel: strings.TrimSpace(deps.AIDefaultModel),
|
||||
bill: cloud.NewResourceMeter(deps, meterKind),
|
||||
bus: newBus(),
|
||||
store: store,
|
||||
ai: deps.AI,
|
||||
defaultModel: strings.TrimSpace(deps.AIDefaultModel),
|
||||
failoverModel: strings.TrimSpace(deps.AIFallbackModel),
|
||||
bill: cloud.NewResourceMeter(deps, meterKind),
|
||||
bus: newBus(),
|
||||
// TASKS PLUG-IN POINT: durable execution rides hanzoai/tasks, not a
|
||||
// bespoke engine. Default is record-only; wiring client.Dial(TASKS_URL)
|
||||
// from github.com/hanzoai/tasks/pkg/sdk/client here makes control forward
|
||||
@@ -276,6 +286,7 @@ func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
}
|
||||
mounted = s
|
||||
|
||||
g := app.Group("/v1/agents")
|
||||
app.Get("/v1/agents", cloud.Handle(s, list))
|
||||
app.Post("/v1/agents", cloud.Handle(s, create))
|
||||
// The static org-wide surfaces are listed before the :ref wildcard for reading
|
||||
@@ -284,18 +295,18 @@ func Mount(app *zip.App, deps cloud.Deps) error {
|
||||
// a ref). Registration order decides nothing here — it only decides which
|
||||
// handler silently wins when two patterns are byte-identical, which is a
|
||||
// collision, not a precedence.
|
||||
app.Get("/v1/agents/metrics", cloud.Handle(s, metrics))
|
||||
app.Get("/v1/agents/activity", cloud.Handle(s, activity))
|
||||
g.Get("/metrics", cloud.Handle(s, metrics))
|
||||
g.Get("/activity", cloud.Handle(s, activity))
|
||||
// Live agent-session control plane: /v1/agents/sessions[/...].
|
||||
mountSessions(s, app)
|
||||
// Agent targets: /v1/agents/targets[/...] — the #48 dispatch destinations a
|
||||
// session runs on.
|
||||
mountTargets(s, app)
|
||||
app.Get("/v1/agents/:ref", cloud.Handle(s, get))
|
||||
app.Patch("/v1/agents/:ref", cloud.Handle(s, update))
|
||||
app.Delete("/v1/agents/:ref", cloud.Handle(s, del))
|
||||
app.Post("/v1/agents/:ref/run", cloud.Handle(s, run))
|
||||
app.Get("/v1/agents/:ref/runs", cloud.Handle(s, runs))
|
||||
g.Get("/:ref", cloud.Handle(s, get))
|
||||
g.Patch("/:ref", cloud.Handle(s, update))
|
||||
g.Delete("/:ref", cloud.Handle(s, del))
|
||||
g.Post("/:ref/run", cloud.Handle(s, run))
|
||||
g.Get("/:ref/runs", cloud.Handle(s, runs))
|
||||
|
||||
// Long-running scheduler: invokes each long-running agent's run on its cron
|
||||
// cadence through the SAME runAgent path as the HTTP handler (one run path,
|
||||
@@ -665,11 +676,12 @@ func runAgent(s *cloud.Service[state], ctx context.Context, a Agent, input, acto
|
||||
return Run{}, err
|
||||
}
|
||||
|
||||
r := executeRun(ctx, s.State.ai, a.Org, a, input)
|
||||
r := executeRun(ctx, s.State.ai, a.Org, a, input, s.State.failoverModel)
|
||||
span.SetAttributes(
|
||||
attribute.String("hanzo.agent.run_id", r.ID),
|
||||
attribute.String("hanzo.agent.run_status", r.Status),
|
||||
attribute.Int64("hanzo.agent.duration_ms", r.DurationMs),
|
||||
attribute.String("gen_ai.response.model", r.Model),
|
||||
)
|
||||
if r.Status == "error" {
|
||||
span.SetStatus(codes.Error, r.Error)
|
||||
@@ -685,12 +697,14 @@ func runAgent(s *cloud.Service[state], ctx context.Context, a Agent, input, acto
|
||||
openRunSession(s, ctx, a, r, actor)
|
||||
|
||||
// Bill only a successful run (mirrors the edge gate: failed work is not
|
||||
// charged). Rich attribution: product=agent (Provider), the agent's model,
|
||||
// and the actor for the audit trail. Fire-and-forget on a background context.
|
||||
// charged). Rich attribution: product=agent (Provider), the model ACTUALLY
|
||||
// used (r.Model — a failover run bills the reliable model it fell over to, not
|
||||
// the throttled one it started on), and the actor for the audit trail.
|
||||
// Fire-and-forget on a background context.
|
||||
if r.Status == "ok" {
|
||||
s.State.bill.MeterUsage(a.Org, meterKind, metering.Usage{
|
||||
AmountCents: fee,
|
||||
Model: a.Model,
|
||||
Model: r.Model,
|
||||
Actor: actor,
|
||||
RequestID: requestID,
|
||||
ClientIP: clientIP,
|
||||
@@ -699,11 +713,31 @@ func runAgent(s *cloud.Service[state], ctx context.Context, a Agent, input, acto
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// executeRun composes the agent's instructions with the caller input, runs one
|
||||
// real chat completion through the AI client, and returns the resulting Run —
|
||||
// status "ok" with output, or "error" with the upstream failure. Pure of HTTP
|
||||
// and persistence so it is directly testable; the caller records + responds.
|
||||
func executeRun(ctx context.Context, ai types.AIClient, org string, a Agent, input string) Run {
|
||||
// maxAttempts bounds retries of a SINGLE model's completion on a transient
|
||||
// upstream failure (429 / 5xx / empty-choices / "Platform overloaded"). Retrying
|
||||
// a completion is side-effect-free — nothing bills until it succeeds — so a
|
||||
// bounded retry with jittered backoff turns an intermittent gateway 429 into a
|
||||
// delivered reply instead of a dropped one.
|
||||
const maxAttempts = 3
|
||||
|
||||
// retryBaseDelay / retryMaxDelay bound the exponential, equal-jittered backoff
|
||||
// between attempts. Small by design: a gateway overload clears in well under a
|
||||
// second, and a run must not stall a bot conversation.
|
||||
const (
|
||||
retryBaseDelay = 150 * time.Millisecond
|
||||
retryMaxDelay = 2 * time.Second
|
||||
)
|
||||
|
||||
// executeRun composes the agent's instructions with the caller input and runs
|
||||
// one chat completion through the AI client — with a bounded retry on transient
|
||||
// upstream overload and, if the agent's own model stays throttled, ONE failover
|
||||
// to the deployment's reliable model (fallback) so an autonomous bot reply still
|
||||
// lands. It returns the resulting Run — status "ok" with output and Model set to
|
||||
// the model that ACTUALLY answered (so metering bills that model), or "error"
|
||||
// with the final upstream failure. Pure of HTTP and persistence so it is directly
|
||||
// testable; the caller records + responds. This reliability policy is the agent
|
||||
// runner's ALONE — the interactive user-facing chat path is untouched.
|
||||
func executeRun(ctx context.Context, ai types.AIClient, org string, a Agent, input, fallback string) Run {
|
||||
// Child step span; the AI client opens its own GenAI span nested under this.
|
||||
ctx, span := agentTracer.Start(ctx, "agent.step", trace.WithSpanKind(trace.SpanKindInternal))
|
||||
defer span.End()
|
||||
@@ -717,11 +751,11 @@ func executeRun(ctx context.Context, ai types.AIClient, org string, a Agent, inp
|
||||
prompt += in
|
||||
}
|
||||
start := time.Now()
|
||||
resp, aiErr := ai.ChatCompletion(ctx, &types.ChatRequest{Model: a.Model, Prompt: prompt, Org: org})
|
||||
resp, used, aiErr := completeWithFailover(ctx, ai, org, prompt, a.Model, fallback)
|
||||
dur := time.Since(start).Milliseconds()
|
||||
id, _ := genID("run")
|
||||
r := Run{
|
||||
ID: id, Org: org, AgentName: a.Name, Model: a.Model, Input: input,
|
||||
ID: id, Org: org, AgentName: a.Name, Model: used, Input: input,
|
||||
DurationMs: dur, CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
if aiErr != nil {
|
||||
@@ -738,6 +772,77 @@ func executeRun(ctx context.Context, ai types.AIClient, org string, a Agent, inp
|
||||
return r
|
||||
}
|
||||
|
||||
// completeWithFailover runs the completion on the agent's model with a bounded
|
||||
// retry (completeWithRetry), then — only if that model is STILL throttled after
|
||||
// its retries — fails over ONCE to fallback, a reliable model. It returns the
|
||||
// response, the model that actually produced it (for honest metering), and the
|
||||
// final error. A non-transient failure on either model returns immediately (the
|
||||
// next model would fail identically). ONE ordered mechanism, no config sprawl.
|
||||
func completeWithFailover(ctx context.Context, ai types.AIClient, org, prompt, model, fallback string) (*types.ChatResponse, string, error) {
|
||||
models := []string{model}
|
||||
if f := strings.TrimSpace(fallback); f != "" && f != model {
|
||||
models = append(models, f)
|
||||
}
|
||||
var lastErr error
|
||||
for _, m := range models {
|
||||
resp, err := completeWithRetry(ctx, ai, org, prompt, m)
|
||||
if err == nil {
|
||||
return resp, m, nil
|
||||
}
|
||||
lastErr = err
|
||||
// Escalate to the next model ONLY on a transient overload; a hard error
|
||||
// (bad request, auth, unserved model) fails fast — failover cannot help.
|
||||
if !errors.Is(err, types.ErrUpstreamBusy) {
|
||||
return nil, m, err
|
||||
}
|
||||
}
|
||||
return nil, models[len(models)-1], lastErr
|
||||
}
|
||||
|
||||
// completeWithRetry calls the completion up to maxAttempts times, retrying ONLY a
|
||||
// transient upstream overload (types.ErrUpstreamBusy) with jittered backoff and
|
||||
// respecting context cancellation. A non-transient error returns immediately.
|
||||
func completeWithRetry(ctx context.Context, ai types.AIClient, org, prompt, model string) (*types.ChatResponse, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < maxAttempts; attempt++ {
|
||||
resp, err := ai.ChatCompletion(ctx, &types.ChatRequest{Model: model, Prompt: prompt, Org: org})
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
lastErr = err
|
||||
if !errors.Is(err, types.ErrUpstreamBusy) {
|
||||
return nil, err // permanent — do not burn retries repeating it
|
||||
}
|
||||
if attempt == maxAttempts-1 {
|
||||
break
|
||||
}
|
||||
if err := sleepBackoff(ctx, attempt); err != nil {
|
||||
return nil, err // context cancelled/expired mid-backoff
|
||||
}
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// sleepBackoff waits an exponential, equal-jittered delay before the next
|
||||
// attempt, or returns the context error if the caller's deadline fires first.
|
||||
func sleepBackoff(ctx context.Context, attempt int) error {
|
||||
d := retryBaseDelay << attempt
|
||||
if d > retryMaxDelay {
|
||||
d = retryMaxDelay
|
||||
}
|
||||
// Equal jitter: half fixed, half random in [0, d/2) — spreads retries without
|
||||
// ever collapsing the delay to ~0 (guarantees forward progress under load).
|
||||
wait := d/2 + time.Duration(mrand.Int64N(int64(d/2)+1))
|
||||
t := time.NewTimer(wait)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func runs(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestExecuteRunOK(t *testing.T) {
|
||||
ai := &fakeAI{content: "hi there"}
|
||||
a := mk("maxpower", "greeter")
|
||||
a.Instructions = "You are a greeter."
|
||||
r := executeRun(context.Background(), ai, "maxpower", a, "say hi")
|
||||
r := executeRun(context.Background(), ai, "maxpower", a, "say hi", "")
|
||||
|
||||
if r.Status != "ok" {
|
||||
t.Fatalf("want ok, got %q err=%q", r.Status, r.Error)
|
||||
@@ -178,7 +178,7 @@ func TestExecuteRunOK(t *testing.T) {
|
||||
|
||||
func TestExecuteRunRecordsError(t *testing.T) {
|
||||
ai := &fakeAI{err: errors.New("model unavailable")}
|
||||
r := executeRun(context.Background(), ai, "maxpower", mk("maxpower", "x"), "in")
|
||||
r := executeRun(context.Background(), ai, "maxpower", mk("maxpower", "x"), "in", "")
|
||||
if r.Status != "error" {
|
||||
t.Fatalf("want error status, got %q", r.Status)
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/types"
|
||||
"github.com/hanzoai/cloud/clients/metering"
|
||||
"github.com/hanzoai/cloud/types"
|
||||
luxlog "github.com/luxfi/log"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
@@ -88,7 +88,10 @@ func mountBilled(t *testing.T, commerceURL string, ai types.AIClient) *zip.App {
|
||||
t.Fatalf("metering.New: %v", err)
|
||||
}
|
||||
app := zip.New(zip.Config{Logger: luxlog.New("test")})
|
||||
deps := cloud.Deps{Logger: luxlog.New("test"), DataDir: t.TempDir(), AI: ai, Metering: m}
|
||||
// AIFallbackModel="best" arms the agent runner's failover so the retry/failover
|
||||
// tests exercise the real escalation path; it never fires for a run whose model
|
||||
// answers (or fails non-transiently), so the other billed tests are unaffected.
|
||||
deps := cloud.Deps{Logger: luxlog.New("test"), DataDir: t.TempDir(), AI: ai, Metering: m, AIFallbackModel: "best"}
|
||||
if err := Mount(app, deps); err != nil {
|
||||
t.Fatalf("Mount: %v", err)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,44 @@ func OpenSession(ctx context.Context, org, actor, agent, title string) (string,
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// OpenSessionOn is OpenSession with the run's dispatch TARGET recorded, so
|
||||
// mission-control shows a routed run on the machine it was sent to (session.target
|
||||
// == the target id) exactly as a locally-linked run shows its host. The target is
|
||||
// re-resolved org-scoped and MUST belong to this org — a session can never claim
|
||||
// to run on another tenant's machine (the same fail-closed rule sessionContext
|
||||
// enforces on the HTTP register path). An empty target falls back to OpenSession.
|
||||
func OpenSessionOn(ctx context.Context, org, actor, agent, title, target string) (string, error) {
|
||||
target = strings.TrimSpace(target)
|
||||
if target == "" {
|
||||
return OpenSession(ctx, org, actor, agent, title)
|
||||
}
|
||||
if mounted == nil {
|
||||
return "", fmt.Errorf("agents: not mounted")
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
if org == "" {
|
||||
return "", fmt.Errorf("agents: org required")
|
||||
}
|
||||
if _, err := mounted.State.store.GetTarget(ctx, org, target); err != nil {
|
||||
if err == errTargetNotFound {
|
||||
return "", fmt.Errorf("agents: target not found in this org")
|
||||
}
|
||||
return "", fmt.Errorf("agents: resolve target: %w", err)
|
||||
}
|
||||
id, err := OpenSession(ctx, org, actor, agent, title)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Stamp the target onto the freshly-opened row (org-scoped update); a failure
|
||||
// here is non-fatal — the session is live, it simply lacks its machine tag.
|
||||
if x, gerr := mounted.State.store.GetSession(ctx, org, id); gerr == nil {
|
||||
x.Target = target
|
||||
x.UpdatedAt = time.Now().Unix()
|
||||
_ = mounted.State.store.UpdateSession(ctx, x)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// LogSessionEvent appends one ordered event (message|tool-call|spawn|log|status|
|
||||
// control) to an org's session and fans it out live. The (org, id) pair is
|
||||
// re-resolved so a caller can only write to a session THIS org owns; kind is
|
||||
|
||||
@@ -114,3 +114,50 @@ func TestInproc_NotMounted_FailsClosed(t *testing.T) {
|
||||
t.Fatal("unmounted OpenSession must fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveTarget turns a human's reference (id or friendly label) into the org's
|
||||
// target, org-scoped and fail-closed: an id wins, else an exact case-folded label,
|
||||
// and a reference matching neither — or another org's machine — is not found.
|
||||
func TestResolveTarget_IdThenLabel_OrgScoped(t *testing.T) {
|
||||
mountInproc(t)
|
||||
ctx := context.Background()
|
||||
now := int64(1000)
|
||||
acme := Target{ID: "tgt_acme1", Org: "acme", Label: "evo", Kind: TargetGPU, Status: TargetOnline, Host: "evo", CreatedAt: now, UpdatedAt: now}
|
||||
evil := Target{ID: "tgt_evil1", Org: "evil", Label: "evo", Kind: TargetGPU, Status: TargetOnline, Host: "evo", CreatedAt: now, UpdatedAt: now}
|
||||
if err := mounted.State.store.CreateTarget(ctx, acme); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mounted.State.store.CreateTarget(ctx, evil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// By id.
|
||||
if got, err := ResolveTarget(ctx, "acme", "tgt_acme1"); err != nil || got.ID != "tgt_acme1" {
|
||||
t.Fatalf("resolve by id: %+v %v", got, err)
|
||||
}
|
||||
// By label (case-folded), scoped to the caller's org — never evil's same-labelled box.
|
||||
if got, err := ResolveTarget(ctx, "acme", "EVO"); err != nil || got.ID != "tgt_acme1" {
|
||||
t.Fatalf("resolve by label must find acme's own, got %+v %v", got, err)
|
||||
}
|
||||
// Another org's id is not found (no cross-tenant leak).
|
||||
if _, err := ResolveTarget(ctx, "acme", "tgt_evil1"); err != errTargetNotFound {
|
||||
t.Fatalf("cross-org id must be not-found, got %v", err)
|
||||
}
|
||||
// An unknown reference is not found — the caller renders an honest error.
|
||||
if _, err := ResolveTarget(ctx, "acme", "nope"); err != errTargetNotFound {
|
||||
t.Fatalf("unknown ref must be not-found, got %v", err)
|
||||
}
|
||||
// Empty ref is not found (never resolves to "some" machine).
|
||||
if _, err := ResolveTarget(ctx, "acme", ""); err != errTargetNotFound {
|
||||
t.Fatalf("empty ref must be not-found, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTarget_NotMounted_FailsClosed(t *testing.T) {
|
||||
prev := mounted
|
||||
mounted = nil
|
||||
t.Cleanup(func() { mounted = prev })
|
||||
if _, err := ResolveTarget(context.Background(), "acme", "evo"); err == nil {
|
||||
t.Fatal("unmounted ResolveTarget must fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
luxlog "github.com/luxfi/log"
|
||||
)
|
||||
|
||||
// mailbox.go is the LIVE hand-off between a routed run's durable owner (the
|
||||
// coding RoutedRunWorkflow, running on the embedded tasks engine) and the
|
||||
// external machine that claims and executes it over HTTP. It is the rendezvous
|
||||
// ONLY — never the durable queue. The tasks engine is the queue of record: it
|
||||
// survives a cloud restart, times a never-claimed run out, and retries. On every
|
||||
// (re)start of the delivery activity the run is (re-)Offered here, so a machine
|
||||
// that long-polls Claim always finds work the engine still owns; a cloud restart
|
||||
// simply re-populates the mailbox from durable history.
|
||||
//
|
||||
// ISOLATION IS STRUCTURAL. Every offer is filed under the key (org, target), and
|
||||
// Claim/Report only ever touch that one key's slot. A run offered for (orgB,
|
||||
// targetY) is unreachable from a Claim or Report for (orgA, targetX) — the tenant
|
||||
// + machine boundary is a property of the map key, not a check a caller can skip.
|
||||
|
||||
// RoutedRun is the NON-SECRET spec of one coding run dispatched to a target. It
|
||||
// carries no credential by design: the executing machine authenticates git +
|
||||
// model routing with its OWN already-held credentials (the same ones `hanzo code`
|
||||
// uses), so no secret ever enters the durable store or crosses to the machine in
|
||||
// the claim response. Everything here is safe to persist in the tasks engine.
|
||||
type RoutedRun struct {
|
||||
Org string `json:"org"`
|
||||
TargetID string `json:"targetId"`
|
||||
SessionID string `json:"sessionId"` // the live session opened at dispatch; the machine streams into it
|
||||
Repo string `json:"repo"`
|
||||
Project string `json:"project,omitempty"`
|
||||
Base string `json:"base,omitempty"`
|
||||
Branch string `json:"branch"`
|
||||
Prompt string `json:"prompt"`
|
||||
CloneURL string `json:"cloneUrl"`
|
||||
TimeoutSeconds int `json:"timeoutSeconds,omitempty"`
|
||||
// Actor + AgentRef are CLOUD-SIDE attribution for the completion path (session
|
||||
// close + PR assignee). They are NOT part of routedRunView, so they never cross
|
||||
// to the executing machine — the machine needs neither.
|
||||
Actor string `json:"actor,omitempty"`
|
||||
AgentRef string `json:"agentRef,omitempty"`
|
||||
}
|
||||
|
||||
// RoutedResult is a routed run's terminal outcome, reported by the machine and
|
||||
// returned to the durable activity so the workflow completes.
|
||||
type RoutedResult struct {
|
||||
OK bool `json:"ok"`
|
||||
Changed bool `json:"changed"`
|
||||
Branch string `json:"branch,omitempty"`
|
||||
CommitSha string `json:"commitSha,omitempty"`
|
||||
Diffstat string `json:"diffstat,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// offer is one run waiting to be claimed, plus the channel its durable owner
|
||||
// blocks on for the terminal result. result is buffered(1) so Report never blocks
|
||||
// even if the owner is between selects; closed fires when the offer is finished
|
||||
// (reported OR abandoned) so a waiter always unblocks.
|
||||
type offer struct {
|
||||
mb *mailbox
|
||||
key string // (org,target)
|
||||
rk string // (org,target,sessionID)
|
||||
run RoutedRun
|
||||
result chan RoutedResult
|
||||
closed chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// Await blocks until the machine reports this run's result, the offer is
|
||||
// abandoned, or ctx (the activity's StartToClose budget) fires. It is the
|
||||
// durable owner's half of the rendezvous.
|
||||
func (o *offer) Await(ctx context.Context) (RoutedResult, bool) {
|
||||
select {
|
||||
case res := <-o.result:
|
||||
return res, true
|
||||
case <-o.closed:
|
||||
// Abandoned or reported-then-closed: drain a delivered result if one raced in.
|
||||
select {
|
||||
case res := <-o.result:
|
||||
return res, true
|
||||
default:
|
||||
return RoutedResult{}, false
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return RoutedResult{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// Close removes the offer from the mailbox (if still present) and unblocks any
|
||||
// waiter. Idempotent — the durable owner defers it so a timed-out or crashed
|
||||
// delivery never leaks a queued or claimed offer.
|
||||
func (o *offer) Close() { o.mb.discard(o) }
|
||||
|
||||
// mailbox is the process-wide rendezvous. queues holds each key's FIFO of
|
||||
// unclaimed offers; byRun indexes every live offer by (org,target,sessionID) for
|
||||
// Report + re-offer dedupe; signal is a per-key broadcast channel (closed and
|
||||
// recreated on Offer) that Claim waits on.
|
||||
type mailbox struct {
|
||||
mu sync.Mutex
|
||||
queues map[string][]*offer
|
||||
byRun map[string]*offer
|
||||
signal map[string]chan struct{}
|
||||
// inflight is the per-org set of live routed sessions (offered, not yet finished),
|
||||
// the gauge the per-org admission cap reads. A SET keyed by session id (not a bare
|
||||
// counter) so a re-offer after a restart re-adds idempotently and a superseded
|
||||
// offer never double-counts or wrongly decrements the still-live session.
|
||||
inflight map[string]map[string]struct{}
|
||||
}
|
||||
|
||||
func newMailbox() *mailbox {
|
||||
return &mailbox{
|
||||
queues: map[string][]*offer{},
|
||||
byRun: map[string]*offer{},
|
||||
signal: map[string]chan struct{}{},
|
||||
inflight: map[string]map[string]struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mailbox) inflightAddLocked(org, sess string) {
|
||||
s := m.inflight[org]
|
||||
if s == nil {
|
||||
s = map[string]struct{}{}
|
||||
m.inflight[org] = s
|
||||
}
|
||||
s[sess] = struct{}{}
|
||||
}
|
||||
|
||||
func (m *mailbox) inflightRemoveLocked(org, sess string) {
|
||||
if s := m.inflight[org]; s != nil {
|
||||
delete(s, sess)
|
||||
if len(s) == 0 {
|
||||
delete(m.inflight, org)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// InFlight returns how many routed runs an org has live (offered, not yet finished).
|
||||
func (m *mailbox) InFlight(org string) int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return len(m.inflight[org])
|
||||
}
|
||||
|
||||
// routedMailbox is the ONE process-wide rendezvous, shared by the coding
|
||||
// delivery activity (Offer/Await) and the machine-facing HTTP surface
|
||||
// (Claim/Report). One mailbox, one way.
|
||||
//
|
||||
// SINGLE-REPLICA DEPENDENCY (accepted, inherited). This rendezvous is IN-PROCESS: the
|
||||
// durable delivery activity (Offer/Await, on whichever replica's tasks worker polls
|
||||
// the agent-routed queue) and the external machine's POST /claim (ingress load-
|
||||
// balanced to any replica) must land on the SAME process, because the mailbox is a
|
||||
// package global, not a shared broker. cloud already runs HARD single-replica —
|
||||
// Recreate, replicas:1 — because the embedded Badger KMS holds an exclusive file lock
|
||||
// and the audit sequence is an in-memory counter (infra/k8s/operator/crs/cloud.yaml),
|
||||
// so route-work INHERITS that guarantee for free and needs no broker. assertSingleReplica
|
||||
// logs the assumption at mount and warns loudly if a multi-replica signal is present.
|
||||
//
|
||||
// IF cloud is ever made multi-replica (the KMS lock lifted): this rendezvous MUST
|
||||
// become replica-aware — either a sticky route that pins a target's /claim to the
|
||||
// replica whose worker owns its delivery, or a shared broker (the embedded NATS/
|
||||
// JetStream already in-process, keyed by (org,target)) so Offer and Claim meet
|
||||
// regardless of which replica each hits. Until then, single-replica is the contract.
|
||||
var routedMailbox = newMailbox()
|
||||
|
||||
// assertSingleReplica records the single-replica assumption the process-global
|
||||
// rendezvous depends on, and warns LOUDLY if a multi-replica signal is detectable
|
||||
// (CLOUD_REPLICAS > 1). It does not fail mount — cloud's replicas:1 is enforced by the
|
||||
// deployment (the KMS lock), so this is a defensive breadcrumb for the day that
|
||||
// changes, not a runtime gate. Called once from mountRouting.
|
||||
func assertSingleReplica(log luxlog.Logger) {
|
||||
if log == nil {
|
||||
return
|
||||
}
|
||||
replicas := 1
|
||||
if v := strings.TrimSpace(os.Getenv("CLOUD_REPLICAS")); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
replicas = n
|
||||
}
|
||||
}
|
||||
if replicas > 1 {
|
||||
log.Warn("route-work: the routed-run rendezvous is process-global and REQUIRES cloud to run single-replica, but CLOUD_REPLICAS>1 — routed /claim will silently fail on a replica that does not own the delivery. Make the rendezvous replica-aware (sticky target route or shared broker) before scaling out.",
|
||||
"replicas", replicas)
|
||||
return
|
||||
}
|
||||
log.Info("route-work: routed-run rendezvous is in-process; assumes cloud single-replica (inherited from the KMS exclusive lock)")
|
||||
}
|
||||
|
||||
func mbKey(org, target string) string { return org + "\x00" + target }
|
||||
func runKey(org, target, sess string) string { return org + "\x00" + target + "\x00" + sess }
|
||||
|
||||
// Offer files run for its (org,target) and returns the handle its durable owner
|
||||
// awaits. A re-offer of the same (org,target,sessionID) — the workflow retrying
|
||||
// or replaying after a restart — supersedes the stale prior offer (removing it
|
||||
// from the queue and unblocking its dead waiter) so a machine never claims a run
|
||||
// whose owner has already moved on.
|
||||
func (m *mailbox) Offer(run RoutedRun) *offer {
|
||||
key := mbKey(run.Org, run.TargetID)
|
||||
rk := runKey(run.Org, run.TargetID, run.SessionID)
|
||||
o := &offer{mb: m, key: key, rk: rk, run: run, result: make(chan RoutedResult, 1), closed: make(chan struct{})}
|
||||
m.mu.Lock()
|
||||
if prev := m.byRun[rk]; prev != nil {
|
||||
m.removeFromQueueLocked(key, prev)
|
||||
prev.finish()
|
||||
}
|
||||
m.byRun[rk] = o
|
||||
m.queues[key] = append(m.queues[key], o)
|
||||
m.broadcastLocked(key)
|
||||
m.mu.Unlock()
|
||||
return o
|
||||
}
|
||||
|
||||
// Claim blocks until an unclaimed run exists for (org,target) or ctx fires,
|
||||
// returning the oldest. The claimed offer leaves the queue but stays in byRun,
|
||||
// awaiting Report. Only this key's queue is ever read, so a claim can never
|
||||
// surface another tenant's or another machine's run.
|
||||
func (m *mailbox) Claim(ctx context.Context, org, target string) (RoutedRun, bool) {
|
||||
key := mbKey(org, target)
|
||||
for {
|
||||
m.mu.Lock()
|
||||
if q := m.queues[key]; len(q) > 0 {
|
||||
o := q[0]
|
||||
m.queues[key] = q[1:]
|
||||
m.mu.Unlock()
|
||||
return o.run, true
|
||||
}
|
||||
sig := m.signalLocked(key)
|
||||
m.mu.Unlock()
|
||||
select {
|
||||
case <-sig:
|
||||
// a new offer (or a superseding one) arrived — re-check
|
||||
case <-ctx.Done():
|
||||
return RoutedRun{}, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Report delivers a terminal result to the run's durable owner. Scoped to
|
||||
// (org,target,sessionID): a report can only ever complete a run that exact key
|
||||
// owns, so one machine can never report on behalf of another. Returns false when
|
||||
// no live offer matches (already reported, abandoned, or never existed).
|
||||
func (m *mailbox) Report(org, target, sess string, res RoutedResult) bool {
|
||||
rk := runKey(org, target, sess)
|
||||
m.mu.Lock()
|
||||
o := m.byRun[rk]
|
||||
if o == nil {
|
||||
m.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
delete(m.byRun, rk)
|
||||
m.removeFromQueueLocked(mbKey(org, target), o)
|
||||
m.mu.Unlock()
|
||||
o.deliver(res)
|
||||
return true
|
||||
}
|
||||
|
||||
// discard drops an offer the owner is done with (ctx timeout / crash / normal
|
||||
// close) so neither the queue nor byRun retains it.
|
||||
func (m *mailbox) discard(o *offer) {
|
||||
m.mu.Lock()
|
||||
if m.byRun[o.rk] == o {
|
||||
delete(m.byRun, o.rk)
|
||||
}
|
||||
m.removeFromQueueLocked(o.key, o)
|
||||
m.mu.Unlock()
|
||||
o.finish()
|
||||
}
|
||||
|
||||
func (m *mailbox) removeFromQueueLocked(key string, o *offer) {
|
||||
q := m.queues[key]
|
||||
for i, e := range q {
|
||||
if e == o {
|
||||
m.queues[key] = append(q[:i:i], q[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// broadcastLocked wakes every Claim waiting on key by closing its signal channel;
|
||||
// a fresh channel replaces it for the next wait.
|
||||
func (m *mailbox) broadcastLocked(key string) {
|
||||
if ch, ok := m.signal[key]; ok {
|
||||
close(ch)
|
||||
delete(m.signal, key)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mailbox) signalLocked(key string) chan struct{} {
|
||||
ch, ok := m.signal[key]
|
||||
if !ok {
|
||||
ch = make(chan struct{})
|
||||
m.signal[key] = ch
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
func (o *offer) deliver(res RoutedResult) {
|
||||
o.once.Do(func() {
|
||||
o.result <- res // buffered(1) — never blocks
|
||||
close(o.closed)
|
||||
})
|
||||
}
|
||||
|
||||
func (o *offer) finish() {
|
||||
o.once.Do(func() { close(o.closed) })
|
||||
}
|
||||
|
||||
// OfferRoutedRun is the exported seam the coding delivery activity uses to place
|
||||
// a run into the live rendezvous. Kept here (agents owns targets + sessions) so
|
||||
// the machine-facing HTTP surface and the durable activity share ONE mailbox.
|
||||
func OfferRoutedRun(run RoutedRun) *offer { return routedMailbox.Offer(run) }
|
||||
@@ -0,0 +1,166 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mkRun(org, target, sess string) RoutedRun {
|
||||
return RoutedRun{Org: org, TargetID: target, SessionID: sess, Repo: "api", Branch: "agent/" + sess}
|
||||
}
|
||||
|
||||
// A claimed run comes back to exactly one claimer, then its report reaches the
|
||||
// offerer that is awaiting it.
|
||||
func TestMailbox_OfferClaimReport(t *testing.T) {
|
||||
m := newMailbox()
|
||||
off := m.Offer(mkRun("acme", "tgt_1", "sess_1"))
|
||||
|
||||
got, ok := m.Claim(context.Background(), "acme", "tgt_1")
|
||||
if !ok || got.SessionID != "sess_1" {
|
||||
t.Fatalf("claim wrong: ok=%v run=%+v", ok, got)
|
||||
}
|
||||
|
||||
done := make(chan RoutedResult, 1)
|
||||
go func() {
|
||||
res, _ := off.Await(context.Background())
|
||||
done <- res
|
||||
}()
|
||||
if !m.Report("acme", "tgt_1", "sess_1", RoutedResult{OK: true, CommitSha: "abc"}) {
|
||||
t.Fatal("report should deliver to the awaiting offer")
|
||||
}
|
||||
select {
|
||||
case res := <-done:
|
||||
if !res.OK || res.CommitSha != "abc" {
|
||||
t.Fatalf("await got wrong result: %+v", res)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("await never received the reported result")
|
||||
}
|
||||
}
|
||||
|
||||
// THE tenant + machine boundary: a claim for (org,target) can NEVER surface a run
|
||||
// offered for a different org OR a different target — it is a property of the key.
|
||||
func TestMailbox_CrossTenantAndCrossMachineIsolation(t *testing.T) {
|
||||
m := newMailbox()
|
||||
m.Offer(mkRun("orgB", "tgt_Y", "sess_foreign_org"))
|
||||
m.Offer(mkRun("acme", "tgt_Y", "sess_foreign_machine"))
|
||||
m.Offer(mkRun("acme", "tgt_X", "sess_mine"))
|
||||
|
||||
// A claim for (acme, tgt_X) gets ONLY acme/tgt_X's run.
|
||||
got, ok := m.Claim(context.Background(), "acme", "tgt_X")
|
||||
if !ok || got.SessionID != "sess_mine" {
|
||||
t.Fatalf("claim leaked across a boundary: ok=%v run=%+v", ok, got)
|
||||
}
|
||||
// And that queue is now empty — no foreign run fell through.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, ok := m.Claim(ctx, "acme", "tgt_X"); ok {
|
||||
t.Fatal("a foreign run must never be claimable as acme/tgt_X")
|
||||
}
|
||||
|
||||
// A Report can only complete a run under its exact key: reporting the foreign
|
||||
// machine's session under tgt_X does nothing.
|
||||
if m.Report("acme", "tgt_X", "sess_foreign_machine", RoutedResult{OK: true}) {
|
||||
t.Fatal("report crossed the machine boundary")
|
||||
}
|
||||
if m.Report("acme", "tgt_Y", "sess_foreign_org", RoutedResult{OK: true}) {
|
||||
t.Fatal("report crossed the org boundary")
|
||||
}
|
||||
}
|
||||
|
||||
// Two racing claimers, one run: exactly one wins.
|
||||
func TestMailbox_NoDoubleClaim(t *testing.T) {
|
||||
m := newMailbox()
|
||||
m.Offer(mkRun("acme", "tgt_1", "sess_1"))
|
||||
|
||||
var wins int
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, ok := m.Claim(ctx, "acme", "tgt_1"); ok {
|
||||
mu.Lock()
|
||||
wins++
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if wins != 1 {
|
||||
t.Fatalf("exactly one claimer must win, got %d", wins)
|
||||
}
|
||||
}
|
||||
|
||||
// A claim with no work times out on ctx and reports no run — fail closed, never hang.
|
||||
func TestMailbox_ClaimTimesOut(t *testing.T) {
|
||||
m := newMailbox()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, ok := m.Claim(ctx, "acme", "tgt_empty"); ok {
|
||||
t.Fatal("an empty mailbox must not yield a run")
|
||||
}
|
||||
}
|
||||
|
||||
// The durable owner's Await unblocks (fail-closed) when its budget ctx fires with
|
||||
// no report — the machine never claimed, or claimed and died.
|
||||
func TestMailbox_AwaitFailsClosedOnDeadline(t *testing.T) {
|
||||
m := newMailbox()
|
||||
off := m.Offer(mkRun("acme", "tgt_1", "sess_1"))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, ok := off.Await(ctx); ok {
|
||||
t.Fatal("await must fail closed when the deadline fires without a report")
|
||||
}
|
||||
}
|
||||
|
||||
// A re-offer of the same run (workflow retry / cloud restart) supersedes the stale
|
||||
// offer: the old waiter unblocks abandoned, and the fresh run is claimable.
|
||||
func TestMailbox_ReOfferSupersedes(t *testing.T) {
|
||||
m := newMailbox()
|
||||
old := m.Offer(mkRun("acme", "tgt_1", "sess_1"))
|
||||
|
||||
// re-offer BEFORE anyone claims the first
|
||||
fresh := m.Offer(mkRun("acme", "tgt_1", "sess_1"))
|
||||
|
||||
// old is abandoned
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if _, ok := old.Await(ctx); ok {
|
||||
t.Fatal("the superseded offer must not complete")
|
||||
}
|
||||
|
||||
// exactly one claimable run remains, and reporting reaches the fresh offer
|
||||
got, ok := m.Claim(context.Background(), "acme", "tgt_1")
|
||||
if !ok || got.SessionID != "sess_1" {
|
||||
t.Fatalf("fresh run not claimable: %+v", got)
|
||||
}
|
||||
if _, ok := m.Claim(ctxShort(), "acme", "tgt_1"); ok {
|
||||
t.Fatal("the stale offer must not have left a duplicate in the queue")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { fresh.Await(context.Background()); close(done) }()
|
||||
if !m.Report("acme", "tgt_1", "sess_1", RoutedResult{OK: true}) {
|
||||
t.Fatal("report must reach the fresh offer")
|
||||
}
|
||||
<-done
|
||||
}
|
||||
|
||||
// Report for an unknown/already-finished run is a clean false.
|
||||
func TestMailbox_ReportUnknownIsNoOp(t *testing.T) {
|
||||
m := newMailbox()
|
||||
if m.Report("acme", "tgt_1", "nope", RoutedResult{OK: true}) {
|
||||
t.Fatal("report for an unknown run must be a no-op")
|
||||
}
|
||||
}
|
||||
|
||||
func ctxShort() context.Context {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond)
|
||||
_ = cancel
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// personalities.go seeds an org's BUILT-IN agents — the named personas a human
|
||||
// @-mentions in Hanzo Team (@dev to build, @des to design, @vi for vision). They
|
||||
// are ordinary rows in the ONE agent registry (this package's store): nothing
|
||||
// about them is special-cased downstream — they list, project into Team as bot
|
||||
// members (bots.go), and answer through the SAME agents.RunOnBehalf path every
|
||||
// other agent uses. The only thing this file adds is a one-time, idempotent
|
||||
// create so a fresh org has its crew without anyone POSTing them by hand.
|
||||
//
|
||||
// One and only one seed: keyed by the registry's UNIQUE(org,name), a re-seed is a
|
||||
// no-op (errConflict is swallowed). The Name is the @-handle (dev/des/vi), so the
|
||||
// Team mention resolves to the persona; Description is the human-facing title.
|
||||
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// persona is one built-in agent definition. Name is the lowercase @-handle;
|
||||
// Description is the display title; Instructions is the system prompt that gives
|
||||
// the persona its voice and remit.
|
||||
type persona struct {
|
||||
Name string
|
||||
Description string
|
||||
Instructions string
|
||||
}
|
||||
|
||||
// personalities is the canonical built-in crew. Adding one here is the ONE way a
|
||||
// new default persona ships — no per-org config, no duplicate definition. The old
|
||||
// hanzo.ai site's voices, brought into Team.
|
||||
var personalities = []persona{
|
||||
{
|
||||
Name: "dev",
|
||||
Description: "Dev — the builder",
|
||||
Instructions: "You are Dev, Hanzo's builder. You ship. When a human @-mentions you " +
|
||||
"you write the code, wire the change, and report what you did in plain terms — " +
|
||||
"file paths, commands, results. You prize the smallest correct change, one and " +
|
||||
"only one way to do a thing, and no ceremony. You never hand-wave: if you built " +
|
||||
"it you say so with proof; if you're blocked you name the blocker. Terse, exact, " +
|
||||
"and always moving toward a finished, working solution.",
|
||||
},
|
||||
{
|
||||
Name: "des",
|
||||
Description: "Des — the designer",
|
||||
Instructions: "You are Des, Hanzo's designer. You own how it looks and feels — layout, " +
|
||||
"type, color, motion, the whole experience. When a human @-mentions you, you " +
|
||||
"think in systems, not one-off screens: a token, a component, a consistent rule " +
|
||||
"that reads as one product in light and dark. You give concrete, buildable design " +
|
||||
"direction (spacing, hierarchy, states), not vague taste. Elegant, accessible, and " +
|
||||
"opinionated — you make the obvious thing beautiful.",
|
||||
},
|
||||
{
|
||||
Name: "vi",
|
||||
Description: "Vi — the visionary",
|
||||
Instructions: "You are Vi, Hanzo's visionary lead. You hold the big picture and the long " +
|
||||
"arc — where the product is going, why it matters, and what to do next to get there. " +
|
||||
"When a human @-mentions you, you connect the dots across the org, cut through noise " +
|
||||
"to the one thing that matters, and rally the crew around it. You think in bets and " +
|
||||
"outcomes, name the strategy plainly, and turn a sprawling ask into a sharp, " +
|
||||
"sequenced plan. Inspiring, decisive, and grounded in what actually ships.",
|
||||
},
|
||||
}
|
||||
|
||||
// SeedPersonalities ensures the built-in crew exists for org. Idempotent: an
|
||||
// already-present persona (UNIQUE org+name) is left untouched, so it is safe to
|
||||
// call on every org first-touch (a new Team workspace, say). Returns the number
|
||||
// newly created.
|
||||
//
|
||||
// It needs a model to attach — the deployment's configured default. With no
|
||||
// default model, seeding is a NO-OP (0, nil): an org gets its crew the moment the
|
||||
// binary has a model to run them on, never a half-created persona that can't run.
|
||||
// A subsystem that is not mounted also no-ops rather than erroring, so a caller on
|
||||
// the login path can call it best-effort without ever blocking a human.
|
||||
func SeedPersonalities(ctx context.Context, org string) (int, error) {
|
||||
if mounted == nil || mounted.State.store == nil {
|
||||
return 0, nil
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
if org == "" {
|
||||
return 0, nil
|
||||
}
|
||||
model := strings.TrimSpace(mounted.State.defaultModel)
|
||||
if model == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
created := 0
|
||||
now := time.Now().Unix()
|
||||
for _, p := range personalities {
|
||||
id, err := genID("agent")
|
||||
if err != nil {
|
||||
return created, err
|
||||
}
|
||||
a := Agent{
|
||||
ID: id,
|
||||
Org: org,
|
||||
Name: p.Name,
|
||||
Model: model,
|
||||
Instructions: p.Instructions,
|
||||
Description: p.Description,
|
||||
Status: "ready",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
err = mounted.State.store.Create(ctx, a)
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, errConflict):
|
||||
// Already seeded — the one-way idempotent no-op.
|
||||
default:
|
||||
return created, err
|
||||
}
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
luxlog "github.com/luxfi/log"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
)
|
||||
|
||||
// mountSeedTest wires the `mounted` singleton to a fresh store with a default
|
||||
// model, so SeedPersonalities has both a store to write and a model to attach.
|
||||
func mountSeedTest(t *testing.T, defaultModel string) {
|
||||
t.Helper()
|
||||
prev := mounted
|
||||
mounted = &cloud.Service[state]{
|
||||
Base: cloud.Base{Log: luxlog.New("test")},
|
||||
State: state{store: testStore(t), defaultModel: defaultModel},
|
||||
}
|
||||
t.Cleanup(func() { mounted = prev })
|
||||
}
|
||||
|
||||
// TestSeedPersonalities proves the built-in crew is created once, is idempotent,
|
||||
// projects the exact @-handles a human mentions in Team, and no-ops without a
|
||||
// model — the full contract of the one-way seed.
|
||||
func TestSeedPersonalities(t *testing.T) {
|
||||
mountSeedTest(t, "zen-1")
|
||||
ctx := context.Background()
|
||||
const org = "acme"
|
||||
|
||||
// First seed creates the whole crew.
|
||||
n, err := SeedPersonalities(ctx, org)
|
||||
if err != nil {
|
||||
t.Fatalf("SeedPersonalities: %v", err)
|
||||
}
|
||||
if n != len(personalities) {
|
||||
t.Fatalf("created %d, want %d (the full built-in crew)", n, len(personalities))
|
||||
}
|
||||
|
||||
// They are ordinary registry rows — ListForOrg returns them with the @-handles.
|
||||
list, err := ListForOrg(ctx, org)
|
||||
if err != nil {
|
||||
t.Fatalf("ListForOrg: %v", err)
|
||||
}
|
||||
got := map[string]Agent{}
|
||||
for _, a := range list {
|
||||
got[a.Name] = a
|
||||
}
|
||||
for _, want := range []string{"dev", "des", "vi"} {
|
||||
a, ok := got[want]
|
||||
if !ok {
|
||||
t.Fatalf("@%s not seeded; have %v", want, keysOf(got))
|
||||
}
|
||||
if a.Model != "zen-1" || a.Status != "ready" || a.Instructions == "" {
|
||||
t.Fatalf("@%s malformed: model=%q status=%q instr=%dB", want, a.Model, a.Status, len(a.Instructions))
|
||||
}
|
||||
}
|
||||
|
||||
// Idempotent: a re-seed creates nothing and never duplicates.
|
||||
n2, err := SeedPersonalities(ctx, org)
|
||||
if err != nil {
|
||||
t.Fatalf("re-seed: %v", err)
|
||||
}
|
||||
if n2 != 0 {
|
||||
t.Fatalf("re-seed created %d, want 0 (idempotent)", n2)
|
||||
}
|
||||
if list2, _ := ListForOrg(ctx, org); len(list2) != len(personalities) {
|
||||
t.Fatalf("after re-seed: %d agents, want %d (no dup)", len(list2), len(personalities))
|
||||
}
|
||||
|
||||
// No default model → no-op, never a half-seeded org.
|
||||
mountSeedTest(t, "")
|
||||
if n3, err := SeedPersonalities(ctx, "globex"); err != nil || n3 != 0 {
|
||||
t.Fatalf("no-model seed = (%d,%v), want (0,nil)", n3, err)
|
||||
}
|
||||
}
|
||||
|
||||
func keysOf(m map[string]Agent) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/hanzoai/cloud/types"
|
||||
)
|
||||
|
||||
// scriptedAI is a deterministic AIClient that models a throttled gateway: a call
|
||||
// whose model still has "busy budget" (or when allBusy is set) returns a
|
||||
// transient ErrUpstreamBusy-tagged error — exactly the shape the real httpAI
|
||||
// produces for a 429 / "Platform overloaded" — otherwise it returns content. It
|
||||
// records every call + model so a test can assert the retry count and which model
|
||||
// finally answered. It does NOT implement types.ModelLister, so create fails open
|
||||
// (any model is accepted without a catalog round-trip).
|
||||
type scriptedAI struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
models []string
|
||||
busy map[string]int // model -> remaining transient failures before it succeeds
|
||||
allBusy bool // every call fails transiently (failover can never win)
|
||||
content string
|
||||
}
|
||||
|
||||
func (s *scriptedAI) ChatCompletion(_ context.Context, req *types.ChatRequest) (*types.ChatResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.calls++
|
||||
s.models = append(s.models, req.Model)
|
||||
if s.allBusy {
|
||||
return nil, fmt.Errorf("429 Platform overloaded: %w", types.ErrUpstreamBusy)
|
||||
}
|
||||
if n := s.busy[req.Model]; n > 0 {
|
||||
s.busy[req.Model] = n - 1
|
||||
return nil, fmt.Errorf("429 Platform overloaded: %w", types.ErrUpstreamBusy)
|
||||
}
|
||||
return &types.ChatResponse{Content: s.content}, nil
|
||||
}
|
||||
|
||||
func (s *scriptedAI) Embed(context.Context, *types.EmbedRequest) ([][]float32, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *scriptedAI) callCount() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.calls
|
||||
}
|
||||
|
||||
func (s *scriptedAI) modelsSeen() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.models...)
|
||||
}
|
||||
|
||||
// TestRunRetriesTransientThenSucceedsBillsOnce is the core reliability contract:
|
||||
// a gateway that 429s TWICE then answers must yield ONE successful run and EXACTLY
|
||||
// ONE debit — not a dropped reply (the old single-shot behavior), and not three
|
||||
// debits (retries must never bill the failed attempts; only the final success
|
||||
// bills, once).
|
||||
func TestRunRetriesTransientThenSucceedsBillsOnce(t *testing.T) {
|
||||
bs := &billServer{available: 100000}
|
||||
ai := &scriptedAI{content: "recovered", busy: map[string]int{"gpt-4o-mini": 2}}
|
||||
app := mountBilled(t, bs.start(t), ai)
|
||||
|
||||
do(t, app, http.MethodPost, "/v1/agents", "acme",
|
||||
map[string]any{"name": "a", "model": "gpt-4o-mini", "instructions": "x"})
|
||||
code, body := do(t, app, http.MethodPost, "/v1/agents/a/run", "acme", map[string]any{"input": "hi"})
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("run that recovers after 2 retries want 200, got %d (%s)", code, body)
|
||||
}
|
||||
// The reply must be the recovered content — not dropped.
|
||||
var rv runView
|
||||
_ = json.Unmarshal(body, &rv)
|
||||
if rv.Output != "recovered" {
|
||||
t.Fatalf("reply must carry the recovered output, got %q", rv.Output)
|
||||
}
|
||||
if got := ai.callCount(); got != 3 {
|
||||
t.Fatalf("want 3 completion attempts (2 busy + 1 ok), got %d", got)
|
||||
}
|
||||
// Exactly one debit for the single eventual success — never one-per-attempt.
|
||||
if !waitForDebit(func() bool { return bs.debits() == 1 }) {
|
||||
t.Fatalf("a retried-then-succeeded run must debit exactly once, got %d", bs.debits())
|
||||
}
|
||||
// Give any erroneous extra debit a chance to land; assert it did not.
|
||||
if bs.debits() != 1 {
|
||||
t.Fatalf("retries must not bill failed attempts: want 1 debit, got %d", bs.debits())
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunFailsOverToReliableModelAndBillsIt proves the escalation: the agent's
|
||||
// own model stays throttled through all its retries, so the run fails over to the
|
||||
// configured reliable model ("best"), still lands a reply, and bills the model
|
||||
// ACTUALLY used (best) — not the throttled one it started on.
|
||||
func TestRunFailsOverToReliableModelAndBillsIt(t *testing.T) {
|
||||
bs := &billServer{available: 100000}
|
||||
// gpt-4o-mini is busy for MORE than its retry budget (never recovers); "best"
|
||||
// answers first try.
|
||||
ai := &scriptedAI{content: "from-best", busy: map[string]int{"gpt-4o-mini": 99}}
|
||||
app := mountBilled(t, bs.start(t), ai)
|
||||
|
||||
do(t, app, http.MethodPost, "/v1/agents", "acme",
|
||||
map[string]any{"name": "a", "model": "gpt-4o-mini", "instructions": "x"})
|
||||
code, body := do(t, app, http.MethodPost, "/v1/agents/a/run", "acme", map[string]any{"input": "hi"})
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("failover run want 200, got %d (%s)", code, body)
|
||||
}
|
||||
var rv runView
|
||||
_ = json.Unmarshal(body, &rv)
|
||||
if rv.Output != "from-best" {
|
||||
t.Fatalf("failover reply must come from the reliable model, got %q", rv.Output)
|
||||
}
|
||||
// Primary exhausted its retries, then exactly one failover attempt on "best".
|
||||
if got := ai.callCount(); got != maxAttempts+1 {
|
||||
t.Fatalf("want %d attempts (primary exhausted + 1 failover), got %d", maxAttempts+1, got)
|
||||
}
|
||||
seen := ai.modelsSeen()
|
||||
if seen[len(seen)-1] != "best" {
|
||||
t.Fatalf("the final attempt must be the failover model, got %q", seen[len(seen)-1])
|
||||
}
|
||||
if !waitForDebit(func() bool { return bs.debits() == 1 }) {
|
||||
t.Fatalf("a failover run must debit exactly once, got %d", bs.debits())
|
||||
}
|
||||
_, ubody := bs.lastDebit()
|
||||
var u struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
_ = json.Unmarshal(ubody, &u)
|
||||
if u.Model != "best" {
|
||||
t.Fatalf("failover run must bill the model actually used (best), got %q", u.Model)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunAllAttemptsBusyExhaustedNoDebit proves the failure contract: when EVERY
|
||||
// attempt on BOTH the agent's model and the failover model is throttled, the run
|
||||
// records a clean error (502) and NOTHING is billed — a persistent overload never
|
||||
// costs the tenant, and never fabricates a reply.
|
||||
func TestRunAllAttemptsBusyExhaustedNoDebit(t *testing.T) {
|
||||
bs := &billServer{available: 100000}
|
||||
ai := &scriptedAI{allBusy: true}
|
||||
app := mountBilled(t, bs.start(t), ai)
|
||||
|
||||
do(t, app, http.MethodPost, "/v1/agents", "acme",
|
||||
map[string]any{"name": "a", "model": "gpt-4o-mini", "instructions": "x"})
|
||||
code, _ := do(t, app, http.MethodPost, "/v1/agents/a/run", "acme", map[string]any{"input": "hi"})
|
||||
if code != http.StatusBadGateway {
|
||||
t.Fatalf("exhausted run want 502, got %d", code)
|
||||
}
|
||||
// Primary retries (maxAttempts) + failover retries (maxAttempts) were all tried.
|
||||
if got := ai.callCount(); got != 2*maxAttempts {
|
||||
t.Fatalf("want %d attempts (primary + failover, both exhausted), got %d", 2*maxAttempts, got)
|
||||
}
|
||||
if waitForDebit(func() bool { return bs.debits() > 0 }) {
|
||||
t.Fatalf("a fully-throttled run must NOT be billed, got %d debits", bs.debits())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// routing.go is the machine-identity + liveness plane for routed runs (#48 half
|
||||
// B). A run dispatched to a target is executed by an EXTERNAL machine (`hanzo
|
||||
// code --serve`) that claims it over HTTP. Two properties make that safe:
|
||||
//
|
||||
// - MACHINE IDENTITY. A target carries a claim key — a high-entropy capability
|
||||
// minted server-side, returned to the daemon ONCE, and stored only as a
|
||||
// SHA-256 hash (never plaintext, like every other secret). A claim/report
|
||||
// must present the key; cloud verifies it in constant time, scoped to
|
||||
// (org, target). Possession of the key IS being that machine, so one machine
|
||||
// can never claim another's runs even within the same org.
|
||||
//
|
||||
// - LIVENESS. Dispatch routes ONLY to a target with a live runner. A serve
|
||||
// daemon proves liveness by polling Claim, which stamps serving_at; the gate
|
||||
// rejects a target whose last poll is older than servingTTL. A run to a dead
|
||||
// or absent runner fails closed at dispatch (never silently runs elsewhere),
|
||||
// and one that dies mid-flight is re-queued/timed-out by the durable owner.
|
||||
//
|
||||
// The claim key lives in its own table so the live (A) target CRUD is untouched.
|
||||
|
||||
const (
|
||||
// servingTTL bounds how stale a target's last claim poll may be and still be
|
||||
// considered "a runner is listening". The serve daemon re-polls right after a
|
||||
// 25s long-poll returns empty, so a healthy runner stamps well inside this.
|
||||
servingTTL = 90 * time.Second
|
||||
|
||||
claimKeyPrefix = "tgtk_"
|
||||
claimKeyBytes = 32 // 256-bit capability
|
||||
maxClaimKey = 128
|
||||
)
|
||||
|
||||
var (
|
||||
errNoClaimKey = errors.New("agents: target has no claim key")
|
||||
errClaimKeyBad = errors.New("agents: claim key mismatch")
|
||||
errTargetNotLive = errors.New("agents: target has no live runner")
|
||||
errTargetNotReady = errors.New("agents: target is not online")
|
||||
)
|
||||
|
||||
// migrateClaimKeys creates the per-target claim-key + serving-liveness table in
|
||||
// the SAME agents.db (one store, one tenancy column). Idempotent.
|
||||
func (s *Store) migrateClaimKeys() error {
|
||||
const ddl = `
|
||||
CREATE TABLE IF NOT EXISTS agent_target_claim_keys (
|
||||
org TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL,
|
||||
serving_at INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (org, target_id)
|
||||
);`
|
||||
if _, err := s.db.Exec(ddl); err != nil {
|
||||
return fmt.Errorf("migrate claim keys: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpsertClaimKeyHash stores (or rotates) a target's claim-key hash. serving_at is
|
||||
// reset to 0 on a fresh mint — the daemon proves liveness by its first poll.
|
||||
func (s *Store) UpsertClaimKeyHash(ctx context.Context, org, targetID, hash string, now int64) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO agent_target_claim_keys (org,target_id,key_hash,serving_at,updated_at)
|
||||
VALUES (?,?,?,0,?)
|
||||
ON CONFLICT(org,target_id) DO UPDATE SET key_hash=excluded.key_hash, serving_at=0, updated_at=excluded.updated_at`,
|
||||
org, targetID, hash, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert claim key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimKeyHash returns a target's stored hash + last serving stamp, or
|
||||
// errNoClaimKey when none was ever minted.
|
||||
func (s *Store) ClaimKeyHash(ctx context.Context, org, targetID string) (hash string, servingAt int64, err error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
`SELECT key_hash, serving_at FROM agent_target_claim_keys WHERE org=? AND target_id=?`, org, targetID)
|
||||
err = row.Scan(&hash, &servingAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", 0, errNoClaimKey
|
||||
}
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("get claim key: %w", err)
|
||||
}
|
||||
return hash, servingAt, nil
|
||||
}
|
||||
|
||||
// StampServing records that a target's runner polled at now (its liveness
|
||||
// heartbeat). Best-effort by the caller; a missing row is a no-op.
|
||||
func (s *Store) StampServing(ctx context.Context, org, targetID string, now int64) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE agent_target_claim_keys SET serving_at=? WHERE org=? AND target_id=?`, now, org, targetID)
|
||||
return err
|
||||
}
|
||||
|
||||
// hashClaimKey is the at-rest form: SHA-256 hex of a high-entropy token. A random
|
||||
// 256-bit key needs no password KDF; SHA-256 gives a fixed-size, constant-time-
|
||||
// comparable digest and the plaintext is never stored.
|
||||
func hashClaimKey(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// newClaimKey mints a fresh capability token.
|
||||
func newClaimKey() (string, error) {
|
||||
b := make([]byte, claimKeyBytes)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return claimKeyPrefix + hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// verifyClaimKey checks a presented key against the target's stored hash in
|
||||
// constant time. Fail-closed: no key on file, or an empty presented key, is a
|
||||
// mismatch — never an accidental pass.
|
||||
func (s *Store) verifyClaimKey(ctx context.Context, org, targetID, presented string) error {
|
||||
presented = strings.TrimSpace(presented)
|
||||
if presented == "" || len(presented) > maxClaimKey {
|
||||
return errClaimKeyBad
|
||||
}
|
||||
stored, _, err := s.ClaimKeyHash(ctx, org, targetID)
|
||||
if err != nil {
|
||||
return err // errNoClaimKey or a real DB error
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(stored), []byte(hashClaimKey(presented))) != 1 {
|
||||
return errClaimKeyBad
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TargetDispatchable is the DRY liveness gate, used at dispatch (fail closed
|
||||
// before enqueue) AND re-checked at claim. A run is dispatchable only to a target
|
||||
// that (a) exists in this org, (b) is online, and (c) has a live runner — a claim
|
||||
// poll within servingTTL. Any failure is an explicit error the dispatcher renders
|
||||
// honestly; it NEVER falls back to running elsewhere.
|
||||
func (s *Store) TargetDispatchable(ctx context.Context, org, targetID string) error {
|
||||
t, err := s.GetTarget(ctx, org, targetID)
|
||||
if err != nil {
|
||||
return err // errTargetNotFound or a real DB error
|
||||
}
|
||||
if t.Status != TargetOnline {
|
||||
return errTargetNotReady
|
||||
}
|
||||
_, servingAt, err := s.ClaimKeyHash(ctx, org, targetID)
|
||||
if err != nil {
|
||||
return errTargetNotLive // no claim key => no runner ever attached
|
||||
}
|
||||
if servingAt <= 0 || time.Now().Unix()-servingAt > int64(servingTTL/time.Second) {
|
||||
return errTargetNotLive
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TargetDispatchable is the exported gate the coding dispatcher injects (it never
|
||||
// imports the store directly). Returns nil when a run may be routed to (org,
|
||||
// targetID), else a descriptive error.
|
||||
func TargetDispatchable(ctx context.Context, org, targetID string) error {
|
||||
if mounted == nil {
|
||||
return fmt.Errorf("agents: not mounted")
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
targetID = strings.TrimSpace(targetID)
|
||||
if org == "" || targetID == "" {
|
||||
return fmt.Errorf("agents: org and target required")
|
||||
}
|
||||
return mounted.State.store.TargetDispatchable(ctx, org, targetID)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// routing_http.go is the machine-facing surface a `hanzo code --serve` daemon
|
||||
// uses to CLAIM and complete routed runs. Every route is BOTH org-scoped (the
|
||||
// gateway-minted X-Org-Id, exactly like the rest of the targets plane) AND
|
||||
// machine-authenticated (the target claim key in X-Target-Key): a caller must
|
||||
// prove it is acting in the target's org and that it holds that specific
|
||||
// machine's capability. A run offered to target X is never reachable from a claim
|
||||
// for target Y, and a claim for another org's target 404s at the org boundary.
|
||||
//
|
||||
// POST /v1/agents/targets/:id/claim-key mint/rotate this target's claim key -> {claimKey}
|
||||
// POST /v1/agents/targets/:id/claim long-poll for the next routed run (X-Target-Key)
|
||||
// POST /v1/agents/targets/:id/runs/:runId/report report a routed run's terminal result (X-Target-Key)
|
||||
|
||||
// claimLongPoll bounds one Claim wait; on expiry the daemon gets 204 and re-polls
|
||||
// immediately, which also refreshes its serving liveness. A var (not a const) so a
|
||||
// test can shrink the empty-poll window without waiting the full window.
|
||||
var claimLongPoll = 25 * time.Second
|
||||
|
||||
const (
|
||||
// claimKeyHeader carries the machine capability. Distinct from Authorization
|
||||
// (which carries the org bearer): org identity and machine identity are two
|
||||
// independent proofs, both required.
|
||||
claimKeyHeader = "X-Target-Key"
|
||||
maxReportField = 64 << 10
|
||||
)
|
||||
|
||||
// mountRouting registers the route-work machine surface. Called from mountTargets
|
||||
// AFTER the target CRUD routes so the extra-segment paths are unambiguous.
|
||||
func mountRouting(s *cloud.Service[state], app *zip.App) {
|
||||
assertSingleReplica(s.Log)
|
||||
g := app.Group("/v1/agents")
|
||||
g.Post("/targets/:id/claim-key", cloud.Handle(s, mintClaimKey))
|
||||
g.Post("/targets/:id/claim", cloud.Handle(s, claimRoutedRun))
|
||||
g.Post("/targets/:id/runs/:runId/report", cloud.Handle(s, reportRoutedRun))
|
||||
}
|
||||
|
||||
// caller is the VALIDATED principal id (X-User-Id) — the machine-owner identity for
|
||||
// route-work. tenant() already required a validated principal, so on any handler that
|
||||
// resolved an org this is non-empty.
|
||||
func caller(c *zip.Ctx) string { return strings.TrimSpace(c.User()) }
|
||||
|
||||
// ownsTarget reports whether the caller may MANAGE this target's route-work plane —
|
||||
// mint/rotate the claim key, claim, report, patch, delete. A machine belongs to the
|
||||
// principal that registered it (least privilege, AC-6): its owner may manage it, and
|
||||
// an org admin (self-service org management, the admin-org model's isAdmin) may manage
|
||||
// any of the org's targets. An UNOWNED (pre-migration) row is admin-only until its
|
||||
// owner re-registers — register binds the owner. Fail-closed: an empty caller or an
|
||||
// empty owner never satisfies the ownership arm, so a non-validated request or a
|
||||
// pre-migration row is never owner-managed.
|
||||
func ownsTarget(c *zip.Ctx, t Target) bool {
|
||||
if principal.IsOrgAdmin(c) || principal.IsSuperAdmin(c) {
|
||||
return true
|
||||
}
|
||||
u := caller(c)
|
||||
return t.Owner != "" && u != "" && u == t.Owner
|
||||
}
|
||||
|
||||
// authorizeTargetManage resolves the (org,id) target and gates it on ownsTarget,
|
||||
// collapsing every failure — cross-org, unknown, or not-owned — to the SAME
|
||||
// errTargetNotFound so the machine surface never distinguishes them (no oracle). The
|
||||
// resolved target is returned for the caller to use (avoids a second read).
|
||||
func authorizeTargetManage(s *cloud.Service[state], c *zip.Ctx, org, id string) (Target, error) {
|
||||
t, err := s.State.store.GetTarget(c.Context(), org, id)
|
||||
if err != nil {
|
||||
return Target{}, errTargetNotFound // unknown / cross-org -> no oracle
|
||||
}
|
||||
if !ownsTarget(c, t) {
|
||||
return Target{}, errTargetNotFound
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// mintClaimKey (re)mints the target's claim key and returns it ONCE. Only the
|
||||
// SHA-256 hash is stored. Org-scoped: only a caller in the target's org can mint,
|
||||
// and the key is bound to (org, target). Rotating supersedes any prior daemon.
|
||||
func mintClaimKey(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("X-Org-Id required")
|
||||
}
|
||||
id := idParam(c)
|
||||
// The target must exist in this org AND the caller must OWN it (or be an org
|
||||
// admin) before it can (re)mint a capability — minting rotates the key, so an
|
||||
// un-scoped mint would let any org member strand a victim's daemon and steal its
|
||||
// runs. Every failure collapses to the same not-found (no oracle).
|
||||
if _, err := authorizeTargetManage(s, c, org, id); err != nil {
|
||||
return zip.ErrNotFound("target not found")
|
||||
}
|
||||
key, err := newClaimKey()
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "rng: %v", err)
|
||||
}
|
||||
if err := s.State.store.UpsertClaimKeyHash(c.Context(), org, id, hashClaimKey(key), time.Now().Unix()); err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "persist: %v", err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, map[string]any{"targetId": id, "claimKey": key})
|
||||
}
|
||||
|
||||
// claimRoutedRun authenticates the machine, refreshes its serving liveness, and
|
||||
// long-polls the rendezvous for the next run addressed to THIS (org, target).
|
||||
// 200 + the run on a claim; 204 when the poll window elapses with no work.
|
||||
func claimRoutedRun(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("X-Org-Id required")
|
||||
}
|
||||
id := idParam(c)
|
||||
// TWO proofs, both required, both fail-closed to the SAME 403 (no oracle): the
|
||||
// caller must OWN this machine (or be an org admin) AND hold its claim key. The
|
||||
// ownership gate is defense in depth — with mint owner-scoped an attacker cannot
|
||||
// obtain a valid key for a victim's machine, but a claim still refuses a
|
||||
// non-owner outright rather than resting solely on the capability.
|
||||
if _, err := authorizeTargetManage(s, c, org, id); err != nil {
|
||||
return claimAuthError(errTargetNotFound)
|
||||
}
|
||||
if err := s.State.store.verifyClaimKey(c.Context(), org, id, c.Header(claimKeyHeader)); err != nil {
|
||||
return claimAuthError(err)
|
||||
}
|
||||
// The poll itself is the runner's liveness proof — stamp it so the dispatch
|
||||
// gate (TargetDispatchable) sees a live runner. Best-effort.
|
||||
_ = s.State.store.StampServing(c.Context(), org, id, time.Now().Unix())
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Context(), claimLongPoll)
|
||||
defer cancel()
|
||||
run, got := routedMailbox.Claim(ctx, org, id)
|
||||
if !got {
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
}
|
||||
return c.JSON(http.StatusOK, routedRunView(run))
|
||||
}
|
||||
|
||||
type reportReq struct {
|
||||
OK bool `json:"ok"`
|
||||
Changed bool `json:"changed"`
|
||||
Branch string `json:"branch"`
|
||||
CommitSha string `json:"commitSha"`
|
||||
Diffstat string `json:"diffstat"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// reportRoutedRun completes a claimed run: it delivers the terminal result to the
|
||||
// run's durable owner (the RoutedRunWorkflow activity), which lets the workflow
|
||||
// finish. Scoped to (org, target, runId) AND claim-key-authenticated, so a
|
||||
// machine can only ever report a run it legitimately holds. Idempotent: a report
|
||||
// for an unknown/already-finished run is a clean no-op (the session terminal was
|
||||
// already set by the machine's own stream).
|
||||
func reportRoutedRun(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("X-Org-Id required")
|
||||
}
|
||||
id := idParam(c)
|
||||
runID := strings.TrimSpace(c.Param("runId"))
|
||||
// Same two proofs as claim: own the machine (or org admin) AND hold its key, so a
|
||||
// non-owner can neither fabricate a report nor complete a victim's run. No oracle.
|
||||
if _, err := authorizeTargetManage(s, c, org, id); err != nil {
|
||||
return claimAuthError(errTargetNotFound)
|
||||
}
|
||||
if err := s.State.store.verifyClaimKey(c.Context(), org, id, c.Header(claimKeyHeader)); err != nil {
|
||||
return claimAuthError(err)
|
||||
}
|
||||
var body reportReq
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
res := RoutedResult{
|
||||
OK: body.OK, Changed: body.Changed,
|
||||
Branch: clampStr(body.Branch, maxRepo),
|
||||
CommitSha: clampStr(body.CommitSha, 128),
|
||||
Diffstat: clampStr(body.Diffstat, maxReportField),
|
||||
Error: clampStr(body.Error, maxReportField),
|
||||
}
|
||||
delivered := routedMailbox.Report(org, id, runID, res)
|
||||
return c.JSON(http.StatusOK, map[string]any{"delivered": delivered})
|
||||
}
|
||||
|
||||
// claimAuthError maps the claim-key verdict onto a fail-closed HTTP status. A
|
||||
// missing target row, a missing/mismatched key, and an unknown org all collapse
|
||||
// to 403 so the surface never distinguishes "wrong key" from "no such target" —
|
||||
// an unauthorized caller learns nothing about what exists.
|
||||
func claimAuthError(err error) error {
|
||||
switch err {
|
||||
case errNoClaimKey, errClaimKeyBad, errTargetNotFound:
|
||||
return zip.ErrForbidden("target claim rejected")
|
||||
default:
|
||||
return zip.Errorf(http.StatusInternalServerError, "claim auth: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// routedRunView is the non-secret run spec handed to the machine. It carries no
|
||||
// credential by design — the machine authenticates git + model routing with its
|
||||
// own already-held credentials.
|
||||
func routedRunView(run RoutedRun) map[string]any {
|
||||
return map[string]any{
|
||||
"sessionId": run.SessionID,
|
||||
"repo": run.Repo,
|
||||
"project": run.Project,
|
||||
"base": run.Base,
|
||||
"branch": run.Branch,
|
||||
"prompt": run.Prompt,
|
||||
"cloneUrl": run.CloneURL,
|
||||
"timeoutSeconds": run.TimeoutSeconds,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// doKey is a keyless-body request with a machine claim key (X-Target-Key) attached.
|
||||
func doKey(t *testing.T, app *zip.App, method, path, org, key string) (int, []byte) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
if org != "" {
|
||||
req.Header.Set("X-Org-Id", org)
|
||||
req.Header.Set("X-User-Id", "u-"+org)
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set(claimKeyHeader, key)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// registerAndMint registers a target for org and mints its claim key, returning
|
||||
// (targetID, claimKey).
|
||||
func registerAndMint(t *testing.T, app *zip.App, org, host string) (string, string) {
|
||||
t.Helper()
|
||||
code, body := do(t, app, "POST", "/v1/agents/targets", org, map[string]any{"label": host, "host": host})
|
||||
if code != 201 && code != 200 {
|
||||
t.Fatalf("register target: %d %s", code, body)
|
||||
}
|
||||
var tv struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &tv)
|
||||
code, body = doKey(t, app, "POST", "/v1/agents/targets/"+tv.ID+"/claim-key", org, "")
|
||||
if code != 200 {
|
||||
t.Fatalf("mint claim key: %d %s", code, body)
|
||||
}
|
||||
var kv struct {
|
||||
ClaimKey string `json:"claimKey"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &kv)
|
||||
if kv.ClaimKey == "" {
|
||||
t.Fatal("claim key empty")
|
||||
}
|
||||
return tv.ID, kv.ClaimKey
|
||||
}
|
||||
|
||||
// A claim without the machine's key, or with the WRONG key, is refused — org
|
||||
// membership alone is not enough to claim a machine's runs.
|
||||
func TestClaim_RequiresMachineKey(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
old := claimLongPoll
|
||||
claimLongPoll = 150 * time.Millisecond
|
||||
defer func() { claimLongPoll = old }()
|
||||
|
||||
id, key := registerAndMint(t, app, "acme", "evo")
|
||||
|
||||
// No key => 403.
|
||||
if code, _ := doKey(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", ""); code != 403 {
|
||||
t.Fatalf("claim with no key must be 403, got %d", code)
|
||||
}
|
||||
// Wrong key => 403.
|
||||
if code, _ := doKey(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", "tgtk_wrong"); code != 403 {
|
||||
t.Fatalf("claim with wrong key must be 403, got %d", code)
|
||||
}
|
||||
// Right key, no work => 204 (never 200, never another tenant's run).
|
||||
if code, _ := doKey(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", key); code != 204 {
|
||||
t.Fatalf("claim with right key + no work must be 204, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// THE machine boundary: a key minted for target A cannot claim target B, and a
|
||||
// different org cannot claim at all — even with a real key for its own target.
|
||||
func TestClaim_CrossMachineAndCrossOrgDenied(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
old := claimLongPoll
|
||||
claimLongPoll = 150 * time.Millisecond
|
||||
defer func() { claimLongPoll = old }()
|
||||
|
||||
idA, keyA := registerAndMint(t, app, "acme", "evoA")
|
||||
idB, _ := registerAndMint(t, app, "acme", "evoB")
|
||||
|
||||
// A's key against B => 403 (constant-time mismatch on B's stored hash).
|
||||
if code, _ := doKey(t, app, "POST", "/v1/agents/targets/"+idB+"/claim", "acme", keyA); code != 403 {
|
||||
t.Fatalf("A's key claiming B must be 403, got %d", code)
|
||||
}
|
||||
|
||||
// Offer a run for acme/idA, then a DIFFERENT org cannot claim idA at all (its
|
||||
// org scope resolves no such target => 403), and the run is never handed out.
|
||||
OfferRoutedRun(RoutedRun{Org: "acme", TargetID: idA, SessionID: "sess_a", Repo: "api"})
|
||||
if code, _ := doKey(t, app, "POST", "/v1/agents/targets/"+idA+"/claim", "evil", keyA); code != 403 {
|
||||
t.Fatalf("another org claiming acme's target must be 403, got %d", code)
|
||||
}
|
||||
// acme WITH A's key claims its own run.
|
||||
code, body := doKey(t, app, "POST", "/v1/agents/targets/"+idA+"/claim", "acme", keyA)
|
||||
if code != 200 {
|
||||
t.Fatalf("acme must claim its own run, got %d %s", code, body)
|
||||
}
|
||||
var rv struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &rv)
|
||||
if rv.SessionID != "sess_a" {
|
||||
t.Fatalf("claimed wrong run: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// The end-to-end machine round trip: offer -> claim -> report reaches the durable
|
||||
// owner awaiting the result.
|
||||
func TestClaimReport_RoundTrip(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
id, key := registerAndMint(t, app, "acme", "evo")
|
||||
|
||||
off := OfferRoutedRun(RoutedRun{Org: "acme", TargetID: id, SessionID: "sess_rt", Repo: "api", Branch: "agent/rt"})
|
||||
|
||||
code, body := doKey(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", key)
|
||||
if code != 200 {
|
||||
t.Fatalf("claim: %d %s", code, body)
|
||||
}
|
||||
|
||||
got := make(chan RoutedResult, 1)
|
||||
go func() { res, _ := off.Await(context.Background()); got <- res }()
|
||||
|
||||
code, _ = doKeyBody(t, app, "POST", "/v1/agents/targets/"+id+"/runs/sess_rt/report", "acme", key,
|
||||
map[string]any{"ok": true, "changed": true, "commitSha": "cafe"})
|
||||
if code != 200 {
|
||||
t.Fatalf("report: %d", code)
|
||||
}
|
||||
select {
|
||||
case res := <-got:
|
||||
if !res.OK || res.CommitSha != "cafe" {
|
||||
t.Fatalf("report did not reach the owner: %+v", res)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("owner never received the report")
|
||||
}
|
||||
}
|
||||
|
||||
// doKeyBody is doKey with a JSON body.
|
||||
func doKeyBody(t *testing.T, app *zip.App, method, path, org, key string, body any) (int, []byte) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(method, path, bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if org != "" {
|
||||
req.Header.Set("X-Org-Id", org)
|
||||
req.Header.Set("X-User-Id", "u-"+org)
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set(claimKeyHeader, key)
|
||||
}
|
||||
resp, err := app.Fiber().Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %s %s: %v", method, path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
// ---- store-level liveness gate ----
|
||||
|
||||
// TargetDispatchable is the fail-closed gate: online + a live runner (a recent
|
||||
// claim poll). Offline, no key, or a stale poll all reject.
|
||||
func TestTargetDispatchable_LivenessGate(t *testing.T) {
|
||||
s := testSessionStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().Unix()
|
||||
tgt := Target{ID: "t1", Org: "acme", Label: "evo", Kind: TargetMachine, Status: TargetOnline, Host: "evo", CreatedAt: now, UpdatedAt: now}
|
||||
if err := s.CreateTarget(ctx, tgt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// No claim key yet => not live => not dispatchable.
|
||||
if err := s.TargetDispatchable(ctx, "acme", "t1"); err != errTargetNotLive {
|
||||
t.Fatalf("no runner => not dispatchable, got %v", err)
|
||||
}
|
||||
// Mint + a fresh serving stamp => dispatchable.
|
||||
if err := s.UpsertClaimKeyHash(ctx, "acme", "t1", hashClaimKey("k"), now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.StampServing(ctx, "acme", "t1", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.TargetDispatchable(ctx, "acme", "t1"); err != nil {
|
||||
t.Fatalf("online + fresh runner => dispatchable, got %v", err)
|
||||
}
|
||||
// A stale serving stamp => not dispatchable (dead runner).
|
||||
if err := s.StampServing(ctx, "acme", "t1", now-int64(servingTTL/time.Second)-5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.TargetDispatchable(ctx, "acme", "t1"); err != errTargetNotLive {
|
||||
t.Fatalf("stale runner => not dispatchable, got %v", err)
|
||||
}
|
||||
// Fresh again but OFFLINE => not dispatchable.
|
||||
_ = s.StampServing(ctx, "acme", "t1", time.Now().Unix())
|
||||
tgt.Status = TargetOffline
|
||||
tgt.UpdatedAt = time.Now().Unix()
|
||||
if err := s.UpdateTarget(ctx, tgt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.TargetDispatchable(ctx, "acme", "t1"); err != errTargetNotReady {
|
||||
t.Fatalf("offline => not dispatchable, got %v", err)
|
||||
}
|
||||
// Unknown target / cross-org => fail closed.
|
||||
if err := s.TargetDispatchable(ctx, "acme", "nope"); err != errTargetNotFound {
|
||||
t.Fatalf("unknown target => not found, got %v", err)
|
||||
}
|
||||
if err := s.TargetDispatchable(ctx, "evil", "t1"); err != errTargetNotFound {
|
||||
t.Fatalf("cross-org => not found, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The claim key is stored ONLY as a hash; verify is constant-time + fail closed.
|
||||
func TestClaimKey_HashedAtRestAndVerified(t *testing.T) {
|
||||
s := testSessionStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().Unix()
|
||||
_ = s.CreateTarget(ctx, Target{ID: "t1", Org: "acme", Status: TargetOnline, CreatedAt: now, UpdatedAt: now})
|
||||
|
||||
key, _ := newClaimKey()
|
||||
if err := s.UpsertClaimKeyHash(ctx, "acme", "t1", hashClaimKey(key), now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The stored value is a hash, never the plaintext.
|
||||
stored, _, _ := s.ClaimKeyHash(ctx, "acme", "t1")
|
||||
if stored == key || stored != hashClaimKey(key) {
|
||||
t.Fatalf("claim key must be stored as a hash, not plaintext")
|
||||
}
|
||||
if err := s.verifyClaimKey(ctx, "acme", "t1", key); err != nil {
|
||||
t.Fatalf("correct key must verify: %v", err)
|
||||
}
|
||||
if err := s.verifyClaimKey(ctx, "acme", "t1", "tgtk_wrong"); err != errClaimKeyBad {
|
||||
t.Fatalf("wrong key must fail: %v", err)
|
||||
}
|
||||
if err := s.verifyClaimKey(ctx, "acme", "t1", ""); err != errClaimKeyBad {
|
||||
t.Fatalf("empty key must fail: %v", err)
|
||||
}
|
||||
// Cross-org verify resolves no key => fail closed.
|
||||
if err := s.verifyClaimKey(ctx, "evil", "t1", key); err != errNoClaimKey {
|
||||
t.Fatalf("cross-org verify must fail closed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- M2: owner/machine scoping of the claim-key plane ----
|
||||
|
||||
// reqAs sends a request with an EXPLICIT principal (X-User-Id) + optional org-admin
|
||||
// bit and claim key + JSON body, so a test can prove owner/admin scoping distinct
|
||||
// from org scoping.
|
||||
func reqAs(t *testing.T, app *zip.App, method, path, org, user string, admin bool, key string, body any) (int, []byte) {
|
||||
t.Helper()
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
b, _ := json.Marshal(body)
|
||||
r = bytes.NewReader(b)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, r)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if org != "" {
|
||||
req.Header.Set("X-Org-Id", org)
|
||||
}
|
||||
if user != "" {
|
||||
req.Header.Set("X-User-Id", user)
|
||||
}
|
||||
if admin {
|
||||
req.Header.Set("X-User-IsOrgAdmin", "true")
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set(claimKeyHeader, key)
|
||||
}
|
||||
resp, err := app.Fiber().Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %s %s: %v", method, path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
// registerAs registers a target in org OWNED by the given principal, returning its id.
|
||||
func registerAs(t *testing.T, app *zip.App, org, user, host string) string {
|
||||
t.Helper()
|
||||
code, body := reqAs(t, app, "POST", "/v1/agents/targets", org, user, false, "", map[string]any{"label": host, "host": host})
|
||||
if code != 201 && code != 200 {
|
||||
t.Fatalf("register target: %d %s", code, body)
|
||||
}
|
||||
var tv struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &tv)
|
||||
if tv.ID == "" {
|
||||
t.Fatalf("register returned no id: %s", body)
|
||||
}
|
||||
return tv.ID
|
||||
}
|
||||
|
||||
// A machine belongs to the principal that registered it: a DIFFERENT member of the
|
||||
// SAME org can neither mint/rotate its claim key, nor patch, nor delete it — only its
|
||||
// owner or an org admin can. Every refusal collapses to not-found (no oracle).
|
||||
func TestClaimKeyPlane_OwnerScoped(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
id := registerAs(t, app, "acme", "alice", "evo")
|
||||
|
||||
// A non-owner member of the same org is DENIED on every management verb.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim-key", "acme", "mallory", false, "", nil); code != 404 {
|
||||
t.Fatalf("non-owner mint must be denied (no oracle -> 404), got %d", code)
|
||||
}
|
||||
if code, _ := reqAs(t, app, "PATCH", "/v1/agents/targets/"+id, "acme", "mallory", false, "", map[string]any{"status": TargetOffline}); code != 404 {
|
||||
t.Fatalf("non-owner patch must be denied, got %d", code)
|
||||
}
|
||||
if code, _ := reqAs(t, app, "DELETE", "/v1/agents/targets/"+id, "acme", "mallory", false, "", nil); code != 404 {
|
||||
t.Fatalf("non-owner delete must be denied, got %d", code)
|
||||
}
|
||||
|
||||
// The OWNER can mint.
|
||||
code, body := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim-key", "acme", "alice", false, "", nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("owner mint must succeed, got %d %s", code, body)
|
||||
}
|
||||
|
||||
// An ORG ADMIN (self-service org management) can manage any of the org's machines.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim-key", "acme", "boss", true, "", nil); code != 200 {
|
||||
t.Fatalf("org admin mint must succeed, got %d", code)
|
||||
}
|
||||
if code, _ := reqAs(t, app, "PATCH", "/v1/agents/targets/"+id, "acme", "boss", true, "", map[string]any{"status": TargetOnline}); code != 200 {
|
||||
t.Fatalf("org admin patch must succeed, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// A non-owner cannot CLAIM a victim's runs or REPORT on them, even if the claim-key
|
||||
// authorization were somehow satisfied — the ownership gate refuses first.
|
||||
func TestClaimReport_OwnerScoped(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
old := claimLongPoll
|
||||
claimLongPoll = 150 * time.Millisecond
|
||||
defer func() { claimLongPoll = old }()
|
||||
|
||||
id := registerAs(t, app, "acme", "alice", "evo")
|
||||
// Alice mints her machine's key.
|
||||
code, body := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim-key", "acme", "alice", false, "", nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("owner mint: %d %s", code, body)
|
||||
}
|
||||
var kv struct {
|
||||
ClaimKey string `json:"claimKey"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &kv)
|
||||
|
||||
// Mallory (same org, not the owner) with the RIGHT key is still refused: she does
|
||||
// not own the machine. (In practice she cannot obtain the key, since mint is
|
||||
// owner-scoped — this is the defense-in-depth arm.)
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", "mallory", false, kv.ClaimKey, nil); code != 403 {
|
||||
t.Fatalf("non-owner claim must be 403, got %d", code)
|
||||
}
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/runs/sess_x/report", "acme", "mallory", false, kv.ClaimKey, map[string]any{"ok": true}); code != 403 {
|
||||
t.Fatalf("non-owner report must be 403, got %d", code)
|
||||
}
|
||||
|
||||
// The owner with her key claims (no work -> 204) and reports fine.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/"+id+"/claim", "acme", "alice", false, kv.ClaimKey, nil); code != 204 {
|
||||
t.Fatalf("owner claim (no work) must be 204, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// A pre-migration UNOWNED target (owner=”) is admin-only, and its owner heals it by
|
||||
// re-registering (register binds the owner). Proven at the store + handler seam.
|
||||
func TestUnownedTarget_AdminOnly_ThenBoundByRegister(t *testing.T) {
|
||||
app := mountApp(t, &fakeAI{content: "x"})
|
||||
ctx := context.Background()
|
||||
now := time.Now().Unix()
|
||||
// Seed an unowned row directly, as an upgraded pre-owner DB would carry.
|
||||
if err := mounted.State.store.CreateTarget(ctx, Target{ID: "tgt_legacy", Org: "acme", Owner: "", Label: "old", Kind: TargetMachine, Status: TargetOnline, Host: "old", CreatedAt: now, UpdatedAt: now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A plain member cannot mint on an unowned row.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/tgt_legacy/claim-key", "acme", "alice", false, "", nil); code != 404 {
|
||||
t.Fatalf("unowned row must be member-denied, got %d", code)
|
||||
}
|
||||
// An org admin can.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/tgt_legacy/claim-key", "acme", "boss", true, "", nil); code != 200 {
|
||||
t.Fatalf("unowned row must be admin-manageable, got %d", code)
|
||||
}
|
||||
// The owner heals it by re-registering the SAME host — register ADOPTS the
|
||||
// unowned row and BINDS the owner (no duplicate).
|
||||
code, body := reqAs(t, app, "POST", "/v1/agents/targets", "acme", "alice", false, "", map[string]any{"label": "old", "host": "old"})
|
||||
if code != 200 && code != 201 {
|
||||
t.Fatalf("re-register: %d %s", code, body)
|
||||
}
|
||||
var tv struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &tv)
|
||||
if tv.ID != "tgt_legacy" {
|
||||
t.Fatalf("re-register must adopt the unowned row (same id), got %q", tv.ID)
|
||||
}
|
||||
// Now alice (the bound owner) can mint.
|
||||
if code, _ := reqAs(t, app, "POST", "/v1/agents/targets/tgt_legacy/claim-key", "acme", "alice", false, "", nil); code != 200 {
|
||||
t.Fatalf("after binding, the owner must be able to mint, got %d", code)
|
||||
}
|
||||
}
|
||||
@@ -48,9 +48,9 @@ func (c *countingAI) Embed(_ context.Context, _ *types.EmbedRequest) ([][]float3
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// schedSvc builds a Service + scheduler with NO billing (gate allows) and the given
|
||||
// schedService builds a Service + scheduler with NO billing (gate allows) and the given
|
||||
// AI, seeded with the supplied agents. Returns the scheduler for direct tick().
|
||||
func schedSvc(t *testing.T, ai types.AIClient, seed ...Agent) *scheduler {
|
||||
func schedService(t *testing.T, ai types.AIClient, seed ...Agent) *scheduler {
|
||||
t.Helper()
|
||||
s := &cloud.Service[state]{Base: cloud.Base{Log: luxlog.New("test")}, State: state{store: testStore(t), ai: ai}}
|
||||
for _, a := range seed {
|
||||
@@ -83,7 +83,7 @@ func waitFor(cond func() bool) bool {
|
||||
// run; a tick at a non-matching minute launches none.
|
||||
func TestSchedulerFiresDueAgent(t *testing.T) {
|
||||
ai := &countingAI{}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "*/5 * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "*/5 * * * *"))
|
||||
ctx := context.Background()
|
||||
|
||||
sc.tick(ctx, at(t, "2026-07-01 12:36")) // 36 not multiple of 5 -> no fire
|
||||
@@ -102,7 +102,7 @@ func TestSchedulerFiresDueAgent(t *testing.T) {
|
||||
// like an HTTP run — the scheduler shares runAgent.
|
||||
func TestSchedulerRecordsRun(t *testing.T) {
|
||||
ai := &countingAI{}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
ctx := context.Background()
|
||||
sc.tick(ctx, at(t, "2026-07-01 12:00"))
|
||||
if !waitFor(func() bool {
|
||||
@@ -119,7 +119,7 @@ func TestSchedulerRecordsRun(t *testing.T) {
|
||||
// tick fires; the immediately-following matching tick is skipped (backoff=1).
|
||||
func TestSchedulerBackoffOnFailure(t *testing.T) {
|
||||
ai := &countingAI{fail: true}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
ctx := context.Background()
|
||||
|
||||
sc.tick(ctx, at(t, "2026-07-01 12:00"))
|
||||
@@ -152,7 +152,7 @@ func TestSchedulerBackoffOnFailure(t *testing.T) {
|
||||
// second matching tick while it is in flight does NOT start a second run.
|
||||
func TestSchedulerConcurrencyCap(t *testing.T) {
|
||||
ai := &countingAI{block: make(chan struct{})}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
ctx := context.Background()
|
||||
|
||||
sc.tick(ctx, at(t, "2026-07-01 12:00")) // starts run #1, which blocks
|
||||
@@ -257,7 +257,7 @@ func TestSchedulerGatesUnfundedRun(t *testing.T) {
|
||||
// path that lets Shutdown close the store safely.
|
||||
func TestSchedulerStopDrainsCleanly(t *testing.T) {
|
||||
ai := &countingAI{}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc.start()
|
||||
// Fire one run via a direct tick, then stop — stop must return after drain.
|
||||
sc.tick(context.Background(), at(t, "2026-07-01 12:00"))
|
||||
@@ -286,7 +286,7 @@ func TestSchedulerStopDrainsCleanly(t *testing.T) {
|
||||
// rather than waiting the full runTimeout.
|
||||
func TestSchedulerStopHonorsDeadline(t *testing.T) {
|
||||
ai := &countingAI{block: make(chan struct{})}
|
||||
sc := schedSvc(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc := schedService(t, ai, longRunning("acme", "cron", "* * * * *"))
|
||||
sc.start()
|
||||
sc.tick(context.Background(), at(t, "2026-07-01 12:00"))
|
||||
if !waitFor(func() bool { return ai.count() == 1 }) {
|
||||
@@ -310,7 +310,7 @@ func TestSchedulerStopHonorsDeadline(t *testing.T) {
|
||||
func TestSchedulerOnlyLongRunning(t *testing.T) {
|
||||
ai := &countingAI{}
|
||||
one := mk("acme", "one") // one-shot default, no schedule
|
||||
sc := schedSvc(t, ai, one)
|
||||
sc := schedService(t, ai, one)
|
||||
sc.tick(context.Background(), at(t, "2026-07-01 12:00"))
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if ai.count() != 0 {
|
||||
|
||||
+12
-11
@@ -182,17 +182,18 @@ func toEventView(e Event) eventView {
|
||||
// :name would otherwise capture "sessions"). Within the block, the static
|
||||
// /stream route precedes the /:id param for the same reason.
|
||||
func mountSessions(s *cloud.Service[state], app *zip.App) {
|
||||
app.Post("/v1/agents/sessions", cloud.Handle(s, registerSession))
|
||||
app.Get("/v1/agents/sessions", cloud.Handle(s, listSessions))
|
||||
app.Get("/v1/agents/sessions/stream", cloud.Handle(s, sessionsStream))
|
||||
app.Get("/v1/agents/sessions/:id", cloud.Handle(s, getSession))
|
||||
app.Patch("/v1/agents/sessions/:id", cloud.Handle(s, patchSession))
|
||||
app.Get("/v1/agents/sessions/:id/tree", cloud.Handle(s, sessionTree))
|
||||
app.Post("/v1/agents/sessions/:id/events", cloud.Handle(s, appendSessionEvent))
|
||||
app.Post("/v1/agents/sessions/:id/pause", cloud.Handle(s, pauseSession))
|
||||
app.Post("/v1/agents/sessions/:id/resume", cloud.Handle(s, resumeSession))
|
||||
app.Post("/v1/agents/sessions/:id/stop", cloud.Handle(s, stopSession))
|
||||
app.Post("/v1/agents/sessions/:id/message", cloud.Handle(s, messageSession))
|
||||
g := app.Group("/v1/agents")
|
||||
g.Post("/sessions", cloud.Handle(s, registerSession))
|
||||
g.Get("/sessions", cloud.Handle(s, listSessions))
|
||||
g.Get("/sessions/stream", cloud.Handle(s, sessionsStream))
|
||||
g.Get("/sessions/:id", cloud.Handle(s, getSession))
|
||||
g.Patch("/sessions/:id", cloud.Handle(s, patchSession))
|
||||
g.Get("/sessions/:id/tree", cloud.Handle(s, sessionTree))
|
||||
g.Post("/sessions/:id/events", cloud.Handle(s, appendSessionEvent))
|
||||
g.Post("/sessions/:id/pause", cloud.Handle(s, pauseSession))
|
||||
g.Post("/sessions/:id/resume", cloud.Handle(s, resumeSession))
|
||||
g.Post("/sessions/:id/stop", cloud.Handle(s, stopSession))
|
||||
g.Post("/sessions/:id/message", cloud.Handle(s, messageSession))
|
||||
}
|
||||
|
||||
func idParam(c *zip.Ctx) string { return strings.TrimSpace(c.Param("id")) }
|
||||
|
||||
@@ -180,6 +180,10 @@ CREATE INDEX IF NOT EXISTS ix_runs_org_agent_created ON agent_runs(org, agent_na
|
||||
if err := s.migrateTargets(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Per-target claim keys + serving liveness (the #48 route-work machine plane).
|
||||
if err := s.migrateClaimKeys(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+265
-24
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/hanzoai/cloud/clients/principal"
|
||||
"github.com/hanzoai/cloud/clients/samples"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
@@ -17,10 +19,11 @@ import (
|
||||
// box, a GPU host, or a whole cluster. It is the #48 link-a-compute seam over the
|
||||
// SAME agents.db (one store, one tenancy column) as sessions/events — NOT a rival
|
||||
// device registry. It composes with the compute fleet rather than duplicating it: a
|
||||
// session records the target id it runs on (agent_sessions.target), and the mission-
|
||||
// control devices view unions these registered targets with the org's BYO workers
|
||||
// (GET /v1/fleet/workers) and BYO clusters (GET /v1/clusters) at the view layer — the
|
||||
// console's established pattern for folding compute sources.
|
||||
// session records the target id it runs on (agent_sessions.target), and the org's
|
||||
// unified board (GET /v1/fleet, clients/visor/board.go) unions these registered
|
||||
// targets with its BYO workers (GET /v1/fleet/workers), BYO clusters and Visor
|
||||
// machines — reading this registry through the in-process seam below rather than
|
||||
// copying it.
|
||||
//
|
||||
// POST /v1/agents/targets register a target -> Target
|
||||
// GET /v1/agents/targets list the org's targets (+ live session load)
|
||||
@@ -30,6 +33,12 @@ import (
|
||||
//
|
||||
// Every route is org-scoped through principal.Org (tenant), fail-closed — a tenant
|
||||
// can never see or mutate another org's targets, exactly like sessions.
|
||||
//
|
||||
// A write carrying `metrics` IS a heartbeat, and a heartbeat is two facts, not one:
|
||||
// the LAST sample (kept on the row, rendered by the views here) and one point in a
|
||||
// utilization SERIES (appended to clients/samples). The row answers "is this machine
|
||||
// alive and what is it doing now"; the series answers "how hot has it been". The
|
||||
// append is best-effort and detached — see recordSample.
|
||||
|
||||
// Target kinds — the closed vocabulary of dispatch destinations.
|
||||
const (
|
||||
@@ -78,6 +87,7 @@ var errTargetNotFound = errors.New("agents: target not found")
|
||||
type Target struct {
|
||||
ID string
|
||||
Org string
|
||||
Owner string // the VALIDATED principal (c.User()) that registered this machine; "" for a pre-migration row
|
||||
Label string
|
||||
Kind string // laptop | cloud | gpu | cluster | machine
|
||||
Status string // online | offline | draining
|
||||
@@ -103,6 +113,7 @@ func (s *Store) migrateTargets() error {
|
||||
CREATE TABLE IF NOT EXISTS agent_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
org TEXT NOT NULL,
|
||||
owner TEXT NOT NULL DEFAULT '',
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
kind TEXT NOT NULL DEFAULT 'machine',
|
||||
status TEXT NOT NULL DEFAULT 'online',
|
||||
@@ -120,9 +131,12 @@ CREATE INDEX IF NOT EXISTS ix_targets_org_created ON agent_targets(org, created_
|
||||
return fmt.Errorf("migrate targets: %w", err)
|
||||
}
|
||||
// Forward, idempotent upgrade for target rows created before the capability +
|
||||
// metrics columns existed. PRAGMA-guarded, so re-running on an upgraded DB is a
|
||||
// no-op — the DDL above covers fresh installs, this covers pre-existing ones.
|
||||
// metrics + owner columns existed. PRAGMA-guarded, so re-running on an upgraded
|
||||
// DB is a no-op — the DDL above covers fresh installs, this covers pre-existing
|
||||
// ones. A pre-owner row backfills owner='' (unowned) and is admin-only until its
|
||||
// owner re-registers (register binds the owner) — see registerTarget.
|
||||
if err := s.addColumns("agent_targets", map[string]string{
|
||||
"owner": "TEXT NOT NULL DEFAULT ''",
|
||||
"spec": "TEXT NOT NULL DEFAULT ''",
|
||||
"metrics": "TEXT NOT NULL DEFAULT ''",
|
||||
"metrics_at": "INTEGER NOT NULL DEFAULT 0",
|
||||
@@ -132,12 +146,12 @@ CREATE INDEX IF NOT EXISTS ix_targets_org_created ON agent_targets(org, created_
|
||||
return nil
|
||||
}
|
||||
|
||||
const targetCols = `id,org,label,kind,status,capacity,host,spec,metrics,metrics_at,created_at,updated_at`
|
||||
const targetCols = `id,org,owner,label,kind,status,capacity,host,spec,metrics,metrics_at,created_at,updated_at`
|
||||
|
||||
func scanTarget(sc interface{ Scan(...any) error }) (Target, error) {
|
||||
var t Target
|
||||
var spec, metrics string
|
||||
err := sc.Scan(&t.ID, &t.Org, &t.Label, &t.Kind, &t.Status, &t.Capacity, &t.Host,
|
||||
err := sc.Scan(&t.ID, &t.Org, &t.Owner, &t.Label, &t.Kind, &t.Status, &t.Capacity, &t.Host,
|
||||
&spec, &metrics, &t.MetricsAt, &t.CreatedAt, &t.UpdatedAt)
|
||||
if err != nil {
|
||||
return t, err
|
||||
@@ -150,8 +164,8 @@ func scanTarget(sc interface{ Scan(...any) error }) (Target, error) {
|
||||
// CreateTarget inserts one target. The id is caller-generated (genID("tgt")).
|
||||
func (s *Store) CreateTarget(ctx context.Context, t Target) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO agent_targets (`+targetCols+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
t.ID, t.Org, t.Label, t.Kind, t.Status, t.Capacity, t.Host,
|
||||
`INSERT INTO agent_targets (`+targetCols+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
t.ID, t.Org, t.Owner, t.Label, t.Kind, t.Status, t.Capacity, t.Host,
|
||||
encodeSpec(t.Spec), encodeMetrics(t.Metrics), t.MetricsAt, t.CreatedAt, t.UpdatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert target: %w", err)
|
||||
@@ -194,12 +208,14 @@ func (s *Store) ListTargets(ctx context.Context, org string) ([]Target, error) {
|
||||
}
|
||||
|
||||
// UpdateTarget persists mutable fields for an existing (org,id) target. Scoped by org
|
||||
// so a cross-tenant id can never mutate another's target.
|
||||
// so a cross-tenant id can never mutate another's target. owner is persisted too so a
|
||||
// relink can BIND a previously-unowned row (registerTarget) and a patch preserves the
|
||||
// owner it read; no client-facing patch field sets owner, so it never moves by mutation.
|
||||
func (s *Store) UpdateTarget(ctx context.Context, t Target) error {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`UPDATE agent_targets SET label=?, kind=?, status=?, capacity=?, host=?, spec=?, metrics=?, metrics_at=?, updated_at=?
|
||||
`UPDATE agent_targets SET owner=?, label=?, kind=?, status=?, capacity=?, host=?, spec=?, metrics=?, metrics_at=?, updated_at=?
|
||||
WHERE org=? AND id=?`,
|
||||
t.Label, t.Kind, t.Status, t.Capacity, t.Host,
|
||||
t.Owner, t.Label, t.Kind, t.Status, t.Capacity, t.Host,
|
||||
encodeSpec(t.Spec), encodeMetrics(t.Metrics), t.MetricsAt, t.UpdatedAt, t.Org, t.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update target: %w", err)
|
||||
@@ -211,6 +227,32 @@ func (s *Store) UpdateTarget(ctx context.Context, t Target) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLinkableTargetByHost returns the target for (org,host) that the caller `owner`
|
||||
// may re-link — its OWN row, else an UNOWNED (pre-migration) row it may adopt —
|
||||
// preferring the exact-owner match, newest first. A row owned by a DIFFERENT
|
||||
// principal is NEVER returned, so a re-link can never clobber another member's
|
||||
// machine: the caller gets its own row or (falling through in registerTarget) a fresh
|
||||
// one. errTargetNotFound when nothing linkable exists.
|
||||
func (s *Store) GetLinkableTargetByHost(ctx context.Context, org, host, owner string) (Target, error) {
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" {
|
||||
return Target{}, errTargetNotFound
|
||||
}
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
`SELECT `+targetCols+` FROM agent_targets
|
||||
WHERE org=? AND host=? AND (owner=? OR owner='')
|
||||
ORDER BY CASE WHEN owner=? THEN 0 ELSE 1 END, created_at DESC, id ASC LIMIT 1`,
|
||||
org, host, owner, owner)
|
||||
t, err := scanTarget(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Target{}, errTargetNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("get linkable target by host: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// GetTargetByHost returns an org's target reporting the given host, or
|
||||
// errTargetNotFound. It is how a re-link of the SAME machine finds its existing target
|
||||
// (idempotent register) instead of creating a duplicate. Org-scoped: a host string can
|
||||
@@ -233,6 +275,90 @@ func (s *Store) GetTargetByHost(ctx context.Context, org, host string) (Target,
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// ---- the in-process seam (org-scoped, fail-closed) ----
|
||||
//
|
||||
// TargetsForOrg / LoadOn are the exported twins of the list + detail reads above:
|
||||
// the ONE way another in-process subsystem (the /v1/fleet board in clients/visor)
|
||||
// reads this registry WITHOUT an HTTP hop back through the gateway — the same
|
||||
// shape ListForOrg gives the agent registry. They are two ORTHOGONAL values on
|
||||
// purpose: a target is what the machine IS, its load is what is running on it, and
|
||||
// a caller that only needs the inventory does not pay for the rollups.
|
||||
//
|
||||
// ISOLATION: org is the ONLY tenant key and is threaded verbatim into the
|
||||
// org-scoped store methods, so a caller for org A can never enumerate or resolve
|
||||
// org B's targets. The caller MUST pass an org it already validated server-side
|
||||
// (principal.Org), never a raw client header.
|
||||
|
||||
// TargetsForOrg returns the org's registered run-targets from the in-process
|
||||
// store, newest first. Fails closed when the subsystem is not mounted or the org
|
||||
// is empty/oversized.
|
||||
func TargetsForOrg(ctx context.Context, org string) ([]Target, error) {
|
||||
if mounted == nil || mounted.State.store == nil {
|
||||
return nil, fmt.Errorf("agents: not mounted")
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
if org == "" || len(org) > principal.MaxOrgLen {
|
||||
return nil, fmt.Errorf("agents: invalid org")
|
||||
}
|
||||
return mounted.State.store.ListTargets(ctx, org)
|
||||
}
|
||||
|
||||
// ResolveTarget resolves a human's target REFERENCE — a target id or its friendly
|
||||
// label (the hostname the CLI registers) — to the org's target, org-scoped and
|
||||
// fail-closed. It is the ONE way a trigger surface (the Slack `code: <repo> on
|
||||
// <target>` grammar, a console picker) turns "on evo" into a target id without
|
||||
// leaking another tenant's inventory: an id or label that resolves to no target in
|
||||
// THIS org returns errTargetNotFound, never another org's machine.
|
||||
//
|
||||
// Precedence: an exact id match wins (ids are unambiguous), else an exact,
|
||||
// case-folded label match (newest first, so a re-registered machine's live row is
|
||||
// preferred). A reference that matches neither is not found — the caller renders an
|
||||
// honest error and NEVER falls back to a local run.
|
||||
func ResolveTarget(ctx context.Context, org, ref string) (Target, error) {
|
||||
if mounted == nil || mounted.State.store == nil {
|
||||
return Target{}, fmt.Errorf("agents: not mounted")
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
ref = strings.TrimSpace(ref)
|
||||
if org == "" || len(org) > principal.MaxOrgLen {
|
||||
return Target{}, fmt.Errorf("agents: invalid org")
|
||||
}
|
||||
if ref == "" || len(ref) > maxTargetID {
|
||||
return Target{}, errTargetNotFound
|
||||
}
|
||||
// An id is exact and unambiguous — try it first.
|
||||
if t, err := mounted.State.store.GetTarget(ctx, org, ref); err == nil {
|
||||
return t, nil
|
||||
} else if err != errTargetNotFound {
|
||||
return Target{}, err
|
||||
}
|
||||
// Else an exact, case-folded label match within this org.
|
||||
rows, err := mounted.State.store.ListTargets(ctx, org)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
for _, t := range rows { // ListTargets is newest-first: the live row wins a label tie
|
||||
if strings.EqualFold(strings.TrimSpace(t.Label), ref) {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return Target{}, errTargetNotFound
|
||||
}
|
||||
|
||||
// LoadOn returns the live session load on one of the org's targets — the same
|
||||
// (target id OR host) mapping the HTTP views use, so the board and /v1/agents/
|
||||
// targets can never disagree about what is running where.
|
||||
func LoadOn(ctx context.Context, org, id, host string) (TargetLoad, error) {
|
||||
if mounted == nil || mounted.State.store == nil {
|
||||
return TargetLoad{}, fmt.Errorf("agents: not mounted")
|
||||
}
|
||||
org = strings.TrimSpace(org)
|
||||
if org == "" || len(org) > principal.MaxOrgLen {
|
||||
return TargetLoad{}, fmt.Errorf("agents: invalid org")
|
||||
}
|
||||
return mounted.State.store.SessionLoad(ctx, org, id, host)
|
||||
}
|
||||
|
||||
// DeleteTarget removes an org's target. Sessions keep their recorded target id (a
|
||||
// historical fact); a detached target simply stops appearing in the registry.
|
||||
func (s *Store) DeleteTarget(ctx context.Context, org, id string) (bool, error) {
|
||||
@@ -262,6 +388,83 @@ func (s *Store) SessionLoad(ctx context.Context, org, id, host string) (TargetLo
|
||||
return TargetLoad{Sessions: total, Running: running}, nil
|
||||
}
|
||||
|
||||
// ---- the fleet time series ----
|
||||
//
|
||||
// A heartbeat is the ONE moment this process learns what a linked machine is
|
||||
// doing, so it is also where the fleet's utilization series is fed. The target row
|
||||
// keeps the LAST sample (the snapshot the views render, unchanged); clients/samples
|
||||
// keeps every sample over time. Two different questions — "is it alive now" and
|
||||
// "how hot has it been" — so two homes, one write.
|
||||
|
||||
// sampleTimeout bounds the warehouse write. Generous (the insert is one small row
|
||||
// in-cluster) but finite, so a wedged datastore can never hold the goroutine open.
|
||||
const sampleTimeout = 5 * time.Second
|
||||
|
||||
// sampleOf projects a target's server-stamped heartbeat into a fleet sample. PURE
|
||||
// (no clock, no I/O, no store) so the whole projection is unit-testable and the
|
||||
// caller decides when it runs.
|
||||
//
|
||||
// cost_cents is 0: an agent run-target is the operator's OWN machine (a laptop, a
|
||||
// dialed-in box) — the fleet meters its utilization, it does not resell it. A
|
||||
// priced source (visor/cloud) fills that column from its own resale price.
|
||||
func sampleOf(t Target) samples.Sample {
|
||||
var model string
|
||||
if len(t.Spec.GPUs) > 0 {
|
||||
// The representative accelerator: the count already rides in GPUs, so the
|
||||
// first card's model names the row. A heterogeneous host is rare enough
|
||||
// that naming its first card beats inventing a summary string here.
|
||||
model = t.Spec.GPUs[0].Model
|
||||
if model == "" {
|
||||
model = t.Spec.GPUs[0].Vendor
|
||||
}
|
||||
}
|
||||
return samples.Sample{
|
||||
Org: t.Org,
|
||||
Source: samples.SourceAgent,
|
||||
Unit: t.ID,
|
||||
Host: t.Host,
|
||||
Kind: t.Kind,
|
||||
At: time.Unix(t.MetricsAt, 0).UTC(),
|
||||
|
||||
CPUs: t.Spec.CPUs,
|
||||
Memory: t.Spec.Memory,
|
||||
MemUsed: t.Metrics.MemUsed,
|
||||
MemFree: t.Metrics.MemFree,
|
||||
Load1: t.Metrics.Load1,
|
||||
Load5: t.Metrics.Load5,
|
||||
Load15: t.Metrics.Load15,
|
||||
GPUUtil: t.Metrics.GPUUtil,
|
||||
GPUs: len(t.Spec.GPUs),
|
||||
GPUModel: model,
|
||||
}
|
||||
}
|
||||
|
||||
// recordSample appends a heartbeat to the fleet series. Best-effort and DETACHED
|
||||
// on purpose — the warehouse is never in the heartbeat's critical path:
|
||||
//
|
||||
// - it runs on its own bounded context, so neither a slow datastore nor the
|
||||
// client hanging up mid-request can stall or cancel the write;
|
||||
// - it never touches the response, so the /v1/agents/targets contract is
|
||||
// byte-identical whether the warehouse is present, absent or on fire;
|
||||
// - a failure is logged, never surfaced — a dropped sample must not cost a
|
||||
// machine its heartbeat.
|
||||
//
|
||||
// This is the shape the billing warehouse write already uses (`go zapWriteUsage`):
|
||||
// the seam is synchronous, the CALLER owns the concurrency.
|
||||
func recordSample(s *cloud.Service[state], t Target) {
|
||||
if t.MetricsAt == 0 {
|
||||
return // no heartbeat in this write — nothing to append
|
||||
}
|
||||
sample := sampleOf(t) // project on the caller's goroutine: t must not escape mutably
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), sampleTimeout)
|
||||
defer cancel()
|
||||
if err := samples.Record(ctx, sample); err != nil {
|
||||
s.Log.Warn("fleet sample write failed", "org", sample.Org, "unit", sample.Unit, "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// ---- HTTP shapes (the published contract) ----
|
||||
|
||||
type targetView struct {
|
||||
@@ -306,11 +509,16 @@ func toTargetView(t Target, load TargetLoad) targetView {
|
||||
// /v1/agents/:ref wildcard (Fiber matches in registration order) so "targets" is not
|
||||
// captured as a ref. The static /v1/agents/targets precedes /v1/agents/targets/:id.
|
||||
func mountTargets(s *cloud.Service[state], app *zip.App) {
|
||||
app.Post("/v1/agents/targets", cloud.Handle(s, registerTarget))
|
||||
app.Get("/v1/agents/targets", cloud.Handle(s, listTargets))
|
||||
app.Get("/v1/agents/targets/:id", cloud.Handle(s, getTarget))
|
||||
app.Patch("/v1/agents/targets/:id", cloud.Handle(s, patchTarget))
|
||||
app.Delete("/v1/agents/targets/:id", cloud.Handle(s, deleteTarget))
|
||||
g := app.Group("/v1/agents")
|
||||
g.Post("/targets", cloud.Handle(s, registerTarget))
|
||||
g.Get("/targets", cloud.Handle(s, listTargets))
|
||||
g.Get("/targets/:id", cloud.Handle(s, getTarget))
|
||||
g.Patch("/targets/:id", cloud.Handle(s, patchTarget))
|
||||
g.Delete("/targets/:id", cloud.Handle(s, deleteTarget))
|
||||
// The #48 route-work machine surface (claim-key, claim long-poll, report)
|
||||
// lives on the same target routes; register after the CRUD so the
|
||||
// extra-segment paths are unambiguous.
|
||||
mountRouting(s, app)
|
||||
}
|
||||
|
||||
// ---- register ----
|
||||
@@ -374,18 +582,28 @@ func registerTarget(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
metricsAt = now // the server owns the staleness clock; a client can't forge it
|
||||
}
|
||||
|
||||
// Idempotent re-link: the SAME machine (org+host) refreshes its existing target
|
||||
// rather than piling up duplicates, so mission-control shows one row per machine
|
||||
// with live spec/metrics. Only an explicit host keys this — an anonymous target
|
||||
// (no host) always creates.
|
||||
// The registering principal OWNS this machine (least privilege): only it (or an
|
||||
// org admin) may later mint the claim key, claim runs, report, patch, or delete
|
||||
// it. tenant() already required a validated principal, so this is non-empty.
|
||||
owner := caller(c)
|
||||
|
||||
// Idempotent re-link: the SAME machine (org+host+owner) refreshes its existing
|
||||
// target rather than piling up duplicates, so mission-control shows one row per
|
||||
// machine with live spec/metrics. It resolves ONLY the caller's own row (or an
|
||||
// UNOWNED pre-migration row, which it ADOPTS by binding owner) — a row owned by a
|
||||
// different member is never touched, so a re-link can never hijack another's
|
||||
// machine; the caller falls through to create its own. Only an explicit host keys
|
||||
// this — an anonymous target (no host) always creates.
|
||||
if host != "" {
|
||||
if existing, err := s.State.store.GetTargetByHost(c.Context(), org, host); err == nil {
|
||||
if existing, err := s.State.store.GetLinkableTargetByHost(c.Context(), org, host, owner); err == nil {
|
||||
existing.Owner = owner // bind an adopted unowned row; no-op if already ours
|
||||
existing.Label, existing.Kind, existing.Status, existing.Capacity = label, kind, status, capacity
|
||||
existing.Spec, existing.Metrics, existing.MetricsAt = spec, metrics, metricsAt
|
||||
existing.UpdatedAt = now
|
||||
if err := s.State.store.UpdateTarget(c.Context(), existing); err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "persist: %v", err)
|
||||
}
|
||||
recordSample(s, existing) // a re-link carrying metrics IS a heartbeat
|
||||
load, _ := s.State.store.SessionLoad(c.Context(), org, existing.ID, existing.Host)
|
||||
return c.JSON(http.StatusOK, toTargetView(existing, load))
|
||||
}
|
||||
@@ -396,13 +614,14 @@ func registerTarget(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
return zip.Errorf(http.StatusInternalServerError, "rng: %v", err)
|
||||
}
|
||||
t := Target{
|
||||
ID: id, Org: org, Label: label, Kind: kind, Status: status,
|
||||
ID: id, Org: org, Owner: owner, Label: label, Kind: kind, Status: status,
|
||||
Capacity: capacity, Host: host, Spec: spec, Metrics: metrics, MetricsAt: metricsAt,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.State.store.CreateTarget(c.Context(), t); err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "persist: %v", err)
|
||||
}
|
||||
recordSample(s, t) // a registration carrying metrics is the target's first sample
|
||||
return c.JSON(http.StatusCreated, toTargetView(t, TargetLoad{}))
|
||||
}
|
||||
|
||||
@@ -472,6 +691,12 @@ func patchTarget(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "get: %v", err)
|
||||
}
|
||||
// Only the machine's owner (or an org admin) may mutate it — a member cannot
|
||||
// reconfigure/drain another member's machine. Fail-closed to the SAME not-found
|
||||
// an unknown id gives, so a probe learns nothing about what exists.
|
||||
if !ownsTarget(c, t) {
|
||||
return zip.ErrNotFound("target not found")
|
||||
}
|
||||
var body patchTargetReq
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
@@ -538,6 +763,9 @@ func patchTarget(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
}
|
||||
return zip.Errorf(http.StatusInternalServerError, "update: %v", err)
|
||||
}
|
||||
if body.Metrics != nil {
|
||||
recordSample(s, t) // THE heartbeat: append it to the fleet series too
|
||||
}
|
||||
load, _ := s.State.store.SessionLoad(c.Context(), org, t.ID, t.Host)
|
||||
return c.JSON(http.StatusOK, toTargetView(t, load))
|
||||
}
|
||||
@@ -550,6 +778,19 @@ func deleteTarget(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
return zip.ErrForbidden("X-Org-Id required")
|
||||
}
|
||||
id := idParam(c)
|
||||
// Resolve + ownership-gate before deleting: only the machine's owner (or an org
|
||||
// admin) may deregister it. A cross-org id, an unknown id, and a non-owned id all
|
||||
// collapse to the same not-found — no oracle.
|
||||
t, err := s.State.store.GetTarget(c.Context(), org, id)
|
||||
if err == errTargetNotFound {
|
||||
return zip.ErrNotFound("target not found")
|
||||
}
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "get: %v", err)
|
||||
}
|
||||
if !ownsTarget(c, t) {
|
||||
return zip.ErrNotFound("target not found")
|
||||
}
|
||||
deleted, err := s.State.store.DeleteTarget(c.Context(), org, id)
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusInternalServerError, "delete: %v", err)
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hanzoai/cloud/clients/samples"
|
||||
)
|
||||
|
||||
// targetsample_test.go covers the FIRST emitter: a run-target heartbeat also
|
||||
// appends to the fleet series (clients/samples).
|
||||
//
|
||||
// The datastore is absent under test, so samples.Record is a proven no-op (its own
|
||||
// package tests that). What MUST be proven here is everything this side owns:
|
||||
// the projection is faithful, the vocabularies agree, and the HTTP contract is
|
||||
// untouched whether or not the warehouse exists.
|
||||
|
||||
// ---- the projection (pure) ----
|
||||
|
||||
// A heartbeat projects onto a sample with no loss and no invention.
|
||||
func TestSampleOfProjectsTheHeartbeat(t *testing.T) {
|
||||
at := time.Now().Unix()
|
||||
tg := Target{
|
||||
ID: "tgt-1", Org: "acme", Kind: TargetGPU, Host: "box.local", Label: "Box",
|
||||
Spec: Spec{OS: "linux", Arch: "arm64", CPUs: 20, Memory: 128 << 30,
|
||||
GPUs: []GPU{{Vendor: "nvidia", Model: "GB10", Memory: 96 << 30}}},
|
||||
Metrics: Metrics{Load1: 2.5, Load5: 2, Load15: 1.5,
|
||||
MemUsed: 64 << 30, MemFree: 64 << 30, GPUUtil: 0.75},
|
||||
MetricsAt: at,
|
||||
}
|
||||
s := sampleOf(tg)
|
||||
|
||||
if s.Org != "acme" || s.Unit != "tgt-1" || s.Host != "box.local" {
|
||||
t.Fatalf("identity did not project: %+v", s)
|
||||
}
|
||||
if s.Source != samples.SourceAgent {
|
||||
t.Fatalf("source want %q, got %q", samples.SourceAgent, s.Source)
|
||||
}
|
||||
if s.Kind != TargetGPU {
|
||||
t.Fatalf("kind want %q, got %q", TargetGPU, s.Kind)
|
||||
}
|
||||
if !s.At.Equal(time.Unix(at, 0).UTC()) {
|
||||
t.Fatalf("at must be the SERVER-stamped heartbeat clock, got %v", s.At)
|
||||
}
|
||||
if s.CPUs != 20 || s.Memory != 128<<30 {
|
||||
t.Fatalf("spec did not project: %+v", s)
|
||||
}
|
||||
if s.MemUsed != 64<<30 || s.MemFree != 64<<30 || s.Load1 != 2.5 || s.Load5 != 2 || s.Load15 != 1.5 {
|
||||
t.Fatalf("metrics did not project: %+v", s)
|
||||
}
|
||||
if s.GPUUtil != 0.75 || s.GPUs != 1 || s.GPUModel != "GB10" {
|
||||
t.Fatalf("gpu did not project: %+v", s)
|
||||
}
|
||||
// An agent's own machine is metered, never resold.
|
||||
if s.CostCents != 0 {
|
||||
t.Fatalf("an agent sample must be unpriced, got %d", s.CostCents)
|
||||
}
|
||||
// The projection must be acceptable to the plane it feeds.
|
||||
if err := samples.Record(t.Context(), s); err != nil {
|
||||
t.Fatalf("a projected sample must be recordable: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The accelerator count comes from the spec, and the row is named by the first
|
||||
// card's model — falling back to its vendor when the model is unknown.
|
||||
func TestSampleOfGPUSummary(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
gpus []GPU
|
||||
wantN int
|
||||
wantModel string
|
||||
}{
|
||||
{"none", nil, 0, ""},
|
||||
{"model", []GPU{{Vendor: "nvidia", Model: "GB10"}}, 1, "GB10"},
|
||||
{"vendor fallback", []GPU{{Vendor: "amd"}}, 1, "amd"},
|
||||
{"multi is counted, first names it", []GPU{{Model: "GB10"}, {Model: "GB10"}}, 2, "GB10"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := sampleOf(Target{ID: "t", Org: "o", Kind: TargetGPU, Spec: Spec{GPUs: tc.gpus}, MetricsAt: 1})
|
||||
if s.GPUs != tc.wantN || s.GPUModel != tc.wantModel {
|
||||
t.Fatalf("want (%d, %q), got (%d, %q)", tc.wantN, tc.wantModel, s.GPUs, s.GPUModel)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// THE cross-package contract: every kind a target can be must be a kind the fleet
|
||||
// series accepts, or heartbeats would silently stop being recorded. This fails the
|
||||
// day someone adds a target kind without teaching the series about it.
|
||||
func TestEveryTargetKindIsAFleetKind(t *testing.T) {
|
||||
fleet := map[string]bool{
|
||||
samples.KindLaptop: true, samples.KindCloud: true, samples.KindGPU: true,
|
||||
samples.KindCluster: true, samples.KindMachine: true, samples.KindWorker: true,
|
||||
}
|
||||
for _, k := range []string{TargetLaptop, TargetCloud, TargetGPU, TargetCluster, TargetMachine} {
|
||||
if !fleet[k] {
|
||||
t.Fatalf("target kind %q is not a fleet sample kind — its heartbeats would be dropped", k)
|
||||
}
|
||||
// Proven end to end: a sample carrying this kind validates.
|
||||
s := sampleOf(Target{ID: "t", Org: "o", Kind: k, MetricsAt: 1})
|
||||
if err := samples.Record(t.Context(), s); err != nil {
|
||||
t.Fatalf("kind %q must be recordable: %v", k, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A write with no heartbeat in it appends nothing — recordSample is a no-op when
|
||||
// the server never stamped a metrics clock.
|
||||
func TestRecordSampleSkipsWhenNoHeartbeat(t *testing.T) {
|
||||
mountApp(t, nil) // sets the `mounted` singleton recordSample logs through
|
||||
// No panic, no goroutine, no write: MetricsAt == 0 means "no sample here".
|
||||
recordSample(mounted, Target{ID: "tgt-1", Org: "acme", Kind: TargetGPU, MetricsAt: 0})
|
||||
}
|
||||
|
||||
// ---- (c) the HTTP contract is untouched by the series ----
|
||||
|
||||
// The heartbeat still 200s with no warehouse, and still returns the snapshot on
|
||||
// the row exactly as before — the series is strictly additive.
|
||||
func TestHeartbeatStill200sWithoutDatastore(t *testing.T) {
|
||||
app := mountApp(t, nil)
|
||||
|
||||
code, body := do(t, app, http.MethodPost, "/v1/agents/targets", "acme", map[string]any{
|
||||
"label": "Box", "kind": TargetGPU, "host": "box.local",
|
||||
"spec": map[string]any{"os": "linux", "cpus": 20, "gpus": []map[string]any{{"vendor": "nvidia", "model": "GB10"}}},
|
||||
"metrics": map[string]any{"load1": 2.5, "gpuUtil": 0.75, "memUsed": 100},
|
||||
})
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("register want 201 without a datastore, got %d (%s)", code, body)
|
||||
}
|
||||
var created targetView
|
||||
if err := json.Unmarshal(body, &created); err != nil {
|
||||
t.Fatalf("shape: %v (%s)", err, body)
|
||||
}
|
||||
if created.Metrics == nil || created.Metrics.GPUUtil != 0.75 {
|
||||
t.Fatalf("the snapshot on the row must be unchanged: %+v", created.Metrics)
|
||||
}
|
||||
if created.MetricsAt == "" {
|
||||
t.Fatal("the server must still stamp the heartbeat clock")
|
||||
}
|
||||
|
||||
// The heartbeat itself.
|
||||
code, body = do(t, app, http.MethodPatch, "/v1/agents/targets/"+created.ID, "acme", map[string]any{
|
||||
"metrics": map[string]any{"load1": 4, "gpuUtil": 0.9, "memUsed": 200},
|
||||
})
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("heartbeat want 200 without a datastore, got %d (%s)", code, body)
|
||||
}
|
||||
var beat targetView
|
||||
if err := json.Unmarshal(body, &beat); err != nil {
|
||||
t.Fatalf("shape: %v (%s)", err, body)
|
||||
}
|
||||
if beat.Metrics == nil || beat.Metrics.GPUUtil != 0.9 || beat.Metrics.Load1 != 4 {
|
||||
t.Fatalf("the heartbeat must still refresh the row snapshot: %+v", beat.Metrics)
|
||||
}
|
||||
|
||||
// A re-link (same org+host) is idempotent and still carries a heartbeat.
|
||||
code, body = do(t, app, http.MethodPost, "/v1/agents/targets", "acme", map[string]any{
|
||||
"label": "Box", "kind": TargetGPU, "host": "box.local",
|
||||
"metrics": map[string]any{"load1": 1},
|
||||
})
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("re-link want 200 (idempotent), got %d (%s)", code, body)
|
||||
}
|
||||
var relinked targetView
|
||||
if err := json.Unmarshal(body, &relinked); err != nil {
|
||||
t.Fatalf("shape: %v (%s)", err, body)
|
||||
}
|
||||
if relinked.ID != created.ID {
|
||||
t.Fatalf("a re-link must refresh the SAME target: %s != %s", relinked.ID, created.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the in-process seam ----
|
||||
|
||||
// TargetsForOrg / LoadOn are org-keyed and fail closed — the board reads through
|
||||
// them, so a cross-tenant id must never resolve.
|
||||
func TestInProcessSeamIsOrgScopedAndFailsClosed(t *testing.T) {
|
||||
app := mountApp(t, nil)
|
||||
code, body := do(t, app, http.MethodPost, "/v1/agents/targets", "acme", map[string]any{
|
||||
"label": "Secret", "kind": TargetGPU, "host": "secret.local",
|
||||
})
|
||||
if code != http.StatusCreated {
|
||||
t.Fatalf("register: %d (%s)", code, body)
|
||||
}
|
||||
var created targetView
|
||||
_ = json.Unmarshal(body, &created)
|
||||
|
||||
// The owner sees it.
|
||||
own, err := TargetsForOrg(t.Context(), "acme")
|
||||
if err != nil {
|
||||
t.Fatalf("TargetsForOrg(acme): %v", err)
|
||||
}
|
||||
if len(own) != 1 || own[0].ID != created.ID {
|
||||
t.Fatalf("the owner must see its target, got %+v", own)
|
||||
}
|
||||
|
||||
// Another tenant sees nothing — the same id is unreachable.
|
||||
other, err := TargetsForOrg(t.Context(), "other")
|
||||
if err != nil {
|
||||
t.Fatalf("TargetsForOrg(other): %v", err)
|
||||
}
|
||||
if len(other) != 0 {
|
||||
t.Fatalf("CROSS-TENANT LEAK: org 'other' enumerated %+v", other)
|
||||
}
|
||||
|
||||
// A blank/oversized org fails closed on both.
|
||||
for _, bad := range []string{"", " "} {
|
||||
if _, err := TargetsForOrg(t.Context(), bad); err == nil {
|
||||
t.Fatalf("TargetsForOrg(%q) must fail closed", bad)
|
||||
}
|
||||
if _, err := LoadOn(t.Context(), bad, created.ID, ""); err == nil {
|
||||
t.Fatalf("LoadOn(%q) must fail closed", bad)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadOn is org-keyed too: the foreign tenant resolves no load for the id.
|
||||
load, err := LoadOn(t.Context(), "other", created.ID, "secret.local")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOn(other): %v", err)
|
||||
}
|
||||
if load.Sessions != 0 || load.Running != 0 {
|
||||
t.Fatalf("CROSS-TENANT LEAK: foreign load %+v", load)
|
||||
}
|
||||
}
|
||||
+46
-2
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
openai "github.com/hanzoai/go-openai"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
@@ -156,6 +157,12 @@ func (a *httpAI) ChatCompletion(ctx context.Context, req *types.ChatRequest) (*t
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, "chat completion failed")
|
||||
// Tag a transient overload (429/5xx/"overloaded") with types.ErrUpstreamBusy
|
||||
// so the agent runner can retry/fail over; a permanent error is left untagged
|
||||
// and fails fast. The message is preserved either way.
|
||||
if transientChat(err) {
|
||||
err = fmt.Errorf("%w: %w", err, types.ErrUpstreamBusy)
|
||||
}
|
||||
return nil, fmt.Errorf("cloud: chat completion (model %q): %w", model, err)
|
||||
}
|
||||
span.SetAttributes(
|
||||
@@ -164,8 +171,10 @@ func (a *httpAI) ChatCompletion(ctx context.Context, req *types.ChatRequest) (*t
|
||||
attribute.Int("gen_ai.usage.output_tokens", resp.Usage.CompletionTokens),
|
||||
)
|
||||
if len(resp.Choices) == 0 {
|
||||
// A 200 with no choices is the gateway's "overloaded, no capacity" shape —
|
||||
// transient, so tag it busy for retry/failover rather than dropping the reply.
|
||||
span.SetStatus(codes.Error, "no choices")
|
||||
return nil, fmt.Errorf("cloud: chat completion (model %q): upstream returned no choices", model)
|
||||
return nil, fmt.Errorf("cloud: chat completion (model %q): upstream returned no choices: %w", model, types.ErrUpstreamBusy)
|
||||
}
|
||||
return &types.ChatResponse{
|
||||
Content: resp.Choices[0].Message.Content,
|
||||
@@ -175,6 +184,41 @@ func (a *httpAI) ChatCompletion(ctx context.Context, req *types.ChatRequest) (*t
|
||||
}, nil
|
||||
}
|
||||
|
||||
// transientChat reports whether an upstream chat-completion error is a transient
|
||||
// overload the agent runner may safely retry or fail over on: HTTP
|
||||
// 429/500/502/503/504, or a gateway that surfaces "overloaded" without a typed
|
||||
// status. A permanent failure — a 4xx that is not 429 (bad request, auth, an
|
||||
// unserved model) — returns false so it fails fast instead of burning retries.
|
||||
func transientChat(err error) bool {
|
||||
if code, ok := httpStatus(err); ok {
|
||||
switch code {
|
||||
case http.StatusTooManyRequests, http.StatusInternalServerError,
|
||||
http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
// No typed status (a bare transport/overload message) — treat an explicit
|
||||
// "overloaded" as transient; anything else is not classifiable, so not retried.
|
||||
return strings.Contains(strings.ToLower(err.Error()), "overloaded")
|
||||
}
|
||||
|
||||
// httpStatus extracts the upstream HTTP status from a go-openai error
|
||||
// (*openai.APIError for a decoded error body, *openai.RequestError for a raw
|
||||
// non-2xx), returning ok=false when the error carries no status.
|
||||
func httpStatus(err error) (int, bool) {
|
||||
var apiErr *openai.APIError
|
||||
if errors.As(err, &apiErr) && apiErr.HTTPStatusCode > 0 {
|
||||
return apiErr.HTTPStatusCode, true
|
||||
}
|
||||
var reqErr *openai.RequestError
|
||||
if errors.As(err, &reqErr) && reqErr.HTTPStatusCode > 0 {
|
||||
return reqErr.HTTPStatusCode, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Embed returns one vector per input from the gateway's OpenAI-compatible
|
||||
// /embeddings, authenticated by the SAME credential as ChatCompletion — so the
|
||||
// semantic tier bills and meters through the ONE org/project-aligned path, never
|
||||
|
||||
@@ -3,6 +3,7 @@ package clients
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -100,6 +101,49 @@ func TestAIHTTP_UpstreamErrorMapped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIHTTP_TransientTagged proves the classification the agent runner relies on:
|
||||
// a transient overload (429 / 5xx / empty-choices) is tagged types.ErrUpstreamBusy
|
||||
// so the runner retries/fails over, while a permanent 4xx (400) is NOT tagged so it
|
||||
// fails fast. Without this split the runner would either drop replies on a passing
|
||||
// 429 or spin retries on an unrecoverable bad request.
|
||||
func TestAIHTTP_TransientTagged(t *testing.T) {
|
||||
serve := func(status int, body string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if status != 0 {
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
transit bool
|
||||
}{
|
||||
{"429 overloaded", http.StatusTooManyRequests, `{"error":{"message":"Platform overloaded"}}`, true},
|
||||
{"503 unavailable", http.StatusServiceUnavailable, `{"error":{"message":"unavailable"}}`, true},
|
||||
{"500 server", http.StatusInternalServerError, `{"error":{"message":"boom"}}`, true},
|
||||
{"200 empty choices", 0, `{"id":"x","object":"chat.completion","choices":[]}`, true},
|
||||
{"400 bad request", http.StatusBadRequest, `{"error":{"message":"bad input"}}`, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := serve(tc.status, tc.body)
|
||||
defer srv.Close()
|
||||
_, err := AIHTTPAt(srv.URL, "sk-test", "deepseek-v4-flash").
|
||||
ChatCompletion(context.Background(), &types.ChatRequest{Prompt: "x"})
|
||||
if err == nil {
|
||||
t.Fatalf("%s: expected an error", tc.name)
|
||||
}
|
||||
if got := errors.Is(err, types.ErrUpstreamBusy); got != tc.transit {
|
||||
t.Fatalf("%s: errors.Is(ErrUpstreamBusy)=%v, want %v (err=%v)", tc.name, got, tc.transit, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIHTTP_ServerErrorMapped asserts a 5xx upstream also maps to an error.
|
||||
func TestAIHTTP_ServerErrorMapped(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
|
||||
@@ -100,15 +100,30 @@ func routes(app *zip.App, s *cloud.Service[state]) {
|
||||
app.Get("/v1/analytics/timeseries", cloud.Handle(s, timeseries))
|
||||
app.Get("/v1/analytics/top", cloud.Handle(s, top))
|
||||
|
||||
// Capture (WRITE) side — the ingest that fills hanzo.events (capture.go). All
|
||||
// POST, all tenant-gated in-handler. /v1/tracker is the page-unload beacon
|
||||
// alias (bare route; never collides with the /v1/tracker/projects* issue tracker).
|
||||
// Capture (WRITE) side — the ingest that fills hanzo.events. POST /v1/event
|
||||
// (event.go) is the ONE canonical front door: body Event | [Event], org
|
||||
// resolved IAM-only and fail-closed, into the ONE write core (ingestEvents).
|
||||
app.Post("/v1/event", cloud.Handle(s, eventIngest))
|
||||
|
||||
// Publishable-key direct ingest (publishable.go) — the FASTEST path: a
|
||||
// write-only pk_ key (HMAC-signed org, no IAM/DB hop) authenticates
|
||||
// {batch:[WireEvent]} straight into the ONE write core. /v1/ingest/keys mints a
|
||||
// pk_ for the caller's org; /v1/errors is the type:'error' read lens (validated
|
||||
// principal — reads never accept the write-only key).
|
||||
app.Post("/v1/ingest", cloud.Handle(s, ingest))
|
||||
app.Post("/v1/ingest/keys", cloud.Handle(s, mintKey))
|
||||
app.Get("/v1/errors", cloud.Handle(s, errorsLens))
|
||||
|
||||
// DEPRECATED ingest aliases — thin wire adapters that normalize onto the SAME
|
||||
// write core (log a one-shot deprecation, keep working). /v1/analytics{,/batch}
|
||||
// and /v1/tracker speak the Segment/beacon CaptureBatch wire; /v1/tracker is a
|
||||
// bare route (never collides with the /v1/tracker/projects* issue tracker).
|
||||
app.Post("/v1/analytics", cloud.Handle(s, capture))
|
||||
app.Post("/v1/analytics/batch", cloud.Handle(s, capture))
|
||||
app.Post("/v1/tracker", cloud.Handle(s, capture))
|
||||
|
||||
// /v1/insights — the unified native surface (insights.go): PostHog-wire
|
||||
// ingest + console reads over the SAME engine. Flags live at /v1/flags.
|
||||
// /v1/insights — console reads over the SAME engine + the DEPRECATED PostHog-
|
||||
// wire ingest adapter (/v1/insights/e → the ONE write core). Flags live at /v1/flags.
|
||||
app.Get("/v1/insights/health", cloud.Handle(s, insightsHealth))
|
||||
app.Post("/v1/insights/e", cloud.Handle(s, insightsIngest))
|
||||
app.Get("/v1/insights/events", cloud.Handle(s, insightsEvents))
|
||||
|
||||
+168
-30
@@ -52,6 +52,7 @@ import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -172,6 +173,7 @@ type CaptureEvent struct {
|
||||
Quantity uint32 `json:"quantity"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
Currency string `json:"currency"`
|
||||
Error *Exception `json:"error"` // set on type:'error' events (folded into properties.$exception)
|
||||
Properties map[string]any `json:"properties"`
|
||||
Library string `json:"library"`
|
||||
LibraryVer string `json:"libraryVersion"`
|
||||
@@ -296,12 +298,20 @@ func resolveEventName(e CaptureEvent) string {
|
||||
return "$identify"
|
||||
case "group":
|
||||
return "$group"
|
||||
case "error":
|
||||
if name == "" {
|
||||
return "$error"
|
||||
}
|
||||
return name
|
||||
default: // "event"
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
// canonicalType folds the type to the closed set {pageview,identify,group,event}.
|
||||
// canonicalType folds the type to the closed set
|
||||
// {pageview,identify,group,error,event}. `error` is first-class so the ingest can
|
||||
// store type:'error' events under event_type='error' — the key the /v1/errors
|
||||
// read lens filters on. An unknown type still folds to "event".
|
||||
func canonicalType(t string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(t)) {
|
||||
case "pageview", "page":
|
||||
@@ -310,6 +320,8 @@ func canonicalType(t string) string {
|
||||
return "identify"
|
||||
case "group":
|
||||
return "group"
|
||||
case "error":
|
||||
return "error"
|
||||
default:
|
||||
return "event"
|
||||
}
|
||||
@@ -498,19 +510,72 @@ func publicCaptureEnabled() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// captureTenant resolves the tenant a batch is attributed to. A VALIDATED
|
||||
// principal always wins (authenticated product traffic → its own org). Otherwise,
|
||||
// for anonymous marketing traffic, the tenant is the PUBLIC brand org derived
|
||||
// SERVER-SIDE from the request Host via the white-label registry — never a
|
||||
// client-claimed org, so the isolation invariant holds: a caller with no bearer
|
||||
// can only ever write into the brand-public partition of the Host it actually
|
||||
// reached, and a forged X-Org-Id is ignored exactly as on the read path. An
|
||||
// unrecognized Host is refused (we never dump anonymous events into a default
|
||||
// org). Returns ("", false) when the caller must be answered 403.
|
||||
// resolveKeyOrg maps a presented project/API key to its org through the ONE IAM
|
||||
// key seam (cloud.OrgForKey). It is a package var ONLY so a test can substitute a
|
||||
// resolver without standing up IAM; production is always cloud.OrgForKey.
|
||||
var resolveKeyOrg = cloud.OrgForKey
|
||||
|
||||
// projectKey returns the project/API key a keyed SDK presents OUT-OF-BAND of the
|
||||
// Authorization header — the transports SanitizeIdentity does NOT mint identity
|
||||
// from, so they never reach tenant() as a principal. In priority order: the
|
||||
// ?api_key= query, the x-api-key / api-key headers, and the PostHog-wire body
|
||||
// field `api_key` (posthog-js and the insights-go batch envelope put it there).
|
||||
// "" when none is present.
|
||||
//
|
||||
// The body is PEEKED via c.Body() — fasthttp buffers the full body, so the later
|
||||
// c.Bind in the handler re-reads the same bytes; peeking does not consume it. Only
|
||||
// the api_key field is decoded (a bad/unrelated JSON body simply yields "").
|
||||
func projectKey(c *zip.Ctx) string {
|
||||
if k := trim(c.Query("api_key")); k != "" {
|
||||
return k
|
||||
}
|
||||
if k := trim(c.Header("x-api-key")); k != "" {
|
||||
return k
|
||||
}
|
||||
if k := trim(c.Header("api-key")); k != "" {
|
||||
return k
|
||||
}
|
||||
if body := c.Body(); len(body) > 0 {
|
||||
var probe struct {
|
||||
APIKey string `json:"api_key"`
|
||||
}
|
||||
if json.Unmarshal(body, &probe) == nil {
|
||||
if k := trim(probe.APIKey); k != "" {
|
||||
return k
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// captureTenant resolves the tenant a batch is attributed to, in strict trust
|
||||
// order:
|
||||
//
|
||||
// 1. A VALIDATED principal always wins (authenticated product traffic → its own
|
||||
// org; this also covers a Hanzo key sent as a bearer, which SanitizeIdentity
|
||||
// has already resolved to a principal upstream).
|
||||
// 2. Otherwise, if the caller PRESENTS a project key out-of-band (posthog-js /
|
||||
// insights-go: api_key in the body/query/x-api-key), resolve it to its org
|
||||
// through the ONE IAM key seam. This FAILS CLOSED: a presented-but-unresolvable
|
||||
// key is refused (→ 403), NEVER falling through to the brand-host fallback —
|
||||
// attributing a keyed request to the wrong (brand-public) partition would be a
|
||||
// cross-tenant write.
|
||||
// 3. Only for TRULY anonymous traffic (no principal, no key) is the tenant the
|
||||
// PUBLIC brand org derived SERVER-SIDE from the request Host via the
|
||||
// white-label registry — never a client-claimed org. An unrecognized Host is
|
||||
// refused (we never dump anonymous events into a default org).
|
||||
//
|
||||
// Returns ("", false) when the caller must be answered 403.
|
||||
func captureTenant(c *zip.Ctx) (string, bool) {
|
||||
if org, ok := tenant(c); ok {
|
||||
return org, true
|
||||
}
|
||||
if key := projectKey(c); key != "" {
|
||||
if org, ok := resolveKeyOrg(c.Context(), key); ok {
|
||||
return org, true
|
||||
}
|
||||
return "", false // presented key that does not resolve → fail CLOSED
|
||||
}
|
||||
if !publicCaptureEnabled() {
|
||||
return "", false
|
||||
}
|
||||
@@ -520,36 +585,88 @@ func captureTenant(c *zip.Ctx) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// capture ingests one batch into hanzo.events, tenant-scoped. Shared by
|
||||
// /v1/analytics, /v1/analytics/batch, and /v1/tracker.
|
||||
func capture(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := captureTenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer or a recognized brand host required")
|
||||
// ── ONE write core ───────────────────────────────────────────────────────────
|
||||
|
||||
// event source tags — the ingest adapter each row arrived through. Stamped into
|
||||
// properties.$source by ingestEvents so the ONE hanzo.events table stays honest
|
||||
// about origin (canonical vs. deprecated wire) WITHOUT a second table or a schema
|
||||
// migration: the read lenses are unchanged and $source is queryable in the
|
||||
// properties JSON, which is exactly the migration signal for the alias sunset.
|
||||
const (
|
||||
sourceEvent = "event" // canonical POST /v1/event (native Event wire)
|
||||
sourcePostHog = "posthog" // POST /v1/insights/e (PostHog wire adapter, deprecated)
|
||||
sourceCapture = "capture" // POST /v1/analytics{,/batch}, /v1/tracker (Segment/beacon, deprecated)
|
||||
)
|
||||
|
||||
// withSource returns a copy of p carrying $source=source (the ingest adapter), so
|
||||
// normalizeEvent's scrub+store path records origin as a property. nil-safe; never
|
||||
// mutates the caller's map (the adapters share their event structs).
|
||||
func withSource(p map[string]any, source string) map[string]any {
|
||||
if source == "" {
|
||||
return p
|
||||
}
|
||||
var batch CaptureBatch
|
||||
if err := c.Bind(&batch); err != nil {
|
||||
return zip.ErrBadRequest("malformed capture batch")
|
||||
out := make(map[string]any, len(p)+1)
|
||||
for k, v := range p {
|
||||
out[k] = v
|
||||
}
|
||||
evs := batch.events()
|
||||
out["$source"] = source
|
||||
return out
|
||||
}
|
||||
|
||||
// deprecatedOnce records one deprecation log per alias path per process, so a
|
||||
// high-volume ingest alias signals its sunset exactly once instead of flooding.
|
||||
// A plain mutex-guarded map (the alias set is tiny — /v1/analytics, /batch,
|
||||
// /tracker) rather than sync.Map: the latter (Go's HashTrieMap) was panicking
|
||||
// "ran out of hash bits" under the hot ingest path, 500-ing EVERY capture. A
|
||||
// bounded map+mutex has no trie state to corrupt and cannot panic here.
|
||||
var (
|
||||
deprecatedMu sync.Mutex
|
||||
deprecatedSeen = make(map[string]struct{}, 8)
|
||||
)
|
||||
|
||||
// deprecated logs (once per path) that a superseded ingest alias was hit, pointing
|
||||
// callers at the canonical front door. It NEVER changes behavior — the alias keeps
|
||||
// working — it only records the migration signal (also visible as $source in the
|
||||
// warehouse).
|
||||
func deprecated(s *cloud.Service[state], c *zip.Ctx, canonical string) {
|
||||
p := c.Path()
|
||||
deprecatedMu.Lock()
|
||||
_, seen := deprecatedSeen[p]
|
||||
if !seen {
|
||||
deprecatedSeen[p] = struct{}{}
|
||||
}
|
||||
deprecatedMu.Unlock()
|
||||
if seen {
|
||||
return
|
||||
}
|
||||
s.Log.Warn("deprecated analytics ingest endpoint; migrate to the canonical event front door",
|
||||
"path", p, "canonical", canonical)
|
||||
}
|
||||
|
||||
// ingestEvents is the ONE write core: normalize → scrub → batch INSERT into the
|
||||
// ONE hanzo.events table. org is the SERVER-resolved tenant (never client input);
|
||||
// source tags the ingest adapter. Every front door — the canonical /v1/event and
|
||||
// the deprecated PostHog / Segment / beacon adapters — funnels here, so there is
|
||||
// exactly one write path. Returns the honest accepted/dropped receipt; the errors
|
||||
// it returns are already HTTP-shaped (zip) for the handler to pass straight up.
|
||||
func ingestEvents(ctx context.Context, org, source string, evs []CaptureEvent) (CaptureResult, error) {
|
||||
if len(evs) == 0 {
|
||||
return c.JSON(http.StatusOK, CaptureResult{})
|
||||
return CaptureResult{}, nil
|
||||
}
|
||||
if len(evs) > maxBatch {
|
||||
return zip.ErrBadRequest("batch too large")
|
||||
return CaptureResult{}, zip.ErrBadRequest("batch too large")
|
||||
}
|
||||
if err := requireDatastore(); err != nil {
|
||||
return err
|
||||
return CaptureResult{}, err
|
||||
}
|
||||
ctx := c.Context()
|
||||
if err := EnsureEventsTable(ctx); err != nil {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "analytics warehouse unavailable: %v", err)
|
||||
return CaptureResult{}, zip.Errorf(http.StatusServiceUnavailable, "analytics warehouse unavailable: %v", err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
rows := make([]eventRow, 0, len(evs))
|
||||
dropped := 0
|
||||
for _, e := range evs {
|
||||
e.Properties = withSource(e.Properties, source)
|
||||
row, ok := normalizeEvent(org, now, e)
|
||||
if !ok {
|
||||
dropped++
|
||||
@@ -558,12 +675,33 @@ func capture(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
rows = append(rows, row)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return c.JSON(http.StatusOK, CaptureResult{Dropped: dropped})
|
||||
return CaptureResult{Dropped: dropped}, nil
|
||||
}
|
||||
|
||||
stmt, args := buildEventsInsert(rows)
|
||||
if err := aiobject.DatastoreExec(ctx, stmt, args...); err != nil {
|
||||
return warehouseErr("capture", err)
|
||||
return CaptureResult{}, warehouseErr("capture", err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, CaptureResult{Accepted: len(rows), Dropped: dropped})
|
||||
return CaptureResult{Accepted: len(rows), Dropped: dropped}, nil
|
||||
}
|
||||
|
||||
// capture ingests a Segment/beacon batch into hanzo.events, tenant-scoped. It is
|
||||
// the DEPRECATED wire adapter behind /v1/analytics, /v1/analytics/batch, and
|
||||
// /v1/tracker: a thin CaptureBatch decoder over the ONE write core (ingestEvents).
|
||||
// New callers post the canonical Event to /v1/event; this alias keeps working and
|
||||
// keeps captureTenant's brand-host path for anonymous marketing traffic.
|
||||
func capture(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
deprecated(s, c, "/v1/event")
|
||||
org, ok := captureTenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer or a recognized brand host required")
|
||||
}
|
||||
var batch CaptureBatch
|
||||
if err := c.Bind(&batch); err != nil {
|
||||
return zip.ErrBadRequest("malformed capture batch")
|
||||
}
|
||||
res, err := ingestEvents(c.Context(), org, sourceCapture, batch.events())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// Copyright 2023-2026 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.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// These tests cover the project-API-key → org resolution added to captureTenant so
|
||||
// keyed, bearer-less SDK traffic (posthog-js / insights-go batch) maps to a tenant.
|
||||
// They drive the REAL /v1/insights/e handler through the injectable resolveKeyOrg
|
||||
// seam, so no IAM is needed. The observable proxy for "resolved to a tenant" is
|
||||
// "passed the tenant gate" — i.e. NOT 403; without a datastore the handler then
|
||||
// returns 503, so any non-403 status means captureTenant admitted the request.
|
||||
|
||||
// stubResolver swaps resolveKeyOrg for the test and records the key it was handed,
|
||||
// so a test asserts BOTH that projectKey extracted the right key AND that
|
||||
// captureTenant honored the resolution. Restored via t.Cleanup.
|
||||
func stubResolver(t *testing.T, fn func(key string) (string, bool)) *string {
|
||||
t.Helper()
|
||||
var got string
|
||||
orig := resolveKeyOrg
|
||||
resolveKeyOrg = func(_ context.Context, key string) (string, bool) {
|
||||
got = key
|
||||
return fn(key)
|
||||
}
|
||||
t.Cleanup(func() { resolveKeyOrg = orig })
|
||||
return &got
|
||||
}
|
||||
|
||||
// postKeyed issues POST path (with optional ?query) to the mounted app, setting an
|
||||
// optional Host and headers and a raw JSON body — no middleware, mirroring the
|
||||
// SanitizeIdentity-minted-header harness the other analytics tests use.
|
||||
func postKeyed(t *testing.T, app *zip.App, path, host, body string, hdr map[string]string) int {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if host != "" {
|
||||
req.Host = host
|
||||
}
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := app.Fiber().Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test POST %s: %v", path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
// TestCaptureTenant_KeyExtractionReachesResolver: a project key presented in the
|
||||
// body, the ?api_key= query, or the x-api-key header is extracted and handed to the
|
||||
// resolver, and a resolved key passes the tenant gate (never 403).
|
||||
func TestCaptureTenant_KeyExtractionReachesResolver(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
cases := []struct {
|
||||
name, path, body string
|
||||
hdr map[string]string
|
||||
wantKey string
|
||||
}{
|
||||
{"body", "/v1/insights/e", `{"api_key":"hk-body","event":"e","distinct_id":"d"}`, nil, "hk-body"},
|
||||
{"query", "/v1/insights/e?api_key=hk-query", `{"event":"e","distinct_id":"d"}`, nil, "hk-query"},
|
||||
{"x-api-key", "/v1/insights/e", `{"event":"e","distinct_id":"d"}`, map[string]string{"x-api-key": "hk-hdr"}, "hk-hdr"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := stubResolver(t, func(string) (string, bool) { return "acme", true })
|
||||
code := postKeyed(t, app, tc.path, "", tc.body, tc.hdr)
|
||||
if *got != tc.wantKey {
|
||||
t.Fatalf("resolver handed key %q, want %q", *got, tc.wantKey)
|
||||
}
|
||||
if code == http.StatusForbidden {
|
||||
t.Fatalf("a resolved key must pass the tenant gate, got 403")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaptureTenant_UnresolvableKeyFailsClosed: a PRESENTED key that does not
|
||||
// resolve is refused (403) EVEN on a recognized brand host — it must never fall
|
||||
// through to the brand-public partition (that would be a cross-tenant write).
|
||||
func TestCaptureTenant_UnresolvableKeyFailsClosed(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
stubResolver(t, func(string) (string, bool) { return "", false }) // nothing resolves
|
||||
code := postKeyed(t, app, "/v1/insights/e", "hanzo.ai",
|
||||
`{"api_key":"hk-bad","event":"e","distinct_id":"d"}`, nil)
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("presented-but-unresolvable key on a brand host must 403 (fail closed), got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaptureTenant_AnonBrandHostFallsBack: with NO key presented, anonymous
|
||||
// traffic on a recognized brand host still resolves to the brand org (not 403), and
|
||||
// the key resolver is never consulted — the key path only triggers on a real key.
|
||||
func TestCaptureTenant_AnonBrandHostFallsBack(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
stubResolver(t, func(key string) (string, bool) {
|
||||
t.Fatalf("resolver consulted for a keyless request (key=%q)", key)
|
||||
return "", false
|
||||
})
|
||||
code := postKeyed(t, app, "/v1/insights/e", "hanzo.ai",
|
||||
`{"event":"e","distinct_id":"d"}`, nil)
|
||||
if code == http.StatusForbidden {
|
||||
t.Fatalf("anonymous capture on a recognized brand host must pass the tenant gate, got 403")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2023-2026 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.
|
||||
|
||||
// event.go — the ONE canonical event-ingestion front door.
|
||||
//
|
||||
// POST /v1/event body: Event | [Event] -> {accepted, dropped}
|
||||
//
|
||||
// A JSON object is one event; a JSON array IS the batch (there is deliberately no
|
||||
// /v1/event/batch). Every other ingest surface (the PostHog wire at
|
||||
// /v1/insights/e, the Segment/beacon wire at /v1/analytics{,/batch} and
|
||||
// /v1/tracker) is a thin DEPRECATED adapter that normalizes its own wire shape
|
||||
// onto CaptureEvent and funnels through the SAME write core (ingestEvents) into
|
||||
// the SAME hanzo.events table. One write path, many adapters.
|
||||
//
|
||||
// AUTH — IAM ONLY, FAIL-CLOSED: the tenant is resolved SERVER-SIDE from a
|
||||
// validated bearer principal (its owner org) or, for a keyed bearer-less SDK, an
|
||||
// access key resolved through the ONE IAM key seam (cloud.OrgForKey). There is NO
|
||||
// brand-host fallback on this endpoint: an unauthenticated or unresolvable caller
|
||||
// is refused (403), so the canonical door never writes an event into a tenant IAM
|
||||
// did not vouch for. The org is NEVER read from the body.
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// Event is the canonical analytics event — the entire ingest contract in four
|
||||
// fields. Only these are first-class; everything else a caller wants to record
|
||||
// travels in Properties (the scrubber runs over it downstream, same as every
|
||||
// event). The tenant is NOT a field: it is resolved server-side from IAM, so a
|
||||
// caller can only ever write into its OWN org's partition.
|
||||
type Event struct {
|
||||
Event string `json:"event"` // event name (required; empty ⇒ dropped as unroutable)
|
||||
DistinctID string `json:"distinctId"` // the person/visitor id the caller owns
|
||||
Time string `json:"time"` // optional RFC3339; clamped to server-now on skew/absent
|
||||
Properties map[string]any `json:"properties"` // everything non-core
|
||||
}
|
||||
|
||||
// toCapture adapts the canonical Event onto the internal CaptureEvent the write
|
||||
// core consumes. Type is left empty (canonicalType ⇒ "event"); no $-property is
|
||||
// promoted to a column here — /v1/event stays a strict four-field contract, and
|
||||
// every non-core field the caller sent stays in Properties.
|
||||
func (e Event) toCapture() CaptureEvent {
|
||||
return CaptureEvent{
|
||||
Event: e.Event,
|
||||
DistinctID: e.DistinctID,
|
||||
Timestamp: e.Time,
|
||||
Properties: e.Properties,
|
||||
}
|
||||
}
|
||||
|
||||
// eventTenant resolves the tenant for POST /v1/event — IAM ONLY, FAIL-CLOSED. A
|
||||
// validated bearer principal wins (its owner org); otherwise a presented access
|
||||
// key is resolved to its org through the ONE IAM key seam (resolveKeyOrg →
|
||||
// cloud.OrgForKey). There is NO brand-host fallback: an unauthenticated or
|
||||
// unresolvable caller returns ("", false) → 403. (The deprecated aliases keep
|
||||
// captureTenant's brand-host path for anonymous marketing traffic; the canonical
|
||||
// endpoint is deliberately stricter — IAM is the only tenant authority here.)
|
||||
func eventTenant(c *zip.Ctx) (string, bool) {
|
||||
if org, ok := tenant(c); ok {
|
||||
return org, true
|
||||
}
|
||||
if key := projectKey(c); key != "" {
|
||||
if org, ok := resolveKeyOrg(c.Context(), key); ok {
|
||||
return org, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// decodeEvents decodes a request body as Event | []Event. The first non-space
|
||||
// byte decides: '[' ⇒ the array batch, anything else ⇒ a single Event. An empty
|
||||
// body yields no events (an honest empty receipt, not an error). Pure over the
|
||||
// raw bytes (the handler passes c.Body() — fasthttp-buffered, the same bytes
|
||||
// projectKey peeked) so the decode is driven directly by tests.
|
||||
func decodeEvents(body []byte) ([]Event, error) {
|
||||
i := 0
|
||||
for i < len(body) {
|
||||
if b := body[i]; b == ' ' || b == '\t' || b == '\r' || b == '\n' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if i >= len(body) {
|
||||
return nil, nil
|
||||
}
|
||||
if body[i] == '[' {
|
||||
var evs []Event
|
||||
if err := json.Unmarshal(body, &evs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return evs, nil
|
||||
}
|
||||
var e Event
|
||||
if err := json.Unmarshal(body, &e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []Event{e}, nil
|
||||
}
|
||||
|
||||
// eventIngest answers POST /v1/event — the ONE canonical ingestion front door.
|
||||
// Org is IAM-derived and fail-closed (eventTenant); the body is Event | [Event];
|
||||
// every event flows through the ONE write core (ingestEvents) into the ONE
|
||||
// hanzo.events table, tagged source=event.
|
||||
func eventIngest(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := eventTenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer or a resolvable access key required")
|
||||
}
|
||||
evs, err := decodeEvents(c.Body())
|
||||
if err != nil {
|
||||
return zip.ErrBadRequest("malformed event payload")
|
||||
}
|
||||
caps := make([]CaptureEvent, len(evs))
|
||||
for i, e := range evs {
|
||||
caps[i] = e.toCapture()
|
||||
}
|
||||
res, err := ingestEvents(c.Context(), org, sourceEvent, caps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(http.StatusOK, res)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// Copyright 2023-2026 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.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── decodeEvents: Event | []Event (single + batch) ──────────────────────────
|
||||
|
||||
func TestDecodeEvents_Single(t *testing.T) {
|
||||
evs, err := decodeEvents([]byte(`{"event":"signup","distinctId":"u1","properties":{"plan":"pro"}}`))
|
||||
if err != nil {
|
||||
t.Fatalf("decode single: %v", err)
|
||||
}
|
||||
if len(evs) != 1 {
|
||||
t.Fatalf("single want 1 event, got %d", len(evs))
|
||||
}
|
||||
if evs[0].Event != "signup" || evs[0].DistinctID != "u1" {
|
||||
t.Fatalf("single decoded = %+v", evs[0])
|
||||
}
|
||||
if evs[0].Properties["plan"] != "pro" {
|
||||
t.Fatalf("single properties = %v", evs[0].Properties)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeEvents_Batch(t *testing.T) {
|
||||
evs, err := decodeEvents([]byte(`[{"event":"a","distinctId":"d"},{"event":"b","distinctId":"d"}]`))
|
||||
if err != nil {
|
||||
t.Fatalf("decode batch: %v", err)
|
||||
}
|
||||
if len(evs) != 2 || evs[0].Event != "a" || evs[1].Event != "b" {
|
||||
t.Fatalf("batch decoded = %+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeEvents_BatchLeadingWhitespace(t *testing.T) {
|
||||
// The array is detected past leading whitespace, not only at byte 0.
|
||||
evs, err := decodeEvents([]byte(" \n\t [{\"event\":\"a\"}]"))
|
||||
if err != nil {
|
||||
t.Fatalf("decode ws-batch: %v", err)
|
||||
}
|
||||
if len(evs) != 1 || evs[0].Event != "a" {
|
||||
t.Fatalf("ws-batch decoded = %+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeEvents_EmptyIsNoEvents(t *testing.T) {
|
||||
// Empty / whitespace-only body ⇒ zero events, NOT an error (honest empty receipt).
|
||||
for _, b := range []string{"", " ", "\n\t"} {
|
||||
evs, err := decodeEvents([]byte(b))
|
||||
if err != nil || len(evs) != 0 {
|
||||
t.Fatalf("empty %q ⇒ evs=%v err=%v", b, evs, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeEvents_Malformed(t *testing.T) {
|
||||
for _, b := range []string{`{"event":`, `[{"event":"a"},`, `not json`} {
|
||||
if _, err := decodeEvents([]byte(b)); err == nil {
|
||||
t.Fatalf("malformed %q want error, got nil", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── adapter → Event/CaptureEvent normalization ──────────────────────────────
|
||||
|
||||
// TestEventToCapture: the canonical Event maps onto CaptureEvent with ONLY the
|
||||
// four core fields promoted; Type is left empty (⇒ "event") and everything else
|
||||
// stays in Properties (nothing is lifted to a column).
|
||||
func TestEventToCapture(t *testing.T) {
|
||||
e := Event{
|
||||
Event: "purchase",
|
||||
DistinctID: "u9",
|
||||
Time: "2026-07-18T00:00:00Z",
|
||||
Properties: map[string]any{"amount": 42, "$current_url": "https://x/y"},
|
||||
}
|
||||
ce := e.toCapture()
|
||||
if ce.Event != "purchase" || ce.DistinctID != "u9" || ce.Timestamp != "2026-07-18T00:00:00Z" {
|
||||
t.Fatalf("core fields = %+v", ce)
|
||||
}
|
||||
if ce.Type != "" {
|
||||
t.Fatalf("Type must be empty (⇒ canonicalType event), got %q", ce.Type)
|
||||
}
|
||||
if ce.URL != "" {
|
||||
t.Fatalf("no $-property is promoted to a column on the canonical wire; URL=%q", ce.URL)
|
||||
}
|
||||
// non-core stays in properties
|
||||
if ce.Properties["amount"] != 42 || ce.Properties["$current_url"] != "https://x/y" {
|
||||
t.Fatalf("properties passthrough = %v", ce.Properties)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEventNormalizeThroughCore: a canonical Event, adapted and normalized, yields
|
||||
// a row stamped with the SERVER org and the resolved event name.
|
||||
func TestEventNormalizeThroughCore(t *testing.T) {
|
||||
row, ok := normalizeEvent("acme", time.Now(), Event{Event: "signup", DistinctID: "u1"}.toCapture())
|
||||
if !ok {
|
||||
t.Fatal("want routable")
|
||||
}
|
||||
if row.tenant != "acme" || row.event != "signup" || row.eventType != "event" {
|
||||
t.Fatalf("row = tenant %q event %q type %q", row.tenant, row.event, row.eventType)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsightsAdapterNormalization: the PostHog wire adapter lifts well-known
|
||||
// $-properties to columns (that is its job) — the OTHER adapter feeding the ONE
|
||||
// core, distinct from the canonical Event wire.
|
||||
func TestInsightsAdapterNormalization(t *testing.T) {
|
||||
ce := insightsEvent{
|
||||
Event: "$pageview",
|
||||
DistinctID: "d",
|
||||
Properties: map[string]any{"$current_url": "https://x/y", "$session_id": "s1"},
|
||||
}.toCapture()
|
||||
if ce.Type != "pageview" {
|
||||
t.Fatalf("posthog $pageview ⇒ type pageview, got %q", ce.Type)
|
||||
}
|
||||
if ce.URL != "https://x/y" || ce.SessionID != "s1" {
|
||||
t.Fatalf("posthog $-props ⇒ columns: url=%q session=%q", ce.URL, ce.SessionID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaptureBatchAdapter: the Segment/beacon adapter prefers `batch`, falling
|
||||
// back to `events`.
|
||||
func TestCaptureBatchAdapter(t *testing.T) {
|
||||
if got := (CaptureBatch{Batch: []CaptureEvent{{Event: "a"}}, Events: []CaptureEvent{{Event: "b"}}}).events(); len(got) != 1 || got[0].Event != "a" {
|
||||
t.Fatalf("batch preferred over events, got %+v", got)
|
||||
}
|
||||
if got := (CaptureBatch{Events: []CaptureEvent{{Event: "b"}}}).events(); len(got) != 1 || got[0].Event != "b" {
|
||||
t.Fatalf("events fallback, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── source tagging (the $source property, one-table origin discriminator) ────
|
||||
|
||||
func TestWithSource(t *testing.T) {
|
||||
// stamps $source
|
||||
got := withSource(nil, sourceEvent)
|
||||
if got["$source"] != "event" {
|
||||
t.Fatalf("withSource(nil,event) = %v", got)
|
||||
}
|
||||
// does not mutate the caller's map, and preserves existing keys
|
||||
orig := map[string]any{"a": 1}
|
||||
out := withSource(orig, sourcePostHog)
|
||||
if out["a"] != 1 || out["$source"] != "posthog" {
|
||||
t.Fatalf("withSource copy = %v", out)
|
||||
}
|
||||
if _, leaked := orig["$source"]; leaked {
|
||||
t.Fatalf("withSource mutated the caller's map: %v", orig)
|
||||
}
|
||||
// empty source is a no-op passthrough (same map)
|
||||
if got := withSource(orig, ""); got["$source"] != nil {
|
||||
t.Fatalf("empty source must not stamp, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSourceStampedIntoProperties: source flows through withSource → normalizeEvent
|
||||
// → the stored properties JSON, so the ONE hanzo.events table carries origin
|
||||
// WITHOUT a schema column.
|
||||
func TestSourceStampedIntoProperties(t *testing.T) {
|
||||
e := CaptureEvent{Event: "x", Properties: withSource(nil, sourceEvent)}
|
||||
row, ok := normalizeEvent("acme", time.Now(), e)
|
||||
if !ok {
|
||||
t.Fatal("want routable")
|
||||
}
|
||||
props := decodeProps(t, row.properties)
|
||||
if props["$source"] != "event" {
|
||||
t.Fatalf("row.properties $source = %v (props=%v)", props["$source"], props)
|
||||
}
|
||||
}
|
||||
|
||||
// ── POST /v1/event: IAM-only, fail-closed auth ──────────────────────────────
|
||||
//
|
||||
// Observable proxy (mirrors capture_keyorg_test): a REFUSED request is 403; an
|
||||
// ADMITTED one reaches requireDatastore and returns 503 (no datastore in tests).
|
||||
// So "not 403" ⇒ the tenant gate admitted the request.
|
||||
|
||||
func TestEvent_NoPrincipalNoKeyForbidden(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
if code, _ := doBody(t, app, http.MethodPost, "/v1/event", "", "", `{"event":"e","distinctId":"d"}`); code != http.StatusForbidden {
|
||||
t.Fatalf("no-principal no-key /v1/event want 403, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvent_BearerPrincipalAdmitted(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
// A validated principal (X-User/X-Org) is admitted → 503 (datastore down), not 403.
|
||||
if code, _ := doBody(t, app, http.MethodPost, "/v1/event", "user-dave", "acme", `{"event":"signup","distinctId":"u1"}`); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer /v1/event want 503 (admitted, datastore down), got %d", code)
|
||||
}
|
||||
// A batch body is admitted the same way.
|
||||
if code, _ := doBody(t, app, http.MethodPost, "/v1/event", "user-dave", "acme", `[{"event":"a","distinctId":"d"},{"event":"b","distinctId":"d"}]`); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer /v1/event batch want 503, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvent_ResolvedKeyAdmitted(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
got := stubResolver(t, func(string) (string, bool) { return "acme", true })
|
||||
code := postKeyed(t, app, "/v1/event", "", `{"api_key":"hk-k","event":"e","distinctId":"d"}`, nil)
|
||||
if *got != "hk-k" {
|
||||
t.Fatalf("resolver handed key %q, want hk-k", *got)
|
||||
}
|
||||
if code == http.StatusForbidden {
|
||||
t.Fatalf("a resolved access key must pass the /v1/event gate, got 403")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvent_UnresolvableKeyFailsClosedEvenOnBrandHost(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
stubResolver(t, func(string) (string, bool) { return "", false })
|
||||
code := postKeyed(t, app, "/v1/event", "hanzo.ai", `{"api_key":"hk-bad","event":"e","distinctId":"d"}`, nil)
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("presented-but-unresolvable key on /v1/event must 403 (fail closed), got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvent_NoBrandHostFallback is THE distinguishing invariant: anonymous traffic
|
||||
// on a recognized brand host is ADMITTED by the deprecated /v1/analytics alias
|
||||
// (brand-public partition) but REFUSED by the canonical /v1/event — IAM is the
|
||||
// only tenant authority on the canonical door.
|
||||
func TestEvent_NoBrandHostFallback(t *testing.T) {
|
||||
app := mountApp(t)
|
||||
body := `{"event":"e","distinctId":"d"}`
|
||||
if code, _ := doHost(t, app, "/v1/event", "", "", "hanzo.ai", body); code != http.StatusForbidden {
|
||||
t.Fatalf("anonymous brand-host /v1/event must 403 (no brand fallback), got %d", code)
|
||||
}
|
||||
// Contrast: the deprecated alias still admits the same anonymous brand-host
|
||||
// traffic (503 = admitted, datastore down), proving the difference is by design.
|
||||
if code, _ := doHost(t, app, "/v1/analytics", "", "", "hanzo.ai", `{"batch":[{"type":"pageview"}]}`); code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("deprecated alias still brand-admits (want 503), got %d", code)
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,11 @@ import (
|
||||
)
|
||||
|
||||
// insightsEvent is the PostHog wire shape (subset that matters for ingest).
|
||||
// UUID is the top-level per-event id PostHog SDKs mint for idempotency; the rest
|
||||
// of the identity/attribution the SDKs carry rides inside Properties (mapped in
|
||||
// toCapture).
|
||||
type insightsEvent struct {
|
||||
UUID string `json:"uuid"`
|
||||
Event string `json:"event"`
|
||||
DistinctID string `json:"distinct_id"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
@@ -65,6 +69,11 @@ func (e insightsEvent) toCapture() CaptureEvent {
|
||||
typ = "pageview"
|
||||
}
|
||||
return CaptureEvent{
|
||||
// Idempotency id: PostHog SDKs carry a top-level event `uuid`; some send it
|
||||
// as an `$insert_id` property instead. Preserve it as the client MessageID so
|
||||
// a retried batch (insights-go retries with backoff) keeps a STABLE row id
|
||||
// rather than the server minting a fresh one per attempt.
|
||||
MessageID: firstNonEmptyStr(strings.TrimSpace(e.UUID), strings.TrimSpace(str("$insert_id"))),
|
||||
Type: typ,
|
||||
Event: e.Event,
|
||||
Timestamp: e.Timestamp,
|
||||
@@ -73,6 +82,19 @@ func (e insightsEvent) toCapture() CaptureEvent {
|
||||
URL: str("$current_url"),
|
||||
Path: str("$pathname"),
|
||||
Referrer: str("$referrer"),
|
||||
// UTM attribution: PostHog SDKs put campaign params in BARE `utm_*`
|
||||
// properties (not $-prefixed — confirmed against the SDK/ingest source).
|
||||
// hanzo.events has first-class utm_* columns and the native capture path
|
||||
// maps CaptureEvent.UTM into them (capture.go), so surfacing them here is
|
||||
// what lets the web/commerce lens attribute traffic to a campaign. They were
|
||||
// previously dropped on the PostHog-wire front door.
|
||||
UTM: UTM{
|
||||
Source: str("utm_source"),
|
||||
Medium: str("utm_medium"),
|
||||
Campaign: str("utm_campaign"),
|
||||
Term: str("utm_term"),
|
||||
Content: str("utm_content"),
|
||||
},
|
||||
Product: str("product"),
|
||||
Library: str("$lib"),
|
||||
LibraryVer: str("$lib_version"),
|
||||
@@ -80,9 +102,13 @@ func (e insightsEvent) toCapture() CaptureEvent {
|
||||
}
|
||||
}
|
||||
|
||||
// insightsIngest answers POST /v1/insights/e — the PostHog-compatible front
|
||||
// door. Same tenant gate, same normalize/scrub, same warehouse as /v1/analytics.
|
||||
// insightsIngest answers POST /v1/insights/e — the DEPRECATED PostHog-wire
|
||||
// adapter. It normalizes the PostHog single/batch shape onto CaptureEvent and
|
||||
// funnels through the ONE write core (ingestEvents, source=posthog); it keeps
|
||||
// captureTenant's brand-host path so anonymous PostHog-wire traffic is unbroken.
|
||||
// New callers post the canonical Event to /v1/event.
|
||||
func insightsIngest(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
deprecated(s, c, "/v1/event")
|
||||
org, ok := captureTenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer or a recognized brand host required")
|
||||
@@ -95,39 +121,15 @@ func insightsIngest(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
if len(events) == 0 && body.Event != "" {
|
||||
events = []insightsEvent{body.insightsEvent}
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return c.JSON(http.StatusOK, CaptureResult{})
|
||||
caps := make([]CaptureEvent, len(events))
|
||||
for i, e := range events {
|
||||
caps[i] = e.toCapture()
|
||||
}
|
||||
if len(events) > maxBatch {
|
||||
return zip.ErrBadRequest("batch too large")
|
||||
}
|
||||
if err := requireDatastore(); err != nil {
|
||||
res, err := ingestEvents(c.Context(), org, sourcePostHog, caps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx := c.Context()
|
||||
if err := EnsureEventsTable(ctx); err != nil {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "analytics warehouse unavailable: %v", err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
rows := make([]eventRow, 0, len(events))
|
||||
dropped := 0
|
||||
for _, e := range events {
|
||||
row, ok := normalizeEvent(org, now, e.toCapture())
|
||||
if !ok {
|
||||
dropped++
|
||||
continue
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return c.JSON(http.StatusOK, CaptureResult{Dropped: dropped})
|
||||
}
|
||||
stmt, args := buildEventsInsert(rows)
|
||||
if err := aiobject.DatastoreExec(ctx, stmt, args...); err != nil {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "analytics warehouse write failed: %v", err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, CaptureResult{Accepted: len(rows), Dropped: dropped})
|
||||
return c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// insightsEvents answers GET /v1/insights/events — the console's recent-events
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2023-2026 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.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestToCapture_PreservesUTMAttribution proves the PostHog-wire adapter carries the
|
||||
// BARE utm_* campaign params (what PostHog SDKs emit) through to the native
|
||||
// CaptureEvent — and thence, via normalizeEvent, into the hanzo.events utm_*
|
||||
// columns the INSERT binds. Regression guard: these were previously dropped, so
|
||||
// every campaign-attributed pageview lost its source/medium/campaign on the
|
||||
// /v1/insights/e front door and the web/commerce lens could never attribute it.
|
||||
func TestToCapture_PreservesUTMAttribution(t *testing.T) {
|
||||
e := insightsEvent{
|
||||
Event: "$pageview",
|
||||
DistinctID: "visitor-1",
|
||||
Properties: map[string]any{
|
||||
"utm_source": "newsletter",
|
||||
"utm_medium": "email",
|
||||
"utm_campaign": "launch",
|
||||
"utm_term": "analytics",
|
||||
"utm_content": "hero-cta",
|
||||
"$current_url": "https://hanzo.ai/insights",
|
||||
},
|
||||
}
|
||||
cap := e.toCapture()
|
||||
if cap.UTM.Source != "newsletter" || cap.UTM.Medium != "email" ||
|
||||
cap.UTM.Campaign != "launch" || cap.UTM.Term != "analytics" || cap.UTM.Content != "hero-cta" {
|
||||
t.Fatalf("UTM not mapped from PostHog wire: %+v", cap.UTM)
|
||||
}
|
||||
// End-to-end through the normalizer into the positional row the INSERT binds.
|
||||
row, ok := normalizeEvent("acme", time.Now(), cap)
|
||||
if !ok {
|
||||
t.Fatal("want ok")
|
||||
}
|
||||
if row.utmSource != "newsletter" || row.utmMedium != "email" ||
|
||||
row.utmCampaign != "launch" || row.utmTerm != "analytics" || row.utmContent != "hero-cta" {
|
||||
t.Fatalf("UTM lost before the events row: src=%q med=%q camp=%q term=%q content=%q",
|
||||
row.utmSource, row.utmMedium, row.utmCampaign, row.utmTerm, row.utmContent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToCapture_IdempotencyID proves the client event id (PostHog top-level `uuid`,
|
||||
// or the `$insert_id` property fallback) is preserved as the stable row id, so a
|
||||
// retried batch does not mint a fresh id per attempt — while an absent id still
|
||||
// falls back to a server-minted one (existing behavior unchanged).
|
||||
func TestToCapture_IdempotencyID(t *testing.T) {
|
||||
// top-level uuid wins
|
||||
row, _ := normalizeEvent("acme", time.Now(),
|
||||
insightsEvent{Event: "signup", DistinctID: "u1", UUID: "evt-abc"}.toCapture())
|
||||
if row.id != "evt-abc" {
|
||||
t.Fatalf("top-level uuid not preserved as row id, got %q", row.id)
|
||||
}
|
||||
// $insert_id property fallback when no top-level uuid
|
||||
row2, _ := normalizeEvent("acme", time.Now(),
|
||||
insightsEvent{Event: "signup", DistinctID: "u1", Properties: map[string]any{"$insert_id": "ins-9"}}.toCapture())
|
||||
if row2.id != "ins-9" {
|
||||
t.Fatalf("$insert_id fallback not preserved, got %q", row2.id)
|
||||
}
|
||||
// absent → server still mints a non-empty id
|
||||
row3, _ := normalizeEvent("acme", time.Now(),
|
||||
insightsEvent{Event: "signup", DistinctID: "u1"}.toCapture())
|
||||
if row3.id == "" {
|
||||
t.Fatal("server must still mint an id when the client sends none")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToCapture_MapsCoreFields guards that the pre-existing $-property mappings
|
||||
// still hold alongside the new UTM/idempotency mappings (no regression).
|
||||
func TestToCapture_MapsCoreFields(t *testing.T) {
|
||||
cap := insightsEvent{
|
||||
Event: "$pageview",
|
||||
DistinctID: "v1",
|
||||
Properties: map[string]any{
|
||||
"$session_id": "s1",
|
||||
"$current_url": "https://hanzo.ai/x",
|
||||
"$pathname": "/x",
|
||||
"$referrer": "https://news.ycombinator.com/",
|
||||
"$lib": "insights-go",
|
||||
"$lib_version": "1.2.3",
|
||||
"product": "console",
|
||||
},
|
||||
}.toCapture()
|
||||
if cap.Type != "pageview" || cap.SessionID != "s1" || cap.URL != "https://hanzo.ai/x" ||
|
||||
cap.Path != "/x" || cap.Referrer != "https://news.ycombinator.com/" ||
|
||||
cap.Library != "insights-go" || cap.LibraryVer != "1.2.3" || cap.Product != "console" {
|
||||
t.Fatalf("core PostHog-wire mapping regressed: %+v", cap)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// Copyright 2023-2026 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.
|
||||
|
||||
// publishable.go — the FASTEST capture path: a write-only PUBLISHABLE KEY (pk_…)
|
||||
// that authenticates a direct-to-datastore ingest with ZERO network hop.
|
||||
//
|
||||
// POST /v1/ingest body: {batch:[WireEvent]} auth: pk_… -> {accepted,dropped}
|
||||
// POST /v1/ingest/keys mint a pk_ for the caller's org (validated principal)
|
||||
// GET /v1/errors recent type:'error' events for the org (read lens)
|
||||
//
|
||||
// WHY a distinct key from the IAM hk-/sk-/pk- family: those resolve through IAM
|
||||
// (get-user?accessKey — a network round-trip) and mint a FULL principal that can
|
||||
// READ. A publishable key is meant to ship in a browser bundle, so it must be
|
||||
// write-only and cheap to verify. This key is:
|
||||
//
|
||||
// - INGEST-ONLY BY CONSTRUCTION. The `pk_` (underscore) prefix is deliberately
|
||||
// NOT in isAPIKey's set (hk-/sk-/pk-/fw_/hz_, all dash/`fw_`/`hz_`), so the
|
||||
// identity boundary (SanitizeIdentity) and OrgForKey both REFUSE it — it can
|
||||
// never become a bearer principal, so it can never read. Its only door is the
|
||||
// ingest verifier below. Write-only is a property of WHICH resolver accepts
|
||||
// the value, not a flag on a row.
|
||||
// - ORG-SCOPED, SIGNED, NON-FORGEABLE. The org is carried in the key but sealed
|
||||
// under HMAC-SHA256(secret, org): a client cannot flip the org without the
|
||||
// secret. The server stamps tenant_id from the VERIFIED org, never from the
|
||||
// request body — the same tenant invariant the rest of the plane enforces.
|
||||
// - LOWEST LATENCY. Verification is one HMAC compute — no IAM call, no keys
|
||||
// table, no DB read. This is the no-Kafka, no-bridge, direct-to-ClickHouse
|
||||
// path; it funnels through the SAME write core (ingestEvents) into the SAME
|
||||
// hanzo.events table as every other adapter. One write path, many front doors.
|
||||
//
|
||||
// SECRET: the HMAC secret is CLOUD_INGEST_KEY_SECRET (KMS-injected by the
|
||||
// operator). Absent ⇒ mint and verify BOTH fail closed (503 / 403) — a deployment
|
||||
// without the secret never mints a forgeable key nor admits an unverifiable one.
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
aiobject "github.com/hanzoai/ai/object"
|
||||
"github.com/hanzoai/cloud"
|
||||
"github.com/zap-proto/zip"
|
||||
)
|
||||
|
||||
// ingestKeySecretEnv names the KMS-injected HMAC secret that seals a publishable
|
||||
// key's org. Absent ⇒ the publishable-key path is disabled (fails closed).
|
||||
const ingestKeySecretEnv = "CLOUD_INGEST_KEY_SECRET"
|
||||
|
||||
// publishablePrefix marks a write-only ingest key. Underscore (not the dash of
|
||||
// the isAPIKey family) is load-bearing: it keeps pk_ OUT of the bearer/principal
|
||||
// path, so a publishable key is structurally read-incapable.
|
||||
const publishablePrefix = "pk_"
|
||||
|
||||
// sourceIngest tags rows that arrived via the publishable-key direct ingest, so
|
||||
// the ONE hanzo.events table stays honest about origin (queryable as
|
||||
// properties.$source) without a second table — same mechanism as the other
|
||||
// adapters (sourceEvent/sourcePostHog/sourceCapture).
|
||||
const sourceIngest = "ingest"
|
||||
|
||||
// sigBytes is the HMAC truncation length (128 bits) — ample against forgery while
|
||||
// keeping the key short enough to embed in a bundle.
|
||||
const sigBytes = 16
|
||||
|
||||
// ── key codec (pure) ─────────────────────────────────────────────────────────
|
||||
|
||||
// ingestSecret returns the configured HMAC secret, or "" when unset (path off).
|
||||
func ingestSecret() string { return strings.TrimSpace(os.Getenv(ingestKeySecretEnv)) }
|
||||
|
||||
// keySig computes the org signature under the secret: HMAC-SHA256(secret, org),
|
||||
// truncated to sigBytes. The org is the only signed input — the tenant a key can
|
||||
// ever write into is fixed at mint time and cannot be shifted without the secret.
|
||||
func keySig(secret, org string) []byte {
|
||||
m := hmac.New(sha256.New, []byte(secret))
|
||||
m.Write([]byte(org))
|
||||
return m.Sum(nil)[:sigBytes]
|
||||
}
|
||||
|
||||
// mintPublishableKey mints "pk_<b64url(org)>.<b64url(sig)>" for org under secret.
|
||||
// '.' is the delimiter because it is OUTSIDE the base64url alphabet (which uses
|
||||
// '-' and '_'), so the two segments split unambiguously. Returns ("",false) when
|
||||
// the secret is unconfigured (fail closed) or org is empty.
|
||||
func mintPublishableKey(secret, org string) (string, bool) {
|
||||
org = strings.TrimSpace(org)
|
||||
if secret == "" || org == "" {
|
||||
return "", false
|
||||
}
|
||||
b64 := base64.RawURLEncoding
|
||||
return publishablePrefix + b64.EncodeToString([]byte(org)) + "." + b64.EncodeToString(keySig(secret, org)), true
|
||||
}
|
||||
|
||||
// verifyPublishableKey resolves a presented key to its org, or ("",false) if the
|
||||
// key is not a well-formed, correctly-signed publishable key under the configured
|
||||
// secret. FAILS CLOSED: unconfigured secret, wrong prefix, malformed segments, or
|
||||
// a signature mismatch all return not-ok. Constant-time signature compare. Pure:
|
||||
// no I/O, so tests drive it directly.
|
||||
func verifyPublishableKey(secret, key string) (string, bool) {
|
||||
key = strings.TrimSpace(key)
|
||||
if secret == "" || !strings.HasPrefix(key, publishablePrefix) {
|
||||
return "", false
|
||||
}
|
||||
body := key[len(publishablePrefix):]
|
||||
dot := strings.IndexByte(body, '.')
|
||||
if dot <= 0 || dot == len(body)-1 {
|
||||
return "", false
|
||||
}
|
||||
b64 := base64.RawURLEncoding
|
||||
orgBytes, err := b64.DecodeString(body[:dot])
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
sig, err := b64.DecodeString(body[dot+1:])
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
org := string(orgBytes)
|
||||
if org == "" || len(org) > maxIngestOrgLen {
|
||||
return "", false
|
||||
}
|
||||
if subtle.ConstantTimeCompare(sig, keySig(secret, org)) != 1 {
|
||||
return "", false
|
||||
}
|
||||
return org, true
|
||||
}
|
||||
|
||||
// maxIngestOrgLen bounds a decoded org (it becomes a warehouse partition key),
|
||||
// mirroring the cap OrgForKey applies to an IAM-resolved owner.
|
||||
const maxIngestOrgLen = 128
|
||||
|
||||
// ── request key extraction ───────────────────────────────────────────────────
|
||||
|
||||
// ingestKey pulls the presented publishable key, in priority order: the
|
||||
// Authorization: Bearer header (the common browser-fetch shape), the
|
||||
// x-hanzo-ingest-key header, then the ?ingest_key= query (navigator.sendBeacon
|
||||
// cannot set headers). Only a pk_-prefixed value is returned — an unrelated
|
||||
// bearer (a real JWT/IAM key) is ignored here so this door never shadows the
|
||||
// identity path. "" when none is present.
|
||||
func ingestKey(c *zip.Ctx) string {
|
||||
if auth := strings.TrimSpace(c.Header("authorization")); auth != "" {
|
||||
parts := strings.SplitN(auth, " ", 2)
|
||||
if len(parts) == 2 && strings.EqualFold(parts[0], "Bearer") {
|
||||
if k := strings.TrimSpace(parts[1]); strings.HasPrefix(k, publishablePrefix) {
|
||||
return k
|
||||
}
|
||||
}
|
||||
}
|
||||
if k := strings.TrimSpace(c.Header("x-hanzo-ingest-key")); strings.HasPrefix(k, publishablePrefix) {
|
||||
return k
|
||||
}
|
||||
if k := strings.TrimSpace(c.Query("ingest_key")); strings.HasPrefix(k, publishablePrefix) {
|
||||
return k
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ── error (exception) folding ────────────────────────────────────────────────
|
||||
|
||||
// Exception is the captured error carried on a type:'error' WireEvent (mirrors
|
||||
// @hanzo/event's Exception). The ingest folds it into properties.$exception so
|
||||
// the ONE events schema needs no new columns and the /v1/errors lens can surface
|
||||
// it straight from the properties JSON.
|
||||
type Exception struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Stack string `json:"stack,omitempty"`
|
||||
Handled *bool `json:"handled,omitempty"`
|
||||
}
|
||||
|
||||
// foldException normalizes a type:'error' event so the write core stores it as a
|
||||
// first-class error: it defaults the type to "error", and lifts the top-level
|
||||
// `error` object into properties.$exception (never mutating the caller's map).
|
||||
// A non-error event passes through unchanged.
|
||||
func foldException(e CaptureEvent) CaptureEvent {
|
||||
if e.Error == nil {
|
||||
return e
|
||||
}
|
||||
if strings.TrimSpace(e.Type) == "" {
|
||||
e.Type = "error"
|
||||
}
|
||||
props := make(map[string]any, len(e.Properties)+1)
|
||||
for k, v := range e.Properties {
|
||||
props[k] = v
|
||||
}
|
||||
props["$exception"] = e.Error
|
||||
e.Properties = props
|
||||
e.Error = nil
|
||||
return e
|
||||
}
|
||||
|
||||
// ── handlers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// ingest answers POST /v1/ingest — the publishable-key direct capture path. The
|
||||
// org is resolved from the SIGNED key (no IAM, no DB), the body is the
|
||||
// @hanzo/event WireEvent batch ({batch:[…]} | {events:[…]}), error events are
|
||||
// folded, and everything funnels through the ONE write core into hanzo.events.
|
||||
// FAILS CLOSED: a missing/unverifiable key is refused (403); the org is never
|
||||
// read from the body.
|
||||
func ingest(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
key := ingestKey(c)
|
||||
if key == "" {
|
||||
return zip.ErrForbidden("publishable ingest key required")
|
||||
}
|
||||
org, ok := verifyPublishableKey(ingestSecret(), key)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("invalid publishable ingest key")
|
||||
}
|
||||
var batch CaptureBatch
|
||||
if err := c.Bind(&batch); err != nil {
|
||||
return zip.ErrBadRequest("malformed ingest batch")
|
||||
}
|
||||
evs := batch.events()
|
||||
for i := range evs {
|
||||
evs[i] = foldException(evs[i])
|
||||
}
|
||||
res, err := ingestEvents(c.Context(), org, sourceIngest, evs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// mintKey answers POST /v1/ingest/keys — an org owner (VALIDATED principal) mints
|
||||
// a publishable key for its OWN org. The key is org-scoped to the caller's tenant
|
||||
// (never a body-supplied org), so a caller can only ever mint a key that writes
|
||||
// into its own partition. Fails closed (503) when the secret is unconfigured.
|
||||
func mintKey(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer required")
|
||||
}
|
||||
secret := ingestSecret()
|
||||
if secret == "" {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "publishable keys unavailable: ingest key secret not configured")
|
||||
}
|
||||
key, ok := mintPublishableKey(secret, org)
|
||||
if !ok {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "could not mint publishable key")
|
||||
}
|
||||
return c.JSON(http.StatusOK, map[string]any{"key": key, "org": org, "scope": "ingest"})
|
||||
}
|
||||
|
||||
// errorsLens answers GET /v1/errors — the error-tracking read view: recent
|
||||
// type:'error' events for the org, newest first. Tenant-scoped server-side and
|
||||
// gated on a VALIDATED principal (tenant()), NOT the publishable key — reads
|
||||
// require real auth, reinforcing that pk_ is write-only. The captured exception
|
||||
// is surfaced straight from properties.$exception. limit defaults 50, caps 200.
|
||||
func errorsLens(s *cloud.Service[state], c *zip.Ctx) error {
|
||||
org, ok := tenant(c)
|
||||
if !ok {
|
||||
return zip.ErrForbidden("valid bearer required")
|
||||
}
|
||||
limit, _ := strconv.Atoi(strings.TrimSpace(c.Query("limit")))
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := aiobject.DatastoreQuery(c.Context(), `
|
||||
SELECT id, timestamp, event, distinct_id, session_id, product, url, path,
|
||||
library, library_version, properties
|
||||
FROM hanzo.events
|
||||
WHERE tenant_id = ? AND event_type = 'error'
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT ?`, org, limit)
|
||||
if err != nil {
|
||||
return zip.Errorf(http.StatusServiceUnavailable, "analytics warehouse unavailable: %v", err)
|
||||
}
|
||||
type errEvent struct {
|
||||
ID string `json:"id"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Event string `json:"event"`
|
||||
DistinctID string `json:"distinctId,omitempty"`
|
||||
SessionID string `json:"sessionId,omitempty"`
|
||||
Product string `json:"product,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Library string `json:"library,omitempty"`
|
||||
LibraryVer string `json:"libraryVersion,omitempty"`
|
||||
Exception json.RawMessage `json:"exception,omitempty"`
|
||||
Properties json.RawMessage `json:"properties,omitempty"`
|
||||
}
|
||||
out := make([]errEvent, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
e := errEvent{
|
||||
ID: asStr(r["id"]), Timestamp: asStr(r["timestamp"]), Event: asStr(r["event"]),
|
||||
DistinctID: asStr(r["distinct_id"]), SessionID: asStr(r["session_id"]),
|
||||
Product: asStr(r["product"]), URL: asStr(r["url"]), Path: asStr(r["path"]),
|
||||
Library: asStr(r["library"]), LibraryVer: asStr(r["library_version"]),
|
||||
}
|
||||
if p := asStr(r["properties"]); p != "" && json.Valid([]byte(p)) {
|
||||
e.Properties = json.RawMessage(p)
|
||||
e.Exception = extractException(p)
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return c.JSON(http.StatusOK, map[string]any{"data": out})
|
||||
}
|
||||
|
||||
// extractException pulls the $exception object out of a properties JSON blob so
|
||||
// the errors lens surfaces it as a first-class field. "" (nil) when absent.
|
||||
func extractException(props string) json.RawMessage {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(props), &m) != nil {
|
||||
return nil
|
||||
}
|
||||
if ex, ok := m["$exception"]; ok {
|
||||
return ex
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Copyright 2023-2026 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.
|
||||
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testSecret = "test-ingest-secret-0123456789"
|
||||
|
||||
// mint→verify is a round trip: a key minted for an org verifies back to exactly
|
||||
// that org under the same secret.
|
||||
func TestPublishableKeyRoundTrip(t *testing.T) {
|
||||
for _, org := range []string{"acme", "hanzo", "maxpower", "org-with-dashes", "MixedCase"} {
|
||||
key, ok := mintPublishableKey(testSecret, org)
|
||||
if !ok {
|
||||
t.Fatalf("mint failed for %q", org)
|
||||
}
|
||||
got, ok := verifyPublishableKey(testSecret, key)
|
||||
if !ok {
|
||||
t.Fatalf("verify failed for freshly minted key %q", key)
|
||||
}
|
||||
if got != org {
|
||||
t.Fatalf("round trip org = %q, want %q", got, org)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The key is write-only by construction: pk_ is NOT accepted by the isAPIKey
|
||||
// family, so it can never be minted into a bearer principal. (Guards the prefix
|
||||
// choice — an accidental switch to a dash prefix would silently make the key
|
||||
// readable.) We assert the prefix here; isAPIKey lives in the parent package.
|
||||
func TestPublishablePrefixIsUnderscore(t *testing.T) {
|
||||
key, _ := mintPublishableKey(testSecret, "acme")
|
||||
if key[:3] != "pk_" {
|
||||
t.Fatalf("publishable key must start with pk_ (write-only lane), got %q", key[:3])
|
||||
}
|
||||
}
|
||||
|
||||
// verify FAILS CLOSED on every malformed / forged / unconfigured case.
|
||||
func TestVerifyFailsClosed(t *testing.T) {
|
||||
good, _ := mintPublishableKey(testSecret, "acme")
|
||||
cases := []struct {
|
||||
name, secret, key string
|
||||
}{
|
||||
{"no secret", "", good},
|
||||
{"wrong prefix", testSecret, "sk-abcdef"},
|
||||
{"empty", testSecret, ""},
|
||||
{"no delimiter", testSecret, "pk_YWNtZQ"},
|
||||
{"trailing delimiter", testSecret, "pk_YWNtZQ."},
|
||||
{"leading delimiter", testSecret, "pk_.YWNtZQ"},
|
||||
{"bad base64 org", testSecret, "pk_!!!.YWNtZQ"},
|
||||
{"bad base64 sig", testSecret, "pk_YWNtZQ.!!!"},
|
||||
{"wrong secret", "other-secret", good},
|
||||
{"tampered org keeps old sig", testSecret, forgeOrg(good, "evil")},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if org, ok := verifyPublishableKey(tc.secret, tc.key); ok {
|
||||
t.Errorf("%s: verify admitted a bad key → org %q (want fail closed)", tc.name, org)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// forgeOrg swaps the org segment of a real key while keeping its signature — the
|
||||
// canonical forgery attempt the HMAC must reject.
|
||||
func forgeOrg(key, newOrg string) string {
|
||||
// pk_<b64org>.<b64sig> — replace the b64org segment.
|
||||
dot := -1
|
||||
for i := 3; i < len(key); i++ {
|
||||
if key[i] == '.' {
|
||||
dot = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if dot < 0 {
|
||||
return key
|
||||
}
|
||||
enc := base64Raw(newOrg)
|
||||
return "pk_" + enc + key[dot:]
|
||||
}
|
||||
|
||||
func base64Raw(s string) string {
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
src := []byte(s)
|
||||
var out []byte
|
||||
for i := 0; i < len(src); i += 3 {
|
||||
var b [3]byte
|
||||
n := copy(b[:], src[i:])
|
||||
out = append(out, alphabet[b[0]>>2])
|
||||
out = append(out, alphabet[(b[0]&0x03)<<4|b[1]>>4])
|
||||
if n > 1 {
|
||||
out = append(out, alphabet[(b[1]&0x0f)<<2|b[2]>>6])
|
||||
}
|
||||
if n > 2 {
|
||||
out = append(out, alphabet[b[2]&0x3f])
|
||||
}
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// foldException lifts a type:'error' event's exception into properties.$exception
|
||||
// and defaults the type, so the write core stores it as event_type='error'.
|
||||
func TestFoldException(t *testing.T) {
|
||||
handled := false
|
||||
e := CaptureEvent{
|
||||
Error: &Exception{Type: "TypeError", Message: "x is not a function", Stack: "at f()", Handled: &handled},
|
||||
}
|
||||
got := foldException(e)
|
||||
if got.Type != "error" {
|
||||
t.Fatalf("type = %q, want error", got.Type)
|
||||
}
|
||||
if got.Error != nil {
|
||||
t.Fatalf("error object must be lifted out (nil after fold), got %+v", got.Error)
|
||||
}
|
||||
ex, ok := got.Properties["$exception"]
|
||||
if !ok {
|
||||
t.Fatal("properties.$exception missing after fold")
|
||||
}
|
||||
b, _ := json.Marshal(ex)
|
||||
var back Exception
|
||||
if json.Unmarshal(b, &back) != nil || back.Message != "x is not a function" {
|
||||
t.Fatalf("lifted exception malformed: %s", b)
|
||||
}
|
||||
|
||||
// normalizeEvent must then store event_type='error'.
|
||||
row, ok := normalizeEvent("acme", time.Now().UTC(), got)
|
||||
if !ok {
|
||||
t.Fatal("normalize dropped a folded error event")
|
||||
}
|
||||
if row.eventType != "error" || row.event != "$error" {
|
||||
t.Fatalf("stored type/event = %q/%q, want error/$error", row.eventType, row.event)
|
||||
}
|
||||
|
||||
// A non-error event is untouched.
|
||||
plain := CaptureEvent{Event: "click"}
|
||||
if foldException(plain).Type != "" {
|
||||
t.Fatal("non-error event was mutated by foldException")
|
||||
}
|
||||
}
|
||||
|
||||
// canonicalType now recognizes error as first-class (still folds unknowns).
|
||||
func TestCanonicalTypeError(t *testing.T) {
|
||||
if canonicalType("error") != "error" {
|
||||
t.Fatal("error must canonicalize to error")
|
||||
}
|
||||
if canonicalType("ERROR") != "error" {
|
||||
t.Fatal("error canonicalization must be case-insensitive")
|
||||
}
|
||||
if canonicalType("weird") != "event" {
|
||||
t.Fatal("unknown type must still fold to event")
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user