hosted controller: signed HTTPS API, command and metrics
hostedctl gains the controller's HTTP API: strict JSON read once under MaxBody, verified and decoded from the same bytes, routes checked by role (operator for /v1/vms, instance for job routes, with the creator check in the controller), one status table with fixed messages, and every verified response signed. Metrics are Prometheus text on their own listener. cmd/equipo-hosted-controller loads a strict config (no wildcard listens, checked keys), wires awsjob and an SNS alerter, and takes Enabled only from EQUIPO_HOSTED_ENABLED=1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+1,998
−0
cmd/equipo-hosted-controller/alerter.go+27 −0cmd/equipo-hosted-controller/alerter_test.go+63 −0cmd/equipo-hosted-controller/config.go+254 −0cmd/equipo-hosted-controller/config_test.go+189 −0cmd/equipo-hosted-controller/main.go+144 −0docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md+31 −0internal/hostedctl/http.go+521 −0internal/hostedctl/http_test.go+539 −0internal/hostedctl/metrics.go+230 −0
CI cancelled — superseded by a newer push — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-1a: Type Size Avail | ext4 96G 85G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 85G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 1.7s
ci-box: codex: fetched and verified in 3.5s
ci-box: codex-code-mode-host: fetched and verified in 1.3s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 10.0s
ci-box: pi: installed and verified in 7.6s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.8s
ci-box: clone deepened in 3.5s
ci-box: file times set from content: 2893 files, 193 directories
ci-box: ready in 17.3s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
ok amadan.net/oficina/equipo/internal/equipotest 0.245s
=== compile ===
go build ./...
go: downloading github.com/aws/aws-sdk-go-v2/config v1.33.21
go: downloading github.com/aws/aws-sdk-go-v2/credentials v1.21.3
go: downloading github.com/aws/aws-sdk-go-v2/service/signin v1.14.0
go: downloading github.com/aws/aws-sdk-go-v2/service/sso v1.39.5
go: downloading github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5
go: downloading github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9
go: downloading github.com/aws/aws-sdk-go-v2/service/sts v1.53.0
go: downloading github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
1.2s
+ go list -export -test -tags testbuild -f ./...
1.3s
+ go list -export -test -tags browser,testbuild -f ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
0.3s
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -version
staticcheck 2026.1 (v0.7.0)
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 -version
Go: go1.26.11
Scanner: govulncheck@v1.8.0
DB: https://vuln.go.dev
DB updated: 2026-11-11 02:51:11 +0000 UTC
go run github.com/zricethezav/gitleaks/v8@v8.30.1 version
version is set by build process
=== check ===
--- shard 0 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-work: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m21.738s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m20.106s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m20.11s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 37.94, cpu waiting 22.13%, memory waiting 0.00%, io waiting 0.51%
--- shard 1 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-review: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m24.002s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m22.317s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m22.32s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 36.58, cpu waiting 21.22%, memory waiting 0.00%, io waiting 0.48%
--- shard 2 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-connections: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m25.694s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m23.548s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m12.93s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.81s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.8s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 36.58, cpu waiting 20.62%, memory waiting 0.00%, io waiting 0.46%
--- shard 3 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-mac: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m20.308s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m18.664s amadan.net/oficina/equipo/internal/headless
receipt: slow test 37.97s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 20.41s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 10.61s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
receipt: slow test 9.67s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
machine: 32 CPUs, load 37.94, cpu waiting 22.13%, memory waiting 0.00%, io waiting 0.51%
--- shard 4 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-guards: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m38.124s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m36.352s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m0.18s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.29s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 9.99s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 9.02s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 5.86s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 35.79, cpu waiting 17.21%, memory waiting 0.00%, io waiting 0.37%
--- shard 5 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-rest: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$|^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$|^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$|^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$|^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 3m20.95s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3m18.872s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m46.53s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 24.48s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 20.71s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 8.2s amadan.net/oficina/equipo/internal/headless TestHeadlessClaudeSignIn
receipt: slow test 7.4s amadan.net/oficina/equipo/internal/headless TestHeadlessBatchAfterRefusedReply
machine: 32 CPUs, load 8.60, cpu waiting 3.27%, memory waiting 0.00%, io waiting 0.06%
--- shard 6 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
receipt: test step 1.024s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 2m1.624s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 7.84s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.74s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 4.31s amadan.net/oficina/equipo/internal/thintest TestContractTeamUpdatePersonNeeds
receipt: slow test 3.81s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.52s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
machine: 32 CPUs, load 2.49, cpu waiting 0.62%, memory waiting 0.00%, io waiting 1.96%
--- shard 7 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest-contract: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
receipt: test step 1.094s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m26.784s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.08s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 5.03s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.41s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.4s amadan.net/oficina/equipo/internal/thintest TestContractPreview
receipt: slow test 2.34s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
machine: 32 CPUs, load 2.49, cpu waiting 0.62%, memory waiting 0.00%, io waiting 1.96%
--- shard 8 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-thin: ./internal/runner/thin
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/runner/thin
cache miss: amadan.net/oficina/equipo/internal/runner/thin: its inputs changed
amadan: job cancelled — a newer push superseded it
--- shard 9 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-bug: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed
receipt: test step 47.202s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 46.135s amadan.net/oficina/equipo/internal/runner
receipt: slow test 26.1s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.02s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 38.46, cpu waiting 22.09%, memory waiting 0.00%, io waiting 0.91%
--- shard 10 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-plans: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed
receipt: test step 48.612s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 46.681s amadan.net/oficina/equipo/internal/runner
receipt: slow test 36.66s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 32.95s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.39s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.62s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 38.46, cpu waiting 22.45%, memory waiting 0.00%, io waiting 0.88%
--- shard 11 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-rest: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$|^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed
receipt: test step 35.197s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 34.258s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.11s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.42s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.11s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.31s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 30.85, cpu waiting 15.13%, memory waiting 0.00%, io waiting 1.11%
--- shard 12 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-a started 30s late; cpu waiting 27.0%, load 23.96
test lane equipotest-a: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[A-D]|^TestQ' ./internal/equipotest
cache miss: amadan.net/oficina/equipo/internal/equipotest: its inputs changed
receipt: test step 1m5.439s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m3.454s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 27.27s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 27.17s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 25.21s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 22.58s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 22.46s amadan.net/oficina/equipo/internal/equipotest TestAuthoritySnapshotChanges
machine: 32 CPUs, load 35.79, cpu waiting 18.36%, memory waiting 0.00%, io waiting 0.40%
--- shard 13 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-e started 30s late; cpu waiting 29.4%, load 23.96
test lane equipotest-e: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[E-P]' ./internal/equipotest
receipt: test step 1.324s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m12.399s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.2s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 19.12s amadan.net/oficina/equipo/internal/equipotest TestProjectOwnersAreMembers
receipt: slow test 19.11s amadan.net/oficina/equipo/internal/equipotest TestProjectsReopen
receipt: slow test 19.11s amadan.net/oficina/equipo/internal/equipotest TestProjectRetryAndRevision
receipt: slow test 19.08s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
machine: 32 CPUs, load 23.96, cpu waiting 12.01%, memory waiting 0.00%, io waiting 1.19%
--- shard 14 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-r started 30s late; cpu waiting 27.0%, load 23.96
test lane equipotest-r: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestR' ./internal/equipotest
cache miss: amadan.net/oficina/equipo/internal/equipotest: its inputs changed
receipt: test step 1m15.401s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m3.392s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 14.2s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 12.72s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 9.64s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 9.63s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 6.59s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 30.74, cpu waiting 15.60%, memory waiting 0.00%, io waiting 0.34%
--- shard 15 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-rest started 30s late; cpu waiting 27.0%, load 23.96
test lane equipotest-rest: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test[A-D]|^TestQ|^Test[E-P]|^TestR' ./internal/equipotest
receipt: test step 394ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m4.231s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 24.45s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 23.28s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 23.2s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 21.61s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
receipt: slow test 21.57s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsRollbackAndUnavailable
machine: 32 CPUs, load 23.96, cpu waiting 11.06%, memory waiting 0.00%, io waiting 1.23%
--- shard 16 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: plan3test started 30s late; cpu waiting 27.0%, load 23.96
test lane plan3test: ./internal/plan3test
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/plan3test
receipt: test step 667ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 48.756s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.61s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.41s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.5s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.47s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.21s amadan.net/oficina/equipo/internal/plan3test TestPlanMigrationUpgrade
machine: 32 CPUs, load 23.96, cpu waiting 12.01%, memory waiting 0.00%, io waiting 1.19%
--- shard 17 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: rest started 30s late; cpu waiting 27.0%, load 23.96
test lane rest: ./cmd/equipo ./cmd/equipo-hosted-controller ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/hostedctl ./internal/hostedwire ./internal/idtest ./internal/isolatedjob ./internal/isolatedjob/awsjob ./internal/isolatedjob/guardfixture ./internal/isolatedjob/isolatedjobtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./cmd/equipo ./cmd/equipo-hosted-controller ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/hostedctl ./internal/hostedwire ./internal/idtest ./internal/isolatedjob ./internal/isolatedjob/awsjob ./internal/isolatedjob/guardfixture ./internal/isolatedjob/isolatedjobtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
cache miss: amadan.net/oficina/equipo/internal/copydesk: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/isolatedjob: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/opencode: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/equipo/team: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/forge: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/claude: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/workspace: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/codex: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/checks: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/containment: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
budget note: internal/equipo took 45.275s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/equipo/chat took 12.529s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/hostedctl took 13.654s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 39.84s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/release took 34.981s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/runner/containment took 39.843s, over the 15s its record on line 40 allows; reported only, timing fails on CI
receipt: test step 2m16.43s against a 60s target (the gate's other steps are not in this figure)
receipt: 14 packages ran, 52 cached, 20 without tests, 0 failed
receipt: slow package 53.139s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 52.394s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 45.275s amadan.net/oficina/equipo/internal/equipo
receipt: slow package 39.843s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow package 39.84s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 21.43s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeAcceptanceHostileRepository
receipt: slow test 15.12s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringOfflineGo
receipt: slow test 12.36s amadan.net/oficina/equipo/internal/hostedctl TestLifecycleSimulation
receipt: slow test 10.89s amadan.net/oficina/equipo/internal/idtest TestIDCallbackGuardAndPendingNonce
receipt: slow test 10.82s amadan.net/oficina/equipo/internal/equipo TestAgentReadRechecksIdentity
machine: 32 CPUs, load 14.39, cpu waiting 5.58%, memory waiting 0.00%, io waiting 0.11%
--- shard 18 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-chat: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m23.309s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m21.65s amadan.net/oficina/equipo/internal/headless
receipt: slow test 37.63s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 15.15s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.65s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.79s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 5.99s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 37.94, cpu waiting 21.73%, memory waiting 0.00%, io waiting 0.49%
--- shard 19 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-work: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m33.647s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m31.824s amadan.net/oficina/equipo/internal/headless
receipt: slow test 26.71s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 22.72s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 14.21s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 10.35s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
receipt: slow test 7.97s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
machine: 32 CPUs, load 35.79, cpu waiting 18.91%, memory waiting 0.00%, io waiting 0.41%
--- shard 20 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-connections: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed
receipt: test step 1m41.129s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m39.405s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.35s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.45s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 12.96s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 10.23s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 10.16s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 33.16, cpu waiting 16.65%, memory waiting 0.00%, io waiting 0.36%
--- shard 21 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-rest: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserCopyContinue
=== RUN TestBrowserCopyContinue
time=2026-11-22T19:46:32.814Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-22T19:46:32.815Z level=INFO msg="startup phase done" phase=state_lock took=265µs
time=2026-11-22T19:46:32.815Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-22T19:46:32.815Z level=INFO msg="startup phase done" phase=claim_roots took=81µs
time=2026-11-22T19:46:32.815Z level=INFO msg="startup phase" phase=sweep
time=2026-11-22T19:46:32.862Z level=INFO msg="startup phase done" phase=sweep took=47.302ms
time=2026-11-22T19:46:32.862Z level=INFO msg="startup phase" phase=credentials
time=2026-11-22T19:46:32.862Z level=INFO msg="startup phase done" phase=credentials took=210µs
time=2026-11-22T19:46:32.862Z level=INFO msg="startup phase" phase=open_state
time=2026-11-22T19:46:32.917Z level=INFO msg="startup phase done" phase=open_state took=54.57ms
time=2026-11-22T19:46:32.918Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-22T19:46:32.919Z level=INFO msg=connecting host=127.0.0.1:37311 protocol=28
time=2026-11-22T19:46:32.920Z level=INFO msg=connected host=127.0.0.1:37311 took=1.043ms
time=2026-11-22T19:46:32.920Z level=INFO msg="capabilities gathering"
time=2026-11-22T19:46:32.922Z level=INFO msg="capabilities gathered" took=1.33ms tags=linux,claude,go
time=2026-11-22T19:46:32.922Z level=INFO msg="hello sent" protocol=28
time=2026-11-22T19:46:32.927Z level=INFO msg=welcome protocol=28 role=primary generation=1
browser_copy_test.go:93: continue did not reach Checks: 0 <nil>
--- FAIL: TestBrowserCopyContinue (1.85s)
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
=== RUN TestBrowserEmptyExplore
time=2026-11-22T19:47:04.191Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-22T19:47:04.191Z level=INFO msg="startup phase done" phase=state_lock took=60µs
time=2026-11-22T19:47:04.191Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-22T19:47:04.191Z level=INFO msg="startup phase done" phase=claim_roots took=82µs
time=2026-11-22T19:47:04.191Z level=INFO msg="startup phase" phase=sweep
time=2026-11-22T19:47:04.223Z level=INFO msg="startup phase done" phase=sweep took=31.574ms
time=2026-11-22T19:47:04.223Z level=INFO msg="startup phase" phase=credentials
time=2026-11-22T19:47:04.223Z level=INFO msg="startup phase done" phase=credentials took=107µs
time=2026-11-22T19:47:04.223Z level=INFO msg="startup phase" phase=open_state
time=2026-11-22T19:47:04.265Z level=INFO msg="startup phase done" phase=open_state took=42.27ms
time=2026-11-22T19:47:04.266Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-22T19:47:04.267Z level=INFO msg=connecting host=127.0.0.1:44359 protocol=28
time=2026-11-22T19:47:04.268Z level=INFO msg=connected host=127.0.0.1:44359 took=955µs
time=2026-11-22T19:47:04.268Z level=INFO msg="capabilities gathering"
time=2026-11-22T19:47:04.269Z level=INFO msg="capabilities gathered" took=769µs tags=linux,claude,go
time=2026-11-22T19:47:04.270Z level=INFO msg="hello sent" protocol=28
time=2026-11-22T19:47:04.275Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-22T19:47:05.351Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_receipts_test.go:169: waiting for [...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserEmptyExplore (5.86s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m27.426s
FAIL amadan.net/oficina/equipo/internal/headless 87.713s
receipt: test step 1m28.833s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m27.426s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.23s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 11.35s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 10.46s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 10.42s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 8.02s amadan.net/oficina/equipo/internal/headless TestBrowserRefreshRace
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' -v -run '^TestBrowserCopyContinue$|^TestBrowserEmptyExplore$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserCopyContinue browser-headless-rest 97c6b929ecc30d280807ab6471eea59927ae7c01 1.85s 36.38
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserEmptyExplore browser-headless-rest 97c6b929ecc30d280807ab6471eea59927ae7c01 5.86s 36.38
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 33.16, cpu waiting 16.65%, memory waiting 0.00%, io waiting 0.36%
--- shard 22 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-rest: ./internal/equipo
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserPreviewBlocksNavigation)$' ./internal/equipo
receipt: test step 978ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 573ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 570ms amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewBlocksNavigation
browser lane browser-rest: ./internal/idtest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserOficinaIDDoor)$' ./internal/idtest
receipt: test step 812ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1.673s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 1.67s amadan.net/oficina/equipo/internal/idtest TestBrowserOficinaIDDoor
browser lane browser-rest: ./internal/plan3test
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestTeamsHierarchyBrowser)$' ./internal/plan3test
receipt: test step 213ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1.856s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 1.86s amadan.net/oficina/equipo/internal/plan3test TestTeamsHierarchyBrowser
browser lane browser-rest: ./internal/thintest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserEmptyConversation|TestBrowserEndedNoteStaysGone|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingSteady|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackPulse|TestBrowserTrackStarCentre|TestBrowserTryAgain)$' ./internal/thintest
receipt: test step 1.214s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 3m20.199s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 17.52s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.35s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 12.02s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.55s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 7.93s amadan.net/oficina/equipo/internal/thintest TestBrowserInnerScreens
machine: 32 CPUs, load 8.54, cpu waiting 2.31%, memory waiting 0.00%, io waiting 1.84%
--- shard 23 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 23: make test-quarantine
python3 scripts/ci-test.py quarantine
quarantine: 12 tests from scripts/ci-quarantine.txt; a failure is retried once, and a pass on the retry is reported as a flake
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^A5_cancel_and_sign_out$|^TestHeadlessConnections$/^C4_claude_sign_in$|^TestHeadlessConnections$/^C5_engineering_failover$|^TestHeadlessConnections$/^C5_engineering_to_codex$|^TestHeadlessConnections$/^C5_engineering_waits$' ./internal/headless (53s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 5.29s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.37s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 9.78s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 10.14s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 24.93s
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^C5_review_auth$|^TestHeadlessConnections$/^C5_review_failover$|^TestHeadlessConnections$/^C5_review_on_codex$|^TestHeadlessConnections$/^C5_review_other_family_first$' ./internal/headless (55s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 15.41s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 12.99s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 11.29s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 13.70s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless (23s)
ok ./internal/headless TestMixedVersions 20.95s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks (1s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.77s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin (0s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 39.91, cpu waiting 22.76%, memory waiting 0.00%, io waiting 0.79%
--- shard 24 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 24: make runner-host
python3 scripts/runner-prerequisites.py
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
receipt: test step 8.423s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 3 without tests, 0 failed
receipt: slow package 7.199s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 169ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 75ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 2ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 0s amadan.net/oficina/equipo/internal/runner/provider/gotoolchain
receipt: slow test 5.19s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.63s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 290ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 170ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 80ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxToolchain
CGO_ENABLED=0 EQUIPO_REQUIRE_USER_SESSION=1 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run '^TestNamespace' -count=1 ./internal/runner/containment
receipt: test step 3.165s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2.853s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 280ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 190ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 100ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
receipt: slow test 100ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReapsOrphans
machine: 32 CPUs, load 10.26, cpu waiting 4.55%, memory waiting 0.00%, io waiting 1.66%
--- shard 25 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: runner-dead-references started 30s late; cpu waiting 27.0%, load 23.96
shard 25: make runner-dead-references lanes-check build vet fmt-check budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2606 text files, 2854 matches, 0 failures
python3 scripts/ci-test.py check
lanes: 18 lanes and 5 browser lanes run every test once; 20-check@29
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner
go vet ./...
go vet -tags testbuild ./internal/runner/thin ./internal/headless
GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 95 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok amadan.net/oficina/equipo/internal/equipo 2.581s
machine: 32 CPUs, load 38.46, cpu waiting 21.28%, memory waiting 0.00%, io waiting 0.94%
--- shard 26 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: staticcheck started 30s late; cpu waiting 27.0%, load 23.96
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 23.96, cpu waiting 13.52%, memory waiting 0.00%, io waiting 1.15%
--- shard 27 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: govulncheck started 30s late; cpu waiting 27.0%, load 23.96
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===
No vulnerabilities found.
Your code is affected by 0 vulnerabilities.
This scan also found 0 vulnerabilities in packages you import and 5
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
machine: 32 CPUs, load 30.85, cpu waiting 16.60%, memory waiting 0.00%, io waiting 1.07%
--- shard 28 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: gitleaks started 30s late; cpu waiting 27.0%, load 23.96
shard 28: make gitleaks
[90m7:46PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net
[90m7:46PM[0m [32mINF[0m [1m1129 commits scanned.[0m
[90m7:46PM[0m [32mINF[0m [1mscanned ~62035216 bytes (62.04 MB) in 14.7s[0m
[90m7:46PM[0m [32mINF[0m [1mno leaks found[0m
machine: 32 CPUs, load 38.46, cpu waiting 20.34%, memory waiting 0.00%, io waiting 0.97%
diff --git a/cmd/equipo-hosted-controller/alerter.go b/cmd/equipo-hosted-controller/alerter.go| new file mode 100644 |
| index 00000000..cb016640 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/alerter.go |
| @@ -0,0 +1,27 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| +) |
| + |
| +// alertTimeout bounds one alert's delivery. hostedctl.New delivers startup |
| +// alerts with a context that never ends, so the alerter sets its own limit. |
| +const alertTimeout = 10 * time.Second |
| + |
| +// snsAlerter delivers the controller's operator alerts to SNS. |
| +type snsAlerter struct { |
| + pub awsjob.SNSPublisher |
| +} |
| + |
| +var _ hostedctl.Alerter = snsAlerter{} |
| + |
| +// Alert publishes a's kind and detail, giving up after alertTimeout. |
| +func (s snsAlerter) Alert(ctx context.Context, a hostedctl.Alert) error { |
| + ctx, cancel := context.WithTimeout(ctx, alertTimeout) |
| + defer cancel() |
| + return s.pub.Publish(ctx, a.Kind, a.Detail) |
| +} |
diff --git a/cmd/equipo-hosted-controller/alerter_test.go b/cmd/equipo-hosted-controller/alerter_test.go| new file mode 100644 |
| index 00000000..52bb57e1 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/alerter_test.go |
| @@ -0,0 +1,63 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| + "github.com/aws/aws-sdk-go-v2/service/sns" |
| +) |
| + |
| +// recordingSNS records each Publish call and whether its context had a |
| +// deadline. |
| +type recordingSNS struct { |
| + inputs []*sns.PublishInput |
| + deadlines []time.Duration |
| + fail error |
| +} |
| + |
| +func (r *recordingSNS) Publish(ctx context.Context, in *sns.PublishInput, _ ...func(*sns.Options)) (*sns.PublishOutput, error) { |
| + r.inputs = append(r.inputs, in) |
| + d := time.Duration(-1) |
| + if dl, ok := ctx.Deadline(); ok { |
| + d = time.Until(dl) |
| + } |
| + r.deadlines = append(r.deadlines, d) |
| + return &sns.PublishOutput{}, r.fail |
| +} |
| + |
| +func TestAlerterWrapsPublisher(t *testing.T) { |
| + t.Parallel() |
| + rec := &recordingSNS{} |
| + a := snsAlerter{pub: awsjob.SNSPublisher{TopicARN: "arn:aws:sns:eu-west-1:1:t", Client: rec}} |
| + // A context with no deadline, as New uses for startup alerts. |
| + if err := a.Alert(context.Background(), hostedctl.Alert{Kind: hostedctl.AlertOrphanStopped, Detail: "vm-1 stopped"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(rec.inputs) != 1 { |
| + t.Fatalf("%d publishes, want 1", len(rec.inputs)) |
| + } |
| + in := rec.inputs[0] |
| + if *in.TopicArn != "arn:aws:sns:eu-west-1:1:t" || !strings.Contains(*in.Subject, hostedctl.AlertOrphanStopped) || |
| + *in.Message != hostedctl.AlertOrphanStopped+"\n\nvm-1 stopped" { |
| + t.Fatalf("publish input = topic %q subject %q message %q", *in.TopicArn, *in.Subject, *in.Message) |
| + } |
| + if d := rec.deadlines[0]; d <= 0 || d > alertTimeout { |
| + t.Fatalf("publish context deadline in %v, want within %v", d, alertTimeout) |
| + } |
| + |
| + // A shorter deadline from the caller is kept, and a failure is returned. |
| + rec.fail = errors.New("sns down") |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| + defer cancel() |
| + if err := a.Alert(ctx, hostedctl.Alert{Kind: "k"}); err == nil { |
| + t.Fatal("a failed publish returned nil") |
| + } |
| + if d := rec.deadlines[1]; d <= 0 || d > time.Second { |
| + t.Fatalf("publish context deadline in %v, want the caller's 1s", d) |
| + } |
| +} |
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go| new file mode 100644 |
| index 00000000..1267b309 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/config.go |
| @@ -0,0 +1,254 @@ |
| +package main |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/netip" |
| + "os" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| +) |
| + |
| +// fileConfig is the -config file: one JSON object read with |
| +// hostedwire.DecodeStrict, so an unknown or repeated key is refused. Every |
| +// field is required. |
| +// |
| +// Keys. Each controller has verify keys of its own, and each key stays under |
| +// one key ID for good: the key ID is not signed, so a key reused by another |
| +// controller, or an ID moved to another key, cannot be told apart from the |
| +// right one. Load refuses an ID listed twice and one public key under two |
| +// IDs, but cannot see keys shared with another controller. |
| +// |
| +// Launches are switched on only by EQUIPO_HOSTED_ENABLED=1 in the |
| +// environment, never by this file. |
| +type fileConfig struct { |
| + // Listen is the HTTPS API's address and MetricsListen the plain HTTP |
| + // metrics listener's: an IP address and port each, never a wildcard. |
| + Listen string `json:"listen"` |
| + MetricsListen string `json:"metrics_listen"` |
| + TLSCertFile string `json:"tls_cert_file"` |
| + TLSKeyFile string `json:"tls_key_file"` |
| + Database string `json:"database"` |
| + // SigningKeyFile holds the controller's ed25519 seed (32 bytes) in |
| + // standard base64. It must not be readable by group or others. |
| + SigningKeyFile string `json:"signing_key_file"` |
| + VerifyKeys []keyEntry `json:"verify_keys"` |
| + Images []imageEntry `json:"images"` |
| + Region string `json:"region"` |
| + VPCID string `json:"vpc_id"` |
| + VMSubnetID string `json:"vm_subnet_id"` |
| + // VMSecurityGroupID is the connector's only security group. |
| + VMSecurityGroupID string `json:"vm_security_group_id"` |
| + // ConnectorARN is the version-qualified ARN of the VPC_EGRESS connector. |
| + ConnectorARN string `json:"connector_arn"` |
| + // Egress is every "address:port" VMs may reach, as the network audit |
| + // expects it. |
| + Egress []string `json:"egress"` |
| + SNSTopicARN string `json:"sns_topic_arn"` |
| +} |
| + |
| +// keyEntry is one verify key: its ID, role (instance or operator) and |
| +// ed25519 public key in standard base64. |
| +type keyEntry struct { |
| + ID string `json:"id"` |
| + Role string `json:"role"` |
| + PublicKey string `json:"public_key"` |
| +} |
| + |
| +// imageEntry is one certified image: its digest, MicroVM image ARN and the |
| +// image version for each size ("small", "large"). |
| +type imageEntry struct { |
| + Digest string `json:"digest"` |
| + ARN string `json:"arn"` |
| + Versions map[string]string `json:"versions"` |
| +} |
| + |
| +// config is a checked fileConfig, ready to wire. |
| +type config struct { |
| + listen, metricsListen, tlsCert, tlsKey, database, topicARN string |
| + signing ed25519.PrivateKey |
| + keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| + ctl hostedctl.Config |
| + aws awsjob.Config |
| +} |
| + |
| +// enabledEnv is the one switch for launches. |
| +const enabledEnv = "EQUIPO_HOSTED_ENABLED" |
| + |
| +// loadConfig reads and checks the config file at path. getenv reads the |
| +// environment (os.Getenv in main). |
| +func loadConfig(path string, getenv func(string) string) (config, error) { |
| + if path == "" { |
| + return config{}, errors.New("no -config file given") |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return config{}, err |
| + } |
| + defer f.Close() |
| + var fc fileConfig |
| + if err := hostedwire.DecodeStrict(f, &fc); err != nil { |
| + return config{}, fmt.Errorf("config %s: %w", path, err) |
| + } |
| + c, err := fc.check() |
| + if err != nil { |
| + return config{}, fmt.Errorf("config %s: %w", path, err) |
| + } |
| + c.ctl.Enabled = getenv(enabledEnv) == "1" |
| + return c, nil |
| +} |
| + |
| +func (fc fileConfig) check() (config, error) { |
| + c := config{tlsCert: fc.TLSCertFile, tlsKey: fc.TLSKeyFile, database: fc.Database, topicARN: fc.SNSTopicARN} |
| + var err error |
| + if c.listen, err = checkListen("listen", fc.Listen); err != nil { |
| + return config{}, err |
| + } |
| + if c.metricsListen, err = checkListen("metrics_listen", fc.MetricsListen); err != nil { |
| + return config{}, err |
| + } |
| + if c.listen == c.metricsListen { |
| + return config{}, errors.New("listen and metrics_listen must differ") |
| + } |
| + for name, v := range map[string]string{"tls_cert_file": fc.TLSCertFile, "tls_key_file": fc.TLSKeyFile, |
| + "database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN} { |
| + if v == "" { |
| + return config{}, fmt.Errorf("%s is required", name) |
| + } |
| + } |
| + if c.signing, err = readSigningKey(fc.SigningKeyFile); err != nil { |
| + return config{}, err |
| + } |
| + if c.keys, err = verifyKeys(fc.VerifyKeys); err != nil { |
| + return config{}, err |
| + } |
| + if c.aws, err = fc.awsConfig(); err != nil { |
| + return config{}, err |
| + } |
| + c.ctl.Images = map[isolatedjob.ImageDigest]bool{} |
| + for d := range c.aws.Images { |
| + c.ctl.Images[d] = true |
| + } |
| + c.ctl.Egress = c.aws.Egress |
| + return c, nil |
| +} |
| + |
| +// checkListen accepts only "IP:port" with a specific IP: a wildcard |
| +// (0.0.0.0, ::) or an empty host (":port") would listen on every interface, |
| +// and a host name could resolve to anything. |
| +func checkListen(name, addr string) (string, error) { |
| + if addr == "" { |
| + return "", fmt.Errorf("%s is required", name) |
| + } |
| + host, port, err := net.SplitHostPort(addr) |
| + if err != nil { |
| + return "", fmt.Errorf("%s %q is not host:port", name, addr) |
| + } |
| + ip, err := netip.ParseAddr(host) |
| + if err != nil || ip.Zone() != "" { |
| + return "", fmt.Errorf("%s %q must name one IP address, not %q", name, addr, host) |
| + } |
| + if ip.Unmap().IsUnspecified() { |
| + return "", fmt.Errorf("%s %q listens on every interface; name one address", name, addr) |
| + } |
| + n, err := strconv.ParseUint(port, 10, 16) |
| + if err != nil || n == 0 || strconv.FormatUint(n, 10) != port { |
| + return "", fmt.Errorf("%s %q has no valid port", name, addr) |
| + } |
| + return netip.AddrPortFrom(ip, uint16(n)).String(), nil |
| +} |
| + |
| +// readSigningKey reads the base64 seed in path. A file that group or others |
| +// may read is refused. |
| +func readSigningKey(path string) (ed25519.PrivateKey, error) { |
| + info, err := os.Stat(path) |
| + if err != nil { |
| + return nil, fmt.Errorf("signing key: %w", err) |
| + } |
| + if info.Mode().Perm()&0o077 != 0 { |
| + return nil, fmt.Errorf("signing key %s is readable by group or others (mode %v)", path, info.Mode().Perm()) |
| + } |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return nil, fmt.Errorf("signing key: %w", err) |
| + } |
| + seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw))) |
| + if err != nil || len(seed) != ed25519.SeedSize { |
| + return nil, fmt.Errorf("signing key %s must hold a %d-byte ed25519 seed in base64", path, ed25519.SeedSize) |
| + } |
| + return ed25519.NewKeyFromSeed(seed), nil |
| +} |
| + |
| +// verifyKeys builds the key table, refusing an ID listed twice, then checks |
| +// it as the API will (hostedctl.CheckVerifyKeys). |
| +func verifyKeys(entries []keyEntry) (map[hostedwire.KeyID]hostedwire.VerifyKey, error) { |
| + keys := map[hostedwire.KeyID]hostedwire.VerifyKey{} |
| + for _, k := range entries { |
| + id := hostedwire.KeyID(k.ID) |
| + if _, dup := keys[id]; dup { |
| + return nil, fmt.Errorf("verify key ID %q is listed twice", k.ID) |
| + } |
| + pub, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey) |
| + if err != nil { |
| + return nil, fmt.Errorf("verify key %q: public key is not base64", k.ID) |
| + } |
| + keys[id] = hostedwire.VerifyKey{Public: pub, Role: hostedwire.Role(k.Role)} |
| + } |
| + if err := hostedctl.CheckVerifyKeys(keys); err != nil { |
| + return nil, err |
| + } |
| + return keys, nil |
| +} |
| + |
| +// awsConfig builds the adapter's config and checks it with awsjob.New, |
| +// which makes no provider call; main builds the real Runner later. |
| +func (fc fileConfig) awsConfig() (awsjob.Config, error) { |
| + ac := awsjob.Config{Region: fc.Region, ConnectorID: fc.ConnectorARN, VPCID: fc.VPCID, VMSubnetID: fc.VMSubnetID, |
| + VMSecurityGroupID: fc.VMSecurityGroupID, Images: map[isolatedjob.ImageDigest]awsjob.Image{}} |
| + for _, img := range fc.Images { |
| + d := isolatedjob.ImageDigest(img.Digest) |
| + if !validDigest(img.Digest) { |
| + return awsjob.Config{}, fmt.Errorf("image digest %q is not sha256: and 64 lower-case hex digits", img.Digest) |
| + } |
| + if _, dup := ac.Images[d]; dup { |
| + return awsjob.Config{}, fmt.Errorf("image %s is listed twice", d) |
| + } |
| + versions := map[isolatedjob.Size]string{} |
| + for size, v := range img.Versions { |
| + versions[isolatedjob.Size(size)] = v |
| + } |
| + ac.Images[d] = awsjob.Image{ARN: img.ARN, Versions: versions} |
| + } |
| + for _, e := range fc.Egress { |
| + ap, err := netip.ParseAddrPort(e) |
| + if err != nil { |
| + return awsjob.Config{}, fmt.Errorf("egress %q is not address:port", e) |
| + } |
| + ac.Egress = append(ac.Egress, ap) |
| + } |
| + if _, err := awsjob.New(ac, awsjob.NewAPI(nil, nil, nil)); err != nil { |
| + return awsjob.Config{}, err |
| + } |
| + return ac, nil |
| +} |
| + |
| +func validDigest(s string) bool { |
| + hex, ok := strings.CutPrefix(s, "sha256:") |
| + if !ok || len(hex) != 64 { |
| + return false |
| + } |
| + for i := 0; i < len(hex); i++ { |
| + if !(hex[i] >= '0' && hex[i] <= '9' || hex[i] >= 'a' && hex[i] <= 'f') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go| new file mode 100644 |
| index 00000000..8f4e1417 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/config_test.go |
| @@ -0,0 +1,189 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +const testDigest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + |
| +func pubB64(seed byte) string { |
| + k := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{seed}, ed25519.SeedSize)) |
| + return base64.StdEncoding.EncodeToString(k.Public().(ed25519.PublicKey)) |
| +} |
| + |
| +// validConfig is a config that loads, with its signing key written to dir. |
| +func validConfig(t *testing.T, dir string) fileConfig { |
| + t.Helper() |
| + keyPath := filepath.Join(dir, "signing.key") |
| + seed := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, ed25519.SeedSize)) |
| + if err := os.WriteFile(keyPath, []byte(seed+"\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return fileConfig{ |
| + Listen: "127.0.0.1:8443", MetricsListen: "100.119.180.57:9090", |
| + TLSCertFile: "/etc/equipo/tls.crt", TLSKeyFile: "/etc/equipo/tls.key", Database: "/var/lib/equipo/hosted.db", |
| + SigningKeyFile: keyPath, |
| + VerifyKeys: []keyEntry{ |
| + {ID: "inst-1", Role: "instance", PublicKey: pubB64(1)}, |
| + {ID: "op-1", Role: "operator", PublicKey: pubB64(2)}, |
| + }, |
| + Images: []imageEntry{{Digest: testDigest, ARN: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img", |
| + Versions: map[string]string{"small": "1", "large": "2"}}}, |
| + Region: "eu-west-1", VPCID: "vpc-1", VMSubnetID: "subnet-1", VMSecurityGroupID: "sg-1", |
| + ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3", |
| + Egress: []string{"10.0.1.5:443"}, |
| + SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted", |
| + } |
| +} |
| + |
| +// load writes body to a file in dir and loads it with launches off. |
| +func load(t *testing.T, dir string, body []byte) (config, error) { |
| + t.Helper() |
| + path := filepath.Join(dir, "controller.json") |
| + if err := os.WriteFile(path, body, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return loadConfig(path, func(string) string { return "" }) |
| +} |
| + |
| +func loadFC(t *testing.T, dir string, fc fileConfig) (config, error) { |
| + t.Helper() |
| + b, err := json.Marshal(fc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return load(t, dir, b) |
| +} |
| + |
| +func TestConfigRefusesMissingListenOrKeys(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + c, err := loadFC(t, dir, validConfig(t, dir)) |
| + if err != nil { |
| + t.Fatalf("valid config: %v", err) |
| + } |
| + if c.listen != "127.0.0.1:8443" || len(c.keys) != 2 || c.keys["op-1"].Role != hostedwire.RoleOperator || |
| + !c.ctl.Images[testDigest] || len(c.ctl.Egress) != 1 || len(c.signing) != ed25519.PrivateKeySize { |
| + t.Fatalf("valid config loaded as %+v", c) |
| + } |
| + |
| + for name, edit := range map[string]func(*fileConfig){ |
| + "no listen": func(f *fileConfig) { f.Listen = "" }, |
| + "no metrics listen": func(f *fileConfig) { f.MetricsListen = "" }, |
| + "same listen twice": func(f *fileConfig) { f.MetricsListen = f.Listen }, |
| + "no TLS cert": func(f *fileConfig) { f.TLSCertFile = "" }, |
| + "no TLS key": func(f *fileConfig) { f.TLSKeyFile = "" }, |
| + "no database": func(f *fileConfig) { f.Database = "" }, |
| + "no signing key": func(f *fileConfig) { f.SigningKeyFile = "" }, |
| + "missing signing key file": func(f *fileConfig) { f.SigningKeyFile = filepath.Join(dir, "absent") }, |
| + "no verify keys": func(f *fileConfig) { f.VerifyKeys = nil }, |
| + "key ID twice": func(f *fileConfig) { |
| + f.VerifyKeys = append(f.VerifyKeys, keyEntry{ID: "inst-1", Role: "instance", PublicKey: pubB64(3)}) |
| + }, |
| + "public key under two IDs": func(f *fileConfig) { |
| + f.VerifyKeys = append(f.VerifyKeys, keyEntry{ID: "inst-2", Role: "instance", PublicKey: pubB64(1)}) |
| + }, |
| + "unknown role": func(f *fileConfig) { f.VerifyKeys[0].Role = "admin" }, |
| + "short public key": func(f *fileConfig) { f.VerifyKeys[0].PublicKey = "AAAA" }, |
| + "bad key ID": func(f *fileConfig) { f.VerifyKeys[0].ID = "inst 1" }, |
| + "no images": func(f *fileConfig) { f.Images = nil }, |
| + "bad digest": func(f *fileConfig) { f.Images[0].Digest = "sha256:AA" }, |
| + "unqualified connector": func(f *fileConfig) { f.ConnectorARN = "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress" }, |
| + "no egress": func(f *fileConfig) { f.Egress = nil }, |
| + "no SNS topic": func(f *fileConfig) { f.SNSTopicARN = "" }, |
| + } { |
| + sub := t.TempDir() |
| + fc := validConfig(t, sub) |
| + edit(&fc) |
| + if _, err := loadFC(t, sub, fc); err == nil { |
| + t.Errorf("%s: config loaded, want a refusal", name) |
| + } |
| + } |
| + |
| + // A signing key others may read is refused. |
| + sub := t.TempDir() |
| + fc := validConfig(t, sub) |
| + if err := os.Chmod(fc.SigningKeyFile, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := loadFC(t, sub, fc); err == nil || !strings.Contains(err.Error(), "readable") { |
| + t.Errorf("world-readable signing key: %v, want a refusal", err) |
| + } |
| + |
| + // The file is decoded strictly. |
| + b, _ := json.Marshal(validConfig(t, sub)) |
| + for name, body := range map[string]string{ |
| + "unknown field": strings.Replace(string(b), "{", `{"listen_any":true,`, 1), |
| + "repeated field": strings.Replace(string(b), "{", `{"listen":"127.0.0.2:1",`, 1), |
| + } { |
| + if _, err := load(t, sub, []byte(body)); err == nil { |
| + t.Errorf("%s: config loaded, want a refusal", name) |
| + } |
| + } |
| +} |
| + |
| +func TestConfigRefusesWildcardListen(t *testing.T) { |
| + t.Parallel() |
| + for _, addr := range []string{"0.0.0.0:8443", "[::]:8443", ":8443", "[::ffff:0.0.0.0]:8443", "localhost:8443", |
| + "127.0.0.1", "127.0.0.1:0", "127.0.0.1:http", "[fe80::1%eth0]:8443"} { |
| + for _, field := range []string{"listen", "metrics_listen"} { |
| + dir := t.TempDir() |
| + fc := validConfig(t, dir) |
| + if field == "listen" { |
| + fc.Listen = addr |
| + } else { |
| + fc.MetricsListen = addr |
| + } |
| + if _, err := loadFC(t, dir, fc); err == nil { |
| + t.Errorf("%s %q loaded, want a refusal", field, addr) |
| + } |
| + } |
| + } |
| + dir := t.TempDir() |
| + fc := validConfig(t, dir) |
| + fc.Listen, fc.MetricsListen = "[fd7a:115c:a1e0::1]:8443", "100.119.180.57:9090" |
| + if _, err := loadFC(t, dir, fc); err != nil { |
| + t.Errorf("specific addresses refused: %v", err) |
| + } |
| +} |
| + |
| +func TestConfigEnabledOnlyFromEnv(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + b, _ := json.Marshal(validConfig(t, dir)) |
| + path := filepath.Join(dir, "controller.json") |
| + if err := os.WriteFile(path, b, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for value, want := range map[string]bool{"1": true, "": false, "0": false, "true": false, "yes": false, " 1": false} { |
| + c, err := loadConfig(path, func(k string) string { |
| + if k == enabledEnv { |
| + return value |
| + } |
| + return "" |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.ctl.Enabled != want { |
| + t.Errorf("%s=%q: Enabled %v, want %v", enabledEnv, value, c.ctl.Enabled, want) |
| + } |
| + } |
| + // The file cannot switch launches on. |
| + on := strings.Replace(string(b), "{", `{"enabled":true,`, 1) |
| + if c, err := load(t, dir, []byte(on)); err == nil || c.ctl.Enabled { |
| + t.Errorf("config with \"enabled\": loaded %v, Enabled %v; want a refusal", err == nil, c.ctl.Enabled) |
| + } |
| +} |
diff --git a/cmd/equipo-hosted-controller/main.go b/cmd/equipo-hosted-controller/main.go| new file mode 100644 |
| index 00000000..f47ae9a5 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/main.go |
| @@ -0,0 +1,144 @@ |
| +// Command equipo-hosted-controller runs the hosted runner controller: the |
| +// signed HTTPS API Equipo instances and operators call, its metrics |
| +// listener, and the reaper loop. It is the one place the AWS adapter is |
| +// wired in. |
| +// |
| +// equipo-hosted-controller -config /etc/equipo-hosted/controller.json |
| +// |
| +// Launches stay off unless EQUIPO_HOSTED_ENABLED=1; stops, reads and the |
| +// reaper run either way. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "log" |
| + "net" |
| + "net/http" |
| + "os" |
| + "os/signal" |
| + "syscall" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| + "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/sns" |
| +) |
| + |
| +// shutdownTimeout bounds how long the servers get to finish requests in |
| +// flight after a signal. |
| +const shutdownTimeout = 30 * time.Second |
| + |
| +func main() { |
| + path := flag.String("config", "", "path of the controller's JSON config file") |
| + flag.Parse() |
| + if err := run(*path); err != nil { |
| + log.Printf("equipo-hosted-controller: %v", err) |
| + os.Exit(1) |
| + } |
| +} |
| + |
| +func run(path string) error { |
| + cfg, err := loadConfig(path, os.Getenv) |
| + if err != nil { |
| + return err |
| + } |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| + defer stop() |
| + |
| + // Bad TLS files or a busy address fail here, before the store is |
| + // opened or any startup alert is sent. |
| + cert, err := tls.LoadX509KeyPair(cfg.tlsCert, cfg.tlsKey) |
| + if err != nil { |
| + return fmt.Errorf("TLS key pair: %w", err) |
| + } |
| + apiLn, err := net.Listen("tcp", cfg.listen) |
| + if err != nil { |
| + return err |
| + } |
| + defer apiLn.Close() |
| + metricsLn, err := net.Listen("tcp", cfg.metricsListen) |
| + if err != nil { |
| + return err |
| + } |
| + defer metricsLn.Close() |
| + |
| + clock := isolatedjob.SystemClock() |
| + store, err := hostedctl.Open(ctx, cfg.database, clock) |
| + if err != nil { |
| + return err |
| + } |
| + defer func() { |
| + if err := store.Close(); err != nil { |
| + log.Printf("equipo-hosted-controller: close store: %v", err) |
| + } |
| + }() |
| + |
| + // The default credential chain; the region is the config's, which the |
| + // connector ARN is checked against. |
| + awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(cfg.aws.Region)) |
| + if err != nil { |
| + return fmt.Errorf("AWS config: %w", err) |
| + } |
| + runner, err := awsjob.New(cfg.aws, awsjob.NewAPI(lambdamicrovms.NewFromConfig(awsCfg), ec2.NewFromConfig(awsCfg), |
| + lambdacore.NewFromConfig(awsCfg))) |
| + if err != nil { |
| + return err |
| + } |
| + metrics := hostedctl.NewMetrics() |
| + alerter := metrics.CountAlerts(snsAlerter{pub: awsjob.SNSPublisher{TopicARN: cfg.topicARN, Client: sns.NewFromConfig(awsCfg)}}) |
| + c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: runner, Auditor: runner, Alerter: alerter}) |
| + if err != nil { |
| + return err |
| + } |
| + api, err := c.Handler(hostedctl.HandlerConfig{Keys: cfg.keys, Signing: cfg.signing, Wall: clock.Wall, Metrics: metrics}) |
| + if err != nil { |
| + return err |
| + } |
| + apiSrv := &http.Server{ |
| + Handler: api, |
| + TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{cert}}, |
| + ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, |
| + // A launch or stop waits on the provider (up to |
| + // hostedctl.ProviderLaunchTimeout), so writes get longer. |
| + WriteTimeout: 2 * time.Minute, IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10, |
| + } |
| + metricsSrv := &http.Server{Handler: metrics.Handler(c), |
| + ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second} |
| + log.Printf("equipo-hosted-controller: API on %s, metrics on %s, launches enabled: %v", cfg.listen, cfg.metricsListen, cfg.ctl.Enabled) |
| + return serve(ctx, c, apiSrv, apiLn, metricsSrv, metricsLn) |
| +} |
| + |
| +// serve runs the reaper loop and both servers until ctx ends or a server |
| +// fails, then shuts the servers down and waits for the loop. |
| +func serve(ctx context.Context, c *hostedctl.Controller, apiSrv *http.Server, apiLn net.Listener, metricsSrv *http.Server, metricsLn net.Listener) error { |
| + loopCtx, stopLoop := context.WithCancel(ctx) |
| + loopDone := make(chan error, 1) |
| + go func() { loopDone <- c.Loop(loopCtx, hostedctl.ReapInterval) }() |
| + |
| + failed := make(chan error, 2) |
| + go func() { failed <- fmt.Errorf("API server: %w", apiSrv.ServeTLS(apiLn, "", "")) }() |
| + go func() { failed <- fmt.Errorf("metrics server: %w", metricsSrv.Serve(metricsLn)) }() |
| + |
| + var runErr error |
| + select { |
| + case <-ctx.Done(): |
| + case runErr = <-failed: |
| + } |
| + shutCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) |
| + defer cancel() |
| + err := errors.Join(apiSrv.Shutdown(shutCtx), metricsSrv.Shutdown(shutCtx)) |
| + stopLoop() |
| + if lerr := <-loopDone; lerr != nil { |
| + log.Printf("equipo-hosted-controller: last reaper pass: %v", lerr) |
| + } |
| + return errors.Join(runErr, err) |
| +} |
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md| index 3d9d762d..9e5595de 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md |
| @@ -673,3 +673,34 @@ failing of 200 in brackets. |
| | I6 treat `unknown` as terminal (refreshOne) | `seed 4 failed at step 5: I6: a1 holds proof from state "unknown"` (85) | yes, passes | |
| | I7a raise the epoch before preparing (prepare UPDATE sets `epoch = epoch + 1`) | `seed 5 failed at step 21: I7: provider resume of vm-0001 for operation op-1 prepared at epoch 1 while the job's epoch is 1` (13) | yes, passes | |
| | I7b commit on a lost reply (driveResume commits on `ErrLostReply`) | `seed 25 failed at step 21: I7: a2 operation op-1 committed with no running read of vm-0002 after its last resume call` (6) | yes, passes | |
| + |
| +## Task 15 |
| + |
| +Controller HTTP API (`internal/hostedctl/http.go`), metrics (`metrics.go`) and the |
| +`equipo-hosted-controller` command (config, main wiring of awsjob, SNS alerter). No edit to an |
| +existing hostedctl file. |
| + |
| +- RED: `go test ./internal/hostedctl -run 'TestRoutes|...|TestMetrics' -count=1` failed to build |
| + (`undefined: Metrics`, `undefined: HandlerConfig`, `e.c.Handler undefined`, `undefined: apiErrors`, |
| + `undefined: lookupError`). The command's tests were written with its code, not before; each guard |
| + there is shown by the mutations below. First green run: `TestMetricsCountJobsByState` failed on |
| + its own matcher (a HELP line matched the sample name), fixed in the test. |
| +- GREEN: `go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestRoutes|TestInstanceKey|TestUnknownFields|TestResponsesSigned|TestConfig|TestDisabled|TestMetrics' -count=1` |
| + ok; new hostedctl tests 0.2 to 0.46 s each, in parallel; whole hostedctl package 8.0 s at load |
| + average 17 to 19, the same 8.0 s with the new tests skipped; command package 0.01 s. |
| + `make build vet` ok; `go test ./internal/isolatedjob -run TestProviderTypesStayInAdapter` ok; |
| + `scripts/ci-test.py check` ok; `make budget` ok; staticcheck v0.7.0 clean on both packages; |
| + dead-reference scan 0 failures. |
| + |
| +Each mutation was applied alone with a script, the named test run, and the file restored from a |
| +saved copy; the test passes again after each. |
| + |
| +| Mutation | Command | Observed failure | Restored | |
| +| --- | --- | --- | --- | |
| +| Drop the creator check (Get: `j.actor != string(by)` removed) | `go test ./internal/hostedctl -run '^TestInstanceKeySeesOnlyItsJobs$' -count=1` | `http_test.go:287: instance B GET /v1/jobs/a1 = 200 {"attempt_id":"a1",...}, want 403` | yes, passes | |
| +| Drop the handler's role check (`case key.Role != rt.role` to `case false`) | `go test ./internal/hostedctl -run '^TestRoutesEnforceRoles$' -count=1` | `http_test.go:239: operator GET /v1/jobs/a1 audit row = {Actor:op-1 ... Action:get_refused ...}, want api_refused by op-1` | yes, passes | |
| +| Accept a wildcard listen (`IsUnspecified` check off) | `go test ./cmd/equipo-hosted-controller -run '^TestConfigRefusesWildcardListen$' -count=1` | `config_test.go:150: listen "0.0.0.0:8443" loaded, want a refusal` | yes, passes | |
| +| Unsigned responses (`SignResponse` call removed) | `go test ./internal/hostedctl -run '^TestResponsesSigned$' -count=1` | `http_test.go:345: launch = 200 {...}, signed false; want a signed 200` | yes, passes | |
| +| Lax decode (`json.Unmarshal` for `DecodeStrict`) | `go test ./internal/hostedctl -run '^TestUnknownFieldsRefused$' -count=1` | `http_test.go:311: launch with unknown field = 200 {...}, want 400 {"code":"bad_json",...}` | yes, passes | |
| +| Error text in responses (message from `err.Error()`) | `go test ./internal/hostedctl -run '^TestRoutesEnforceRoles$' -count=1` | `http_test.go:232: operator GET /v1/jobs/a1 = 403 {"code":"forbidden","message":"hostedctl: this key may not do that: route get needs the instance role"}, want 403 {"code":"forbidden","message":"This key may not do that."}` | yes, passes | |
| +| Enabled from any non-empty env value (`!= ""` for `== "1"`) | `go test ./cmd/equipo-hosted-controller -run '^TestConfigEnabledOnlyFromEnv$' -count=1` | `config_test.go:181: EQUIPO_HOSTED_ENABLED="true": Enabled true, want false` | yes, passes | |
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go| new file mode 100644 |
| index 00000000..ea531b08 |
| --- /dev/null |
| +++ b/internal/hostedctl/http.go |
| @@ -0,0 +1,521 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// HandlerConfig is what the controller's HTTP API needs besides the |
| +// controller. Every field but Metrics is required. |
| +type HandlerConfig struct { |
| + // Keys are the verify keys and their roles. Each controller has keys of |
| + // its own and keeps each key under one key ID for good: the key ID is not |
| + // signed, so it must never move to another key or another controller. |
| + Keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| + // Signing is the controller's key; every verified request's response is |
| + // signed with it. |
| + Signing ed25519.PrivateKey |
| + // Wall is the wall clock a request's timestamp is checked against. |
| + Wall func() time.Time |
| + // Metrics, when set, counts launches and refusals. |
| + Metrics *Metrics |
| +} |
| + |
| +// Audit action the handler writes when a key's role may not use a route. The |
| +// controller's methods audit their own refusals. |
| +const actionAPIRefused = "api_refused" |
| + |
| +// Errors of the handler itself, before any controller method runs. |
| +var ( |
| + errNoRoute = errors.New("hostedctl: no such route") |
| + errMethod = errors.New("hostedctl: method not allowed on this route") |
| + errQuery = errors.New("hostedctl: routes take no query") |
| + errRead = errors.New("hostedctl: reading the request body failed") |
| +) |
| + |
| +// apiError is how one kind of error is answered: its status, a fixed code |
| +// and a fixed message. The error's own text is never sent. |
| +type apiError struct { |
| + err error |
| + status int |
| + code string |
| + msg string |
| +} |
| + |
| +// apiErrors maps errors to responses, first match wins. ErrStoreLost comes |
| +// first, so a refusal whose audit row could not be written reports the lost |
| +// store. ErrProviderLaunch is 502 rather than 500: the controller is well and |
| +// the intent is saved, so the client may read the job again later. |
| +var apiErrors = []apiError{ |
| + {ErrStoreLost, http.StatusServiceUnavailable, "store_lost", "The controller lost its database. Try again later."}, |
| + {hostedwire.ErrTooLarge, http.StatusRequestEntityTooLarge, "too_large", "The request body is too large."}, |
| + {hostedwire.ErrNonceStore, http.StatusServiceUnavailable, "unavailable", "The request could not be checked. Try again later."}, |
| + {hostedwire.ErrNotConfigured, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, |
| + {hostedwire.ErrSharedKey, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, |
| + {hostedwire.ErrUnsigned, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {hostedwire.ErrMalformed, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {hostedwire.ErrUnknownKey, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {hostedwire.ErrSkew, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {hostedwire.ErrBadSignature, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {hostedwire.ErrReplay, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| + {errRead, http.StatusBadRequest, "unreadable", "The request body could not be read."}, |
| + {errQuery, http.StatusBadRequest, "query", "Routes take no query string."}, |
| + {hostedwire.ErrBadJSON, http.StatusBadRequest, "bad_json", "The body is not the JSON object this route takes."}, |
| + {hostedwire.ErrDuration, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| + {isolatedjob.ErrBootstrapTooLarge, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| + {isolatedjob.ErrInvalid, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| + {ErrImageNotAllowed, http.StatusBadRequest, "image_not_allowed", "The image is not in the allowlist."}, |
| + {ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."}, |
| + {errNoRoute, http.StatusNotFound, "no_route", "No such route."}, |
| + {isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."}, |
| + {errMethod, http.StatusMethodNotAllowed, "method", "This route does not take that method."}, |
| + {ErrStopPending, http.StatusAccepted, "stop_pending", "Stop accepted. The VM is not proven stopped yet; ask again."}, |
| + {ErrGenerationCancelled, http.StatusConflict, "generation_cancelled", "That pause generation is cancelled or not the current one."}, |
| + {ErrNotQuiescent, http.StatusConflict, "not_quiescent", "No quiescent acknowledgement for this pause generation."}, |
| + {ErrResumePending, http.StatusConflict, "resume_pending", "A resume is pending. Retry with its operation ID."}, |
| + {ErrReplacementLive, http.StatusConflict, "replacement_live", "The replaced attempt is not proven stopped."}, |
| + {ErrStateUnknown, http.StatusConflict, "state_unknown", "The provider reports an unknown VM state."}, |
| + {isolatedjob.ErrConflict, http.StatusConflict, "conflict", "The job's state does not allow that."}, |
| + {ErrPastDeadline, http.StatusGone, "past_deadline", "The job's stop time has passed."}, |
| + {isolatedjob.ErrThrottled, http.StatusTooManyRequests, "throttled", "The provider is busy. Try again later."}, |
| + {ErrDisabled, http.StatusServiceUnavailable, "disabled", "Hosted launches are switched off."}, |
| + {ErrNetworkAudit, http.StatusServiceUnavailable, "network_audit", "No network audit has passed recently. Try again later."}, |
| + {ErrProviderLaunch, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, |
| + {isolatedjob.ErrIncomplete, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, |
| +} |
| + |
| +// errInternal answers every error apiErrors does not name. |
| +var errInternal = apiError{status: http.StatusInternalServerError, code: "internal", msg: "The controller failed. Try again later."} |
| + |
| +// lookupError returns how err is answered. |
| +func lookupError(err error) apiError { |
| + for _, a := range apiErrors { |
| + if errors.Is(err, a.err) { |
| + return a |
| + } |
| + } |
| + return errInternal |
| +} |
| + |
| +// route is one API route. serve decodes body (already verified) and calls |
| +// the controller; it returns the status and value of a success. |
| +type route struct { |
| + name string // for metrics and audit rows |
| + method string |
| + role hostedwire.Role |
| + serve func(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) |
| +} |
| + |
| +// jobActions are the POST routes under /v1/jobs/{attempt}/. |
| +var jobActions = map[string]route{ |
| + "stop": {"stop", http.MethodPost, hostedwire.RoleInstance, serveStop}, |
| + "drain": {"drain", http.MethodPost, hostedwire.RoleInstance, serveDrain}, |
| + "quiescent": {"quiescent", http.MethodPost, hostedwire.RoleInstance, serveQuiescent}, |
| + "suspend": {"suspend", http.MethodPost, hostedwire.RoleInstance, serveSuspend}, |
| + "reopen": {"reopen", http.MethodPost, hostedwire.RoleInstance, serveReopen}, |
| + "resume": {"resume", http.MethodPost, hostedwire.RoleInstance, serveResume}, |
| +} |
| + |
| +var ( |
| + routeLaunch = route{"launch", http.MethodPost, hostedwire.RoleInstance, serveLaunch} |
| + routeGet = route{"get", http.MethodGet, hostedwire.RoleInstance, serveGet} |
| + routeVMs = route{"vms", http.MethodGet, hostedwire.RoleOperator, serveVMs} |
| +) |
| + |
| +// matchRoute finds r's route and the attempt its path names. Path segments |
| +// are unescaped one by one, so an attempt ID may hold any character. |
| +func matchRoute(r *http.Request) (route, string, error) { |
| + seg := strings.Split(r.URL.EscapedPath(), "/") |
| + var rt route |
| + var attempt string |
| + switch { |
| + case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs": |
| + rt = routeLaunch |
| + case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "vms": |
| + rt = routeVMs |
| + case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": |
| + rt, attempt = routeGet, seg[3] |
| + case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": |
| + a, ok := jobActions[seg[4]] |
| + if !ok { |
| + return route{}, "", errNoRoute |
| + } |
| + rt, attempt = a, seg[3] |
| + default: |
| + return route{}, "", errNoRoute |
| + } |
| + if attempt != "" { |
| + var err error |
| + if attempt, err = url.PathUnescape(attempt); err != nil { |
| + return route{}, "", errNoRoute |
| + } |
| + } |
| + if r.Method != rt.method { |
| + return rt, attempt, errMethod |
| + } |
| + if r.URL.RawQuery != "" || r.URL.ForceQuery { |
| + return rt, attempt, errQuery |
| + } |
| + return rt, attempt, nil |
| +} |
| + |
| +// Handler returns the controller's HTTP API. It refuses a config with no |
| +// keys, a key of the wrong length or with an unknown role, one public key |
| +// under two key IDs, or a signing key of the wrong length. |
| +// |
| +// Each request goes through, in order: |
| +// |
| +// 1. Read the body, at most hostedwire.MaxBody+1 bytes; more is 413. |
| +// 2. Verify the signature over exactly those bytes, which also records the |
| +// nonce in the store (Store.Remember) so a replay is refused. |
| +// 3. Match the route: an unknown path is 404, another method 405, a query |
| +// 400. |
| +// 4. Check the key's role against the route's; a mismatch is 403 with an |
| +// api_refused audit row. |
| +// 5. Decode the same bytes with hostedwire.DecodeStrict (a GET takes an |
| +// empty body), then call the controller, which checks that the key |
| +// created the attempt and audits its own refusals. |
| +// |
| +// A request that fails at step 1 or 2 is answered unsigned with a fixed |
| +// body: its nonce is not yet verified, and signing a response bound to a |
| +// nonce anyone may choose would hand out controller-signed refusals. Every |
| +// later response, refusals included, is signed with hostedwire.SignResponse |
| +// bound to the request's nonce. Every error is answered from apiErrors with a |
| +// fixed code and message, never the error's own text. |
| +func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) { |
| + if err := CheckVerifyKeys(hc.Keys); err != nil { |
| + return nil, err |
| + } |
| + if len(hc.Signing) != ed25519.PrivateKeySize { |
| + return nil, errors.New("hostedctl: the signing key has the wrong length") |
| + } |
| + if hc.Wall == nil { |
| + return nil, errors.New("hostedctl: the API needs a wall clock") |
| + } |
| + keys := make(map[hostedwire.KeyID]hostedwire.VerifyKey, len(hc.Keys)) |
| + for id, k := range hc.Keys { |
| + keys[id] = hostedwire.VerifyKey{Public: bytes.Clone(k.Public), Role: k.Role} |
| + } |
| + return &apiHandler{ |
| + c: c, |
| + v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall}, |
| + sign: bytes.Clone(hc.Signing), |
| + m: hc.Metrics, |
| + }, nil |
| +} |
| + |
| +// CheckVerifyKeys refuses an empty key table, a key ID or public key of the |
| +// wrong form, a role other than instance or operator, and one public key |
| +// under two key IDs. |
| +func CheckVerifyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) error { |
| + if len(keys) == 0 { |
| + return errors.New("hostedctl: no verify keys") |
| + } |
| + seen := map[string]hostedwire.KeyID{} |
| + for id, k := range keys { |
| + if !validKeyID(string(id)) { |
| + return fmt.Errorf("hostedctl: key ID %q must be 1 to 64 characters of A-Z, a-z, 0-9, '.', '_' or '-'", id) |
| + } |
| + if len(k.Public) != ed25519.PublicKeySize { |
| + return fmt.Errorf("hostedctl: public key of %s has the wrong length", id) |
| + } |
| + if k.Role != hostedwire.RoleInstance && k.Role != hostedwire.RoleOperator { |
| + return fmt.Errorf("hostedctl: key %s has role %q; want instance or operator", id, k.Role) |
| + } |
| + if other, dup := seen[string(k.Public)]; dup { |
| + return fmt.Errorf("hostedctl: %w: %s and %s", hostedwire.ErrSharedKey, other, id) |
| + } |
| + seen[string(k.Public)] = id |
| + } |
| + return nil |
| +} |
| + |
| +// validKeyID matches hostedwire's key ID rule: 1 to 64 characters of |
| +// [A-Za-z0-9._-]. |
| +func validKeyID(s string) bool { |
| + if len(s) < 1 || len(s) > 64 { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + c := s[i] |
| + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +type apiHandler struct { |
| + c *Controller |
| + v *hostedwire.Verifier |
| + sign ed25519.PrivateKey |
| + m *Metrics |
| +} |
| + |
| +func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + body, err := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1)) |
| + switch { |
| + case err != nil: |
| + err = errRead |
| + case len(body) > hostedwire.MaxBody: |
| + err = hostedwire.ErrTooLarge |
| + } |
| + var by hostedwire.KeyID |
| + var key hostedwire.VerifyKey |
| + if err == nil { |
| + by, key, err = h.v.Verify(r, body) |
| + } |
| + if err != nil { |
| + a := lookupError(err) |
| + h.m.apiError("unverified", a.code) |
| + h.write(w, a.status, errorBody(a), "") |
| + return |
| + } |
| + nonce := headerValue(r.Header, hostedwire.HeaderNonce) |
| + ctx := r.Context() |
| + |
| + rt, attempt, err := matchRoute(r) |
| + switch { |
| + case err != nil: |
| + case key.Role != rt.role: |
| + err = h.refuseRole(ctx, by, key.Role, rt, attempt) |
| + case rt.method == http.MethodGet && len(body) != 0: |
| + err = fmt.Errorf("%w: a GET takes no body", hostedwire.ErrBadJSON) |
| + } |
| + var out any |
| + if err == nil { |
| + out, err = rt.serve(ctx, h.c, by, key, attempt, body) |
| + } |
| + name := rt.name |
| + if name == "" { |
| + name = "none" |
| + } |
| + if err != nil { |
| + a := lookupError(err) |
| + h.m.apiError(name, a.code) |
| + if rt.name == routeLaunch.name { |
| + h.m.launch(a.code) |
| + } |
| + h.write(w, a.status, errorBody(a), nonce) |
| + return |
| + } |
| + resp, err := json.Marshal(out) |
| + if err != nil { |
| + h.m.apiError(name, errInternal.code) |
| + h.write(w, errInternal.status, errorBody(errInternal), nonce) |
| + return |
| + } |
| + if v, ok := out.(hostedwire.JobView); ok && rt.name == routeLaunch.name { |
| + h.m.launch(v.State) |
| + } |
| + h.write(w, http.StatusOK, resp, nonce) |
| +} |
| + |
| +// write sends body with status, signed for nonce unless nonce is empty. |
| +func (h *apiHandler) write(w http.ResponseWriter, status int, body []byte, nonce string) { |
| + hdr := w.Header() |
| + hdr.Set("Content-Type", "application/json") |
| + hdr.Set("Cache-Control", "no-store") |
| + if nonce != "" { |
| + hostedwire.SignResponse(hdr, status, nonce, body, h.sign) |
| + } |
| + w.WriteHeader(status) |
| + _, _ = w.Write(body) |
| +} |
| + |
| +func errorBody(a apiError) []byte { |
| + b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) |
| + return b |
| +} |
| + |
| +// headerValue returns the one value of name; Verify has already checked |
| +// there is exactly one, under any spelling of the name. |
| +func headerValue(h http.Header, name string) string { |
| + for k, v := range h { |
| + if strings.EqualFold(k, name) && len(v) == 1 { |
| + return v[0] |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// refuseRole audits a key whose role may not use rt and returns ErrForbidden |
| +// (joined with the audit's error, if any). |
| +func (h *apiHandler) refuseRole(ctx context.Context, by hostedwire.KeyID, role hostedwire.Role, rt route, attempt string) error { |
| + err := fmt.Errorf("%w: route %s needs the %s role", ErrForbidden, rt.name, rt.role) |
| + if !printableASCII(attempt, maxNameLen) { |
| + attempt = "" |
| + } |
| + aerr := h.c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionAPIRefused, |
| + Reason: fmt.Sprintf("route %s needs the %s role; the key has %s", rt.name, rt.role, role), At: h.c.store.Clock().Now()}) |
| + }) |
| + return errors.Join(err, aerr) |
| +} |
| + |
| +// decode reads body into v with hostedwire.DecodeStrict: the same bytes the |
| +// signature covers. |
| +func decode(body []byte, v any) error { |
| + return hostedwire.DecodeStrict(bytes.NewReader(body), v) |
| +} |
| + |
| +func serveLaunch(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| + var q hostedwire.LaunchRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + life, err := q.MaxLifetime() |
| + if err != nil { |
| + return nil, err |
| + } |
| + v, err := c.Launch(ctx, by, key, LaunchRequest{AttemptID: q.AttemptID, TaskID: q.TaskID, Account: q.Account, |
| + Replaces: q.Replaces, Image: q.Image, Size: q.Size, MaxLifetime: life, InstanceCode: q.InstanceCode}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return wireView(v), nil |
| +} |
| + |
| +// serveGet: Get takes no key, so the route's role check above is the only |
| +// one; Get itself checks that by created the attempt. |
| +func serveGet(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, attempt string, _ []byte) (any, error) { |
| + v, err := c.Get(ctx, by, attempt) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return wireView(v), nil |
| +} |
| + |
| +func wireView(v JobView) hostedwire.JobView { |
| + return hostedwire.JobView{AttemptID: v.AttemptID, LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch, |
| + DeadlineInMS: v.DeadlineIn.Milliseconds(), DrainInMS: v.DrainIn.Milliseconds(), StopInMS: v.StopIn.Milliseconds()} |
| +} |
| + |
| +func serveStop(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.StopRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + p, err := c.Stop(ctx, by, key, attempt, q.Reason) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return p.wire(), nil |
| +} |
| + |
| +func serveDrain(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.DrainRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + g, err := c.Drain(ctx, by, key, attempt) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.DrainResponse{Generation: g}, nil |
| +} |
| + |
| +func serveQuiescent(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.QuiescentRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + if err := c.Quiescent(ctx, by, key, attempt, q.Generation); err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.QuiescentResponse(q), nil |
| +} |
| + |
| +func serveSuspend(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.SuspendRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + if err := c.Suspend(ctx, by, key, attempt, q.Generation); err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.SuspendResponse(q), nil |
| +} |
| + |
| +func serveReopen(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.ReopenRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + if err := c.Reopen(ctx, by, key, attempt, q.Generation); err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.ReopenResponse(q), nil |
| +} |
| + |
| +func serveResume(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| + var q hostedwire.ResumeRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + epoch, err := c.Resume(ctx, by, key, attempt, q.OperationID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.ResumeResponse{Epoch: epoch}, nil |
| +} |
| + |
| +func serveVMs(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) { |
| + vms, err := c.ListVMs(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.VMListResponse{VMs: vms}, nil |
| +} |
| + |
| +// ListVMs returns every VM the provider lists, each with the attempt whose |
| +// saved Ref it is, or "" when it is no job's. A VM a launch intent may own |
| +// but has no Ref saved yet shows "". It makes one provider List and changes |
| +// nothing. |
| +func (c *Controller) ListVMs(ctx context.Context) ([]hostedwire.VMView, error) { |
| + vms, err := c.runner.List(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + owners := map[isolatedjob.Ref]string{} |
| + err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + rows, err := tx.QueryContext(ctx, `SELECT vm_ref, attempt_id FROM jobs WHERE vm_ref IS NOT NULL`) |
| + if err != nil { |
| + return fmt.Errorf("hostedctl: read job refs: %w", err) |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var ref, attempt string |
| + if err := rows.Scan(&ref, &attempt); err != nil { |
| + return fmt.Errorf("hostedctl: read job refs: %w", err) |
| + } |
| + owners[isolatedjob.Ref(ref)] = attempt |
| + } |
| + return rows.Err() |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := make([]hostedwire.VMView, 0, len(vms)) |
| + for _, vm := range vms { |
| + v := hostedwire.VMView{VMRef: vm.Ref, State: vm.State, AttemptID: owners[vm.Ref], AgeKnown: vm.AgeKnown} |
| + if vm.AgeKnown { |
| + v.AgeMS = vm.ProviderAge.Milliseconds() |
| + } |
| + out = append(out, v) |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/hostedctl/http_test.go b/internal/hostedctl/http_test.go| new file mode 100644 |
| index 00000000..befc71ac |
| --- /dev/null |
| +++ b/internal/hostedctl/http_test.go |
| @@ -0,0 +1,539 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// Keys of the HTTP tests: two instance keys, an operator key and the |
| +// controller's signing key. |
| +var ( |
| + keyInstA = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| + keyInstB = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)) |
| + keyOp = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3}, ed25519.SeedSize)) |
| + keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) |
| +) |
| + |
| +const ( |
| + idInstA hostedwire.KeyID = "inst-a" |
| + idInstB hostedwire.KeyID = "inst-b" |
| + idOp hostedwire.KeyID = "op-1" |
| +) |
| + |
| +func testKeys() map[hostedwire.KeyID]hostedwire.VerifyKey { |
| + return map[hostedwire.KeyID]hostedwire.VerifyKey{ |
| + idInstA: {Public: keyInstA.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, |
| + idInstB: {Public: keyInstB.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, |
| + idOp: {Public: keyOp.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator}, |
| + } |
| +} |
| + |
| +// apiEnv is a launchEnv with the controller's API served over TLS on |
| +// 127.0.0.1. |
| +type apiEnv struct { |
| + *launchEnv |
| + srv *httptest.Server |
| + metrics *Metrics |
| + nonces int |
| +} |
| + |
| +func newAPIEnv(t *testing.T, enabled bool) *apiEnv { |
| + t.Helper() |
| + e := &apiEnv{launchEnv: newLaunchEnv(t)} |
| + if !enabled { |
| + e.cfg.Enabled = false |
| + e.newController() |
| + e.audit() |
| + } |
| + e.serve() |
| + return e |
| +} |
| + |
| +// serve starts (or restarts) the API server over the current controller. |
| +func (e *apiEnv) serve() { |
| + e.t.Helper() |
| + if e.srv != nil { |
| + e.srv.Close() |
| + } |
| + e.metrics = NewMetrics() |
| + h, err := e.c.Handler(HandlerConfig{Keys: testKeys(), Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics}) |
| + if err != nil { |
| + e.t.Fatalf("Handler = %v", err) |
| + } |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + e.t.Fatal(err) |
| + } |
| + e.srv = httptest.NewUnstartedServer(h) |
| + e.srv.Listener = ln |
| + e.srv.StartTLS() |
| + e.t.Cleanup(e.srv.Close) |
| +} |
| + |
| +// reply is one answer from the API. |
| +type reply struct { |
| + status int |
| + body []byte |
| + resp *http.Response |
| + nonce string |
| +} |
| + |
| +// signed reports whether the reply carries a controller signature bound to |
| +// its request's nonce. |
| +func (r reply) signed() bool { |
| + return hostedwire.VerifyResponse(r.resp, r.body, r.nonce, keyCtl.Public().(ed25519.PublicKey)) == nil |
| +} |
| + |
| +// errBody decodes an ErrorResponse. |
| +func (r reply) errBody(t *testing.T) hostedwire.ErrorResponse { |
| + t.Helper() |
| + var er hostedwire.ErrorResponse |
| + if err := json.Unmarshal(r.body, &er); err != nil { |
| + t.Fatalf("error body %q: %v", r.body, err) |
| + } |
| + return er |
| +} |
| + |
| +// nextNonce returns a fresh nonce for this env. |
| +func (e *apiEnv) nextNonce() string { |
| + e.nonces++ |
| + return fmt.Sprintf("test-nonce-%010d", e.nonces) |
| +} |
| + |
| +// newRequest builds a request signed by key under id with a fresh nonce. |
| +func (e *apiEnv) newRequest(method, path string, body []byte, id hostedwire.KeyID, key ed25519.PrivateKey) (*http.Request, string) { |
| + e.t.Helper() |
| + req, err := http.NewRequest(method, e.srv.URL+path, bytes.NewReader(body)) |
| + if err != nil { |
| + e.t.Fatal(err) |
| + } |
| + nonce := e.nextNonce() |
| + if err := hostedwire.SignRequest(req, body, id, key, e.clk.Wall(), nonce); err != nil { |
| + e.t.Fatal(err) |
| + } |
| + return req, nonce |
| +} |
| + |
| +func (e *apiEnv) send(req *http.Request, nonce string) reply { |
| + e.t.Helper() |
| + resp, err := e.srv.Client().Do(req) |
| + if err != nil { |
| + e.t.Fatalf("%s %s: %v", req.Method, req.URL.Path, err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + e.t.Fatal(err) |
| + } |
| + return reply{status: resp.StatusCode, body: b, resp: resp, nonce: nonce} |
| +} |
| + |
| +// call sends one signed request and wants a signed reply. |
| +func (e *apiEnv) call(method, path string, body any, id hostedwire.KeyID, key ed25519.PrivateKey) reply { |
| + e.t.Helper() |
| + var raw []byte |
| + switch b := body.(type) { |
| + case nil: |
| + case string: |
| + raw = []byte(b) |
| + default: |
| + var err error |
| + if raw, err = json.Marshal(b); err != nil { |
| + e.t.Fatal(err) |
| + } |
| + } |
| + r := e.send(e.newRequest(method, path, raw, id, key)) |
| + if !r.signed() { |
| + e.t.Fatalf("%s %s answered %d %q without a valid signature", method, path, r.status, r.body) |
| + } |
| + return r |
| +} |
| + |
| +func wireLaunch(attempt string) hostedwire.LaunchRequest { |
| + return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA, |
| + Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: testCode} |
| +} |
| + |
| +// launch launches attempt as instance A and wants a 200. |
| +func (e *apiEnv) launch(attempt string) hostedwire.JobView { |
| + e.t.Helper() |
| + r := e.call("POST", "/v1/jobs", wireLaunch(attempt), idInstA, keyInstA) |
| + if r.status != http.StatusOK { |
| + e.t.Fatalf("launch %s = %d %s", attempt, r.status, r.body) |
| + } |
| + var v hostedwire.JobView |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &v); err != nil { |
| + e.t.Fatalf("launch reply %q: %v", r.body, err) |
| + } |
| + return v |
| +} |
| + |
| +// jobRoutes are the attempt routes with a valid body for each. |
| +func jobRoutes(attempt string) []struct { |
| + method, path string |
| + body any |
| +} { |
| + p := "/v1/jobs/" + attempt |
| + return []struct { |
| + method, path string |
| + body any |
| + }{ |
| + {"GET", p, nil}, |
| + {"POST", p + "/stop", hostedwire.StopRequest{Reason: "done"}}, |
| + {"POST", p + "/drain", hostedwire.DrainRequest{}}, |
| + {"POST", p + "/quiescent", hostedwire.QuiescentRequest{Generation: 1}}, |
| + {"POST", p + "/suspend", hostedwire.SuspendRequest{Generation: 1}}, |
| + {"POST", p + "/reopen", hostedwire.ReopenRequest{Generation: 1}}, |
| + {"POST", p + "/resume", hostedwire.ResumeRequest{OperationID: "op-1"}}, |
| + } |
| +} |
| + |
| +// fixedBody is the exact body of a refusal with code. |
| +func fixedBody(t *testing.T, code string) string { |
| + t.Helper() |
| + for _, a := range apiErrors { |
| + if a.code == code { |
| + b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) |
| + return string(b) |
| + } |
| + } |
| + t.Fatalf("no API error with code %q", code) |
| + return "" |
| +} |
| + |
| +func TestRoutesEnforceRoles(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + view := e.launch("a1") |
| + |
| + // The operator key may use no job route: the handler refuses it with a |
| + // signed 403 and its own audit row, before any controller method runs. |
| + routes := append(jobRoutes("a1"), struct { |
| + method, path string |
| + body any |
| + }{"POST", "/v1/jobs", wireLaunch("a2")}) |
| + for _, rt := range routes { |
| + before := len(auditRows(t, e.store)) |
| + r := e.call(rt.method, rt.path, rt.body, idOp, keyOp) |
| + if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { |
| + t.Fatalf("operator %s %s = %d %s, want 403 %s", rt.method, rt.path, r.status, r.body, fixedBody(t, "forbidden")) |
| + } |
| + rows := auditRows(t, e.store) |
| + if len(rows) != before+1 { |
| + t.Fatalf("operator %s %s wrote %d audit rows, want 1", rt.method, rt.path, len(rows)-before) |
| + } |
| + if a := rows[len(rows)-1]; a.Action != actionAPIRefused || a.Actor != idOp { |
| + t.Fatalf("operator %s %s audit row = %+v, want %s by %s", rt.method, rt.path, a, actionAPIRefused, idOp) |
| + } |
| + } |
| + if j, _ := e.job("a1"); j.state != JobStarting || e.jobCount() != 1 { |
| + t.Fatalf("after the operator's refused calls: a1 %s, %d jobs; want a1 starting and no new job", j.state, e.jobCount()) |
| + } |
| + |
| + // An instance key may not list VMs. |
| + before := len(auditRows(t, e.store)) |
| + if r := e.call("GET", "/v1/vms", nil, idInstA, keyInstA); r.status != http.StatusForbidden { |
| + t.Fatalf("instance GET /v1/vms = %d %s, want 403", r.status, r.body) |
| + } |
| + if rows := auditRows(t, e.store); len(rows) != before+1 || rows[len(rows)-1].Action != actionAPIRefused { |
| + t.Fatalf("instance GET /v1/vms audit rows %v, want one %s", rows[before:], actionAPIRefused) |
| + } |
| + |
| + // The operator key lists VMs, each with its attempt. |
| + r := e.call("GET", "/v1/vms", nil, idOp, keyOp) |
| + if r.status != http.StatusOK { |
| + t.Fatalf("operator GET /v1/vms = %d %s", r.status, r.body) |
| + } |
| + var list hostedwire.VMListResponse |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &list); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(list.VMs) != 1 || list.VMs[0].VMRef != view.VMRef || list.VMs[0].AttemptID != "a1" { |
| + t.Fatalf("GET /v1/vms = %+v, want only a1's VM %s", list.VMs, view.VMRef) |
| + } |
| +} |
| + |
| +func TestInstanceKeySeesOnlyItsJobs(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + view := e.launch("a1") |
| + if view.AttemptID != "a1" || view.State != JobStarting || view.VMRef == "" || len(view.LaunchID) != launchIDLen { |
| + t.Fatalf("launch view = %+v", view) |
| + } |
| + r := e.call("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| + if r.status != http.StatusOK { |
| + t.Fatalf("creator GET = %d %s", r.status, r.body) |
| + } |
| + |
| + // Another instance key gets the same 403 for a1 and for an attempt |
| + // that does not exist, so it learns nothing of a1. |
| + for _, attempt := range []string{"a1", "nope"} { |
| + for _, rt := range jobRoutes(attempt) { |
| + r := e.call(rt.method, rt.path, rt.body, idInstB, keyInstB) |
| + if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { |
| + t.Fatalf("instance B %s %s = %d %s, want 403", rt.method, rt.path, r.status, r.body) |
| + } |
| + } |
| + } |
| + if j, _ := e.job("a1"); j.state != JobStarting || j.stopRequested.Valid { |
| + t.Fatalf("a1 after instance B's calls = %s (stop asked %v), want starting with no stop", j.state, j.stopRequested.Valid) |
| + } |
| + // A second launch of a1 by B is a conflict, not a takeover. |
| + if r := e.call("POST", "/v1/jobs", wireLaunch("a1"), idInstB, keyInstB); r.status != http.StatusConflict { |
| + t.Fatalf("instance B relaunch of a1 = %d %s, want 409", r.status, r.body) |
| + } |
| +} |
| + |
| +func TestUnknownFieldsRefused(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + good, _ := json.Marshal(wireLaunch("a1")) |
| + extra := strings.Replace(string(good), "{", `{"vm_ref":"vm-9",`, 1) |
| + upper := strings.Replace(string(good), `"attempt_id"`, `"Attempt_ID"`, 1) |
| + twice := strings.Replace(string(good), "{", `{"attempt_id":"a9",`, 1) |
| + for _, c := range []struct{ name, body string }{{"unknown field", extra}, {"upper-case key", upper}, |
| + {"repeated key", twice}, {"two objects", string(good) + string(good)}, {"not an object", `[1]`}, {"empty", ``}} { |
| + r := e.call("POST", "/v1/jobs", c.body, idInstA, keyInstA) |
| + if r.status != http.StatusBadRequest || string(r.body) != fixedBody(t, "bad_json") { |
| + t.Fatalf("launch with %s = %d %s, want 400 %s", c.name, r.status, r.body, fixedBody(t, "bad_json")) |
| + } |
| + } |
| + if n := e.jobCount(); n != 0 { |
| + t.Fatalf("%d jobs after refused launches, want 0", n) |
| + } |
| + e.launch("a1") |
| + for path, body := range map[string]string{ |
| + "/v1/jobs/a1/stop": `{"reason":"done","force":true}`, |
| + "/v1/jobs/a1/drain": `{"generation":1}`, |
| + "/v1/jobs/a1": `{}`, // GET takes no body |
| + } { |
| + method := "POST" |
| + if path == "/v1/jobs/a1" { |
| + method = "GET" |
| + } |
| + if r := e.call(method, path, body, idInstA, keyInstA); r.status != http.StatusBadRequest { |
| + t.Fatalf("%s %s with %s = %d %s, want 400", method, path, body, r.status, r.body) |
| + } |
| + } |
| + if j, _ := e.job("a1"); j.stopRequested.Valid || j.state != JobStarting { |
| + t.Fatalf("a1 after refused bodies = %s, stop asked %v; want untouched", j.state, j.stopRequested.Valid) |
| + } |
| +} |
| + |
| +func TestResponsesSigned(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + |
| + // Success, refusals and unknown routes are all signed, bound to the |
| + // request's nonce. |
| + req, nonce := e.newRequest("POST", "/v1/jobs", mustJSON(t, wireLaunch("a1")), idInstA, keyInstA) |
| + r := e.send(req, nonce) |
| + if r.status != http.StatusOK || !r.signed() { |
| + t.Fatalf("launch = %d %s, signed %v; want a signed 200", r.status, r.body, r.signed()) |
| + } |
| + r.nonce = e.nextNonce() |
| + if r.signed() { |
| + t.Fatal("the launch reply verifies against another nonce") |
| + } |
| + for _, c := range []struct { |
| + method, path string |
| + want int |
| + code string |
| + }{ |
| + {"GET", "/v1/nothing", http.StatusNotFound, "no_route"}, |
| + {"GET", "/v1/jobs/a1/stop", http.StatusMethodNotAllowed, "method"}, |
| + {"DELETE", "/v1/jobs/a1", http.StatusMethodNotAllowed, "method"}, |
| + {"GET", "/v1/vms?all=1", http.StatusBadRequest, "query"}, |
| + } { |
| + r := e.call(c.method, c.path, nil, idOp, keyOp) |
| + if r.status != c.want || string(r.body) != fixedBody(t, c.code) { |
| + t.Fatalf("%s %s = %d %s, want signed %d %s", c.method, c.path, r.status, r.body, c.want, fixedBody(t, c.code)) |
| + } |
| + } |
| + |
| + // A request that fails verification is answered unsigned, with a |
| + // fixed body naming no reason. |
| + unauth := fixedBody(t, "unauthorized") |
| + check := func(name string, r reply, status int, body string) { |
| + t.Helper() |
| + if r.status != status || string(r.body) != body || r.resp.Header.Get(hostedwire.HeaderSignature) != "" { |
| + t.Fatalf("%s = %d %q (signature %q), want unsigned %d %s", name, r.status, r.body, |
| + r.resp.Header.Get(hostedwire.HeaderSignature), status, body) |
| + } |
| + } |
| + plain, _ := http.NewRequest("GET", e.srv.URL+"/v1/jobs/a1", nil) |
| + check("unsigned request", e.send(plain, "nonce-unused-0000000"), http.StatusUnauthorized, unauth) |
| + |
| + req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstB) // B's key under A's ID |
| + check("wrong key", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| + |
| + req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, "inst-z", keyInstA) |
| + check("unknown key ID", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| + |
| + req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| + again := req.Clone(req.Context()) |
| + if r := e.send(req, nonce); r.status != http.StatusOK || !r.signed() { |
| + t.Fatalf("first send = %d %s", r.status, r.body) |
| + } |
| + check("replay", e.send(again, nonce), http.StatusUnauthorized, unauth) |
| + |
| + req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| + e.clk.SetWall(testWall.Add(hostedwire.MaxSkew + time.Second)) |
| + check("skewed", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| + e.clk.SetWall(testWall) |
| + |
| + big := bytes.Repeat([]byte{' '}, hostedwire.MaxBody+1) |
| + req, nonce = e.newRequest("POST", "/v1/jobs", nil, idInstA, keyInstA) |
| + req.Body, req.ContentLength = io.NopCloser(bytes.NewReader(big)), int64(len(big)) |
| + check("too large", e.send(req, nonce), http.StatusRequestEntityTooLarge, fixedBody(t, "too_large")) |
| +} |
| + |
| +func mustJSON(t *testing.T, v any) []byte { |
| + t.Helper() |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +func TestDisabledRefusesLaunchButServesStop(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + e.launch("a1") |
| + |
| + // The same store under a controller with launches off. |
| + e.cfg.Enabled = false |
| + e.newController() |
| + e.audit() |
| + e.serve() |
| + |
| + r := e.call("POST", "/v1/jobs", wireLaunch("a2"), idInstA, keyInstA) |
| + if r.status != http.StatusServiceUnavailable || r.errBody(t).Code != "disabled" { |
| + t.Fatalf("launch while disabled = %d %s, want 503 disabled", r.status, r.body) |
| + } |
| + if e.jobCount() != 1 { |
| + t.Fatalf("%d jobs, want only a1", e.jobCount()) |
| + } |
| + |
| + // Stop is served: pending first, then proof. |
| + stop := hostedwire.StopRequest{Reason: "done"} |
| + r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) |
| + if r.status != http.StatusAccepted || r.errBody(t).Code != "stop_pending" { |
| + t.Fatalf("stop while disabled = %d %s, want 202 stop_pending", r.status, r.body) |
| + } |
| + e.fake.Tick() |
| + r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) |
| + var proof hostedwire.StopProof |
| + if r.status != http.StatusOK || hostedwire.DecodeStrict(bytes.NewReader(r.body), &proof) != nil || |
| + proof.AttemptID != "a1" || !proof.State.Terminal() { |
| + t.Fatalf("second stop = %d %s, want 200 with proof", r.status, r.body) |
| + } |
| +} |
| + |
| +func TestMetricsCountJobsByState(t *testing.T) { |
| + t.Parallel() |
| + e := newAPIEnv(t, true) |
| + e.launch("a1") |
| + e.launch("a2") |
| + e.call("POST", "/v1/jobs/a1/stop", hostedwire.StopRequest{Reason: "done"}, idInstA, keyInstA) |
| + e.call("GET", "/v1/vms", nil, idInstA, keyInstA) // a refusal |
| + |
| + got := e.scrape() |
| + for _, line := range []string{ |
| + `equipo_hosted_jobs{state="starting"} 1`, |
| + `equipo_hosted_jobs{state="stopping"} 1`, |
| + `equipo_hosted_jobs{state="waiting"} 0`, |
| + `equipo_hosted_store_readable 1`, |
| + `equipo_hosted_launches_total{result="starting"} 2`, |
| + `equipo_hosted_errors_total{route="stop",code="stop_pending"} 1`, |
| + `equipo_hosted_errors_total{route="vms",code="forbidden"} 1`, |
| + `equipo_hosted_network_audit_passing 1`, |
| + } { |
| + if !strings.Contains(got, "\n"+line+"\n") { |
| + t.Errorf("metrics lack %q:\n%s", line, got) |
| + } |
| + } |
| + if strings.Contains(got, "\nequipo_hosted_reap_last_error ") { |
| + t.Errorf("metrics report a reaper pass before any ran:\n%s", got) |
| + } |
| + |
| + // After a pass whose alert is delivered, its results and the alert show. |
| + al := e.metrics.CountAlerts(&recordingAlerter{}) |
| + if err := al.Alert(e.ctx, Alert{Kind: AlertOrphanStopped, Detail: "vm-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + failing := e.metrics.CountAlerts(&recordingAlerter{fail: errors.New("down")}) |
| + _ = failing.Alert(e.ctx, Alert{Kind: AlertAuditFailed}) |
| + e.reap() |
| + got = e.scrape() |
| + for _, line := range []string{ |
| + `equipo_hosted_reap_last_error 0`, |
| + `equipo_hosted_reap_last_orphans_stopped 0`, |
| + `equipo_hosted_reap_last_orphans_deferred 0`, |
| + `equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1`, |
| + `equipo_hosted_alerts_total{kind="audit_failed",result="failed"} 1`, |
| + } { |
| + if !strings.Contains(got, "\n"+line+"\n") { |
| + t.Errorf("metrics after a pass lack %q:\n%s", line, got) |
| + } |
| + } |
| + |
| + // An unreadable store leaves the job counts out, never zero. |
| + if err := e.store.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + got = e.scrape() |
| + if strings.Contains(got, "equipo_hosted_jobs{") || !strings.Contains(got, "\nequipo_hosted_store_readable 0\n") { |
| + t.Fatalf("metrics with the store closed:\n%s", got) |
| + } |
| +} |
| + |
| +// scrape reads the metrics page. |
| +func (e *apiEnv) scrape() string { |
| + e.t.Helper() |
| + rec := httptest.NewRecorder() |
| + e.metrics.Handler(e.c).ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) |
| + if rec.Code != http.StatusOK { |
| + e.t.Fatalf("GET /metrics = %d", rec.Code) |
| + } |
| + return "\n" + rec.Body.String() |
| +} |
| + |
| +func TestRoutesMapErrorsToStatus(t *testing.T) { |
| + t.Parallel() |
| + for _, c := range []struct { |
| + err error |
| + want int |
| + }{ |
| + {isolatedjob.ErrInvalid, 400}, {hostedwire.ErrBadJSON, 400}, {ErrImageNotAllowed, 400}, |
| + {hostedwire.ErrBadSignature, 401}, {hostedwire.ErrSkew, 401}, {hostedwire.ErrReplay, 401}, {hostedwire.ErrUnknownKey, 401}, |
| + {ErrForbidden, 403}, {isolatedjob.ErrNotFound, 404}, |
| + {isolatedjob.ErrConflict, 409}, {ErrGenerationCancelled, 409}, {ErrNotQuiescent, 409}, {ErrResumePending, 409}, |
| + {ErrReplacementLive, 409}, {ErrStateUnknown, 409}, |
| + {ErrStopPending, 202}, {ErrPastDeadline, 410}, {hostedwire.ErrTooLarge, 413}, {isolatedjob.ErrThrottled, 429}, |
| + {ErrDisabled, 503}, {ErrNetworkAudit, 503}, {ErrStoreLost, 503}, {ErrProviderLaunch, 502}, |
| + {errors.New("anything else"), 500}, |
| + // A refusal whose audit row could not be written because the store |
| + // is gone reports the store. |
| + {errors.Join(ErrForbidden, fmt.Errorf("%w: gone", ErrStoreLost)), 503}, |
| + } { |
| + a := lookupError(fmt.Errorf("%w: secret detail", c.err)) |
| + if a.status != c.want || strings.Contains(a.msg, "secret") || a.msg == "" || a.code == "" { |
| + t.Errorf("lookupError(%v) = %+v, want status %d with a fixed message", c.err, a, c.want) |
| + } |
| + } |
| +} |
diff --git a/internal/hostedctl/metrics.go b/internal/hostedctl/metrics.go| new file mode 100644 |
| index 00000000..ad6442d4 |
| --- /dev/null |
| +++ b/internal/hostedctl/metrics.go |
| @@ -0,0 +1,230 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "fmt" |
| + "io" |
| + "maps" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// Metrics counts what the API and the alerter did since the process |
| +// started, and renders those counts with the controller's current state as |
| +// Prometheus text on a listener of its own. It is safe for concurrent use; |
| +// a nil *Metrics counts nothing. |
| +type Metrics struct { |
| + mu sync.Mutex |
| + launches map[string]uint64 // the launched job's state, or the refusal's code |
| + errs map[[2]string]uint64 // route, code |
| + alerts map[[2]string]uint64 // kind, "sent" or "failed" |
| +} |
| + |
| +// NewMetrics returns empty counts. |
| +func NewMetrics() *Metrics { |
| + return &Metrics{launches: map[string]uint64{}, errs: map[[2]string]uint64{}, alerts: map[[2]string]uint64{}} |
| +} |
| + |
| +func (m *Metrics) launch(result string) { |
| + if m == nil { |
| + return |
| + } |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.launches[result]++ |
| +} |
| + |
| +func (m *Metrics) apiError(route, code string) { |
| + if m == nil { |
| + return |
| + } |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.errs[[2]string{route, code}]++ |
| +} |
| + |
| +// CountAlerts wraps next so each alert it is given is counted by kind, as |
| +// sent or failed. |
| +func (m *Metrics) CountAlerts(next Alerter) Alerter { |
| + return countingAlerter{m: m, next: next} |
| +} |
| + |
| +type countingAlerter struct { |
| + m *Metrics |
| + next Alerter |
| +} |
| + |
| +func (a countingAlerter) Alert(ctx context.Context, al Alert) error { |
| + err := a.next.Alert(ctx, al) |
| + if a.m != nil { |
| + result := "sent" |
| + if err != nil { |
| + result = "failed" |
| + } |
| + a.m.mu.Lock() |
| + a.m.alerts[[2]string{al.Kind, result}]++ |
| + a.m.mu.Unlock() |
| + } |
| + return err |
| +} |
| + |
| +// knownStates are the job states always reported, as 0 when no job is in |
| +// them, once the store has been read. |
| +var knownStates = []string{JobWaiting, JobStarting, JobRunning, JobDraining, JobSuspending, JobSuspended, |
| + JobResuming, JobStopping, JobStopped, JobAbandoned} |
| + |
| +// Handler serves GET /metrics for c. A value the controller cannot read now |
| +// is left out rather than shown as zero: the job counts when the store read |
| +// fails, the audit status before any audit has run, and the reaper's results |
| +// before its first pass. |
| +func (m *Metrics) Handler(c *Controller) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/metrics" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if r.Method != http.MethodGet { |
| + w.WriteHeader(http.StatusMethodNotAllowed) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") |
| + m.write(r.Context(), w, c) |
| + }) |
| +} |
| + |
| +func (m *Metrics) write(ctx context.Context, w io.Writer, c *Controller) { |
| + p := promWriter{w: w} |
| + |
| + counts, err := c.jobsByState(ctx) |
| + p.head("equipo_hosted_store_readable", "gauge", "1 when the metrics read of the job table worked, else 0.") |
| + p.sample("equipo_hosted_store_readable", nil, boolValue(err == nil)) |
| + p.head("equipo_hosted_jobs", "gauge", "Jobs by state. Absent when the store could not be read.") |
| + if err == nil { |
| + states := slices.Clone(knownStates) |
| + for s := range counts { |
| + if !slices.Contains(states, s) { |
| + states = append(states, s) |
| + } |
| + } |
| + for _, s := range states { |
| + p.sample("equipo_hosted_jobs", []string{"state", s}, float64(counts[s])) |
| + } |
| + } |
| + |
| + now := c.store.Clock().Now() |
| + p.head("equipo_hosted_network_audit_passing", "gauge", "1 when the last network audit passed and is fresh enough for launches, else 0. Absent before the first audit.") |
| + if passing, ran := c.audit.status(now); ran { |
| + p.sample("equipo_hosted_network_audit_passing", nil, boolValue(passing)) |
| + } |
| + |
| + last, ran := c.LastReap() |
| + for _, g := range []struct { |
| + name, help string |
| + v float64 |
| + }{ |
| + {"equipo_hosted_reap_last_error", "1 when the last reaper pass returned an error, else 0.", boolValue(last.Err != nil)}, |
| + {"equipo_hosted_reap_last_orphans_stopped", "Orphan VMs the last reaper pass asked the provider to stop.", float64(last.Report.OrphansStopped)}, |
| + {"equipo_hosted_reap_last_orphans_deferred", "Orphan VMs past their grace the last reaper pass left running for a waiting intent.", float64(last.Report.OrphansDeferred)}, |
| + {"equipo_hosted_reap_last_age_seconds", "Controller time since the last reaper pass finished.", time.Duration(now - last.At).Seconds()}, |
| + } { |
| + p.head(g.name, "gauge", g.help+" Absent before the first pass.") |
| + if ran { |
| + p.sample(g.name, nil, g.v) |
| + } |
| + } |
| + |
| + m.mu.Lock() |
| + launches, errs, alerts := maps.Clone(m.launches), maps.Clone(m.errs), maps.Clone(m.alerts) |
| + m.mu.Unlock() |
| + p.head("equipo_hosted_launches_total", "counter", "Launch requests answered, by the job state returned or the refusal's code.") |
| + for _, k := range slices.Sorted(maps.Keys(launches)) { |
| + p.sample("equipo_hosted_launches_total", []string{"result", k}, float64(launches[k])) |
| + } |
| + p.head("equipo_hosted_errors_total", "counter", "API requests answered from the error table, by route and code (stop_pending, a 202, included). Route unverified is a request that failed its signature check.") |
| + for _, k := range slices.SortedFunc(maps.Keys(errs), comparePair) { |
| + p.sample("equipo_hosted_errors_total", []string{"route", k[0], "code", k[1]}, float64(errs[k])) |
| + } |
| + p.head("equipo_hosted_alerts_total", "counter", "Operator alerts by kind, sent or failed.") |
| + for _, k := range slices.SortedFunc(maps.Keys(alerts), comparePair) { |
| + p.sample("equipo_hosted_alerts_total", []string{"kind", k[0], "result", k[1]}, float64(alerts[k])) |
| + } |
| +} |
| + |
| +func comparePair(a, b [2]string) int { |
| + if c := strings.Compare(a[0], b[0]); c != 0 { |
| + return c |
| + } |
| + return strings.Compare(a[1], b[1]) |
| +} |
| + |
| +func boolValue(b bool) float64 { |
| + if b { |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| +// jobsByState counts the job table by state. |
| +func (c *Controller) jobsByState(ctx context.Context) (map[string]int64, error) { |
| + out := map[string]int64{} |
| + err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + rows, err := tx.QueryContext(ctx, `SELECT state, count(*) FROM jobs GROUP BY state`) |
| + if err != nil { |
| + return err |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var s string |
| + var n int64 |
| + if err := rows.Scan(&s, &n); err != nil { |
| + return err |
| + } |
| + out[s] = n |
| + } |
| + return rows.Err() |
| + }) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedctl: count jobs by state: %w", err) |
| + } |
| + return out, nil |
| +} |
| + |
| +// status reports whether the last audit passes the launch gate at now, and |
| +// whether any audit has run. |
| +func (s *auditState) status(now T) (passing, ran bool) { |
| + s.mu.Lock() |
| + ran = s.ran |
| + s.mu.Unlock() |
| + return s.check(now) == nil, ran |
| +} |
| + |
| +// promWriter writes the Prometheus text format. |
| +type promWriter struct{ w io.Writer } |
| + |
| +func (p promWriter) head(name, typ, help string) { |
| + fmt.Fprintf(p.w, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, typ) |
| +} |
| + |
| +// sample writes one line; labels alternate names and values. |
| +func (p promWriter) sample(name string, labels []string, v float64) { |
| + var b strings.Builder |
| + b.WriteString(name) |
| + if len(labels) > 0 { |
| + b.WriteByte('{') |
| + for i := 0; i+1 < len(labels); i += 2 { |
| + if i > 0 { |
| + b.WriteByte(',') |
| + } |
| + fmt.Fprintf(&b, "%s=\"%s\"", labels[i], labelEscaper.Replace(labels[i+1])) |
| + } |
| + b.WriteByte('}') |
| + } |
| + fmt.Fprintf(&b, " %v\n", v) |
| + _, _ = io.WriteString(p.w, b.String()) |
| +} |
| + |
| +var labelEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`) |