oficina / equipo Public

hosted: release artifacts and host configuration by digest

release-hosted.sh builds the hosts' binaries, the operator tools, the image
inputs and pinned Litestream, records each SHA-256 in hosted-VERSION.json
and SHA256SUMS, and publishes as publish-renderer.sh does (--dry-run only
here). Controller and proxy cloud-init templates install by digest, wait
15 minutes for private keys, fetch config and restore before start. The
controller gains keygen, first-boot TLS with a write-once SPKI pin,
operators.json at start, CloudWatch metrics and GET /healthz on the
metrics listener.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 23d82aff64ef12a9996ae8b402ff1605d8d08e02 parent 928918f
22 files changed, +2,747 −10
  • .rastrillo/budgets.txt +1 −1
  • Makefile +11 −0
  • cmd/equipo-hosted-controller/cloudinit_test.go +753 −0
  • cmd/equipo-hosted-controller/config.go +38 −3
  • cmd/equipo-hosted-controller/config_test.go +3 −0
  • cmd/equipo-hosted-controller/healthz_test.go +68 −0
  • cmd/equipo-hosted-controller/keygen.go +138 −0
  • cmd/equipo-hosted-controller/keygen_test.go +138 −0
  • cmd/equipo-hosted-controller/main.go +47 −5
  • cmd/equipo-hosted-controller/pin_test.go +152 −0
  • cmd/equipo-hosted-controller/tlspin.go +130 −0
  • cmd/equipo-hosted-controller/watch.go +175 −0
  • cmd/equipo-hosted-controller/watch_test.go +213 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +41 −0
  • go.mod +2 −1
  • go.sum +2 −0
  • infra/hosted/README.md +48 −0
  • infra/hosted/modules/controller/cloud-init.yaml.tmpl +281 −0
  • infra/hosted/modules/proxy/cloud-init.yaml.tmpl +211 −0
  • infra/hosted/release-pins.json +17 −0
  • internal/hostedctl/healthz.go +29 −0
  • scripts/release-hosted.sh +249 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 29bbc6a3..8712dedf 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -86,4 +86,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin,
# branch uses an indexed primary-key lookup, one current-member/device check,
# and the same bounded cardView as the snapshot; no list scan or new route.
perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
-size internal/hostedctl 6050 10017 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. Task 22 review 2: Admission answers the job's current deadline (DeadlineInMS, counted from the answer) so the instance caps hosted credentials by a deadline moved earlier after launch, and its assertion; measured 6050/10017.
+size internal/hostedctl 6079 10017 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. Task 22 review 2: Admission answers the job's current deadline (DeadlineInMS, counted from the answer) so the instance caps hosted credentials by a deadline moved earlier after launch, and its assertion; measured 6050/10017. Task 29: healthz.go, the metrics listener's GET /healthz (Controller.Healthz, a store read; the command mounts it beside /metrics and the API has no such route); wiring only, the CloudWatch publisher and Litestream lag live in the command; measured 6079/10017.
diff --git a/Makefile b/Makefile
index 8bd304d4..45a1ebd4 100644
--- a/Makefile
+++ b/Makefile
@@ -60,6 +60,17 @@ release-in-tree: release-runner
scripts/build-instance-release.sh $(RUNNER_RELEASE_DIR) $(RELEASE_BIN) $(RELEASE_GOOS) $(RELEASE_GOARCH) "$$(git rev-parse --short HEAD)"
@git rev-parse HEAD > $(RELEASE_BIN).COMMIT
+# release-hosted builds the hosted runner release (slice 2 Task 29):
+# the hosts' and the operator's binaries, the image inputs and pinned
+# Litestream, each SHA-256 in hosted-VERSION.json and SHA256SUMS, published
+# on the forge as hosted-VERSION. HOSTED_FLAGS passes --dry-run,
+# --runner-kit DIR or --image-inputs DIR; scripts/release-hosted.sh says
+# what each needs. For example:
+# make release-hosted HOSTED_VERSION=0.1.0 HOSTED_FLAGS='--dry-run --out /some/dir'
+.PHONY: release-hosted
+release-hosted:
+ scripts/release-hosted.sh $(HOSTED_FLAGS) $(HOSTED_VERSION)
+
# staged-check is the production gate: it refuses unless the artifacts
# are the ones this release's build recorded (its provenance manifest,
# written by make release) and releases/staged records a green staging
diff --git a/cmd/equipo-hosted-controller/cloudinit_test.go b/cmd/equipo-hosted-controller/cloudinit_test.go
new file mode 100644
index 00000000..169f71c8
--- /dev/null
+++ b/cmd/equipo-hosted-controller/cloudinit_test.go
@@ -0,0 +1,753 @@
+package main
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "gopkg.in/yaml.v3"
+)
+
+// The hosts' cloud-init templates (Task 29). OpenTofu renders them with
+// templatefile; the tests render them with renderTemplate, which accepts
+// only the subset they use, and run their boot scripts on this machine
+// under a scratch root, with aws, curl, systemctl and useradd replaced by
+// shims. Nothing here reaches the network or AWS.
+const (
+ controllerTemplate = "../../infra/hosted/modules/controller/cloud-init.yaml.tmpl"
+ proxyTemplate = "../../infra/hosted/modules/proxy/cloud-init.yaml.tmpl"
+ testReleaseURL = "https://amadan.net/oficina/equipo/-/releases/hosted-0.1.0"
+ testAccount = "149757027610"
+ testConfigBucket = "equipo-hosted-config-149757027610"
+ litestreamAsset = "litestream-0.5.18-linux-arm64.tar.gz"
+)
+
+var templateName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
+
+// maxUserData is EC2's limit on user data, in bytes before base64. The
+// tests' values are the size of real ones (keys, ARNs, a CA certificate).
+const maxUserData = 16384
+
+// userDataHeadroom is room for what a real deployment adds beyond the
+// tests' values (another verify key, longer ARNs).
+const userDataHeadroom = 2048
+
+// renderTemplate renders the template at path as templatefile does for
+// the subset the host templates keep to: ${name} for a variable of vars,
+// $${ for a literal ${ and %%{ for a literal %{. Any other interpolation,
+// a directive, an unknown variable or an unused one fails the test.
+func renderTemplate(t *testing.T, path string, vars map[string]string) string {
+ t.Helper()
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s, used := string(raw), map[string]bool{}
+ var b strings.Builder
+ for i := 0; i < len(s); {
+ switch {
+ case strings.HasPrefix(s[i:], "$${"):
+ b.WriteString("${")
+ i += 3
+ case strings.HasPrefix(s[i:], "%%{"):
+ b.WriteString("%{")
+ i += 3
+ case strings.HasPrefix(s[i:], "%{"):
+ t.Fatalf("%s: a template directive at byte %d; the host templates use none", path, i)
+ case strings.HasPrefix(s[i:], "${"):
+ end := strings.IndexByte(s[i:], '}')
+ if end < 0 {
+ t.Fatalf("%s: an unclosed ${ at byte %d", path, i)
+ }
+ name := s[i+2 : i+end]
+ v, ok := vars[name]
+ if !templateName.MatchString(name) || !ok {
+ t.Fatalf("%s: ${%s} is not a variable the test passes", path, name)
+ }
+ used[name] = true
+ b.WriteString(v)
+ i += end + 1
+ default:
+ b.WriteByte(s[i])
+ i++
+ }
+ }
+ for name := range vars {
+ if !used[name] {
+ t.Fatalf("%s does not use the variable %s", path, name)
+ }
+ }
+ return b.String()
+}
+
+type cloudFile struct {
+ Path string `yaml:"path"`
+ Content string `yaml:"content"`
+ Encoding string `yaml:"encoding"`
+ Permissions string `yaml:"permissions"`
+}
+
+type cloudConfig struct {
+ WriteFiles []cloudFile `yaml:"write_files"`
+ Runcmd [][]string `yaml:"runcmd"`
+}
+
+// parseCloudConfig checks the rendered text is a cloud-config document
+// and decodes it strictly.
+func parseCloudConfig(t *testing.T, text string) cloudConfig {
+ t.Helper()
+ if !strings.HasPrefix(text, "#cloud-config\n") {
+ t.Fatal("the rendered template does not start #cloud-config")
+ }
+ var cc cloudConfig
+ dec := yaml.NewDecoder(strings.NewReader(text))
+ dec.KnownFields(true)
+ if err := dec.Decode(&cc); err != nil {
+ t.Fatalf("the rendered template is not the cloud-config the test expects: %v", err)
+ }
+ return cc
+}
+
+func (cc cloudConfig) file(t *testing.T, path string) string {
+ t.Helper()
+ for _, f := range cc.WriteFiles {
+ if f.Path == path {
+ if f.Encoding == "b64" {
+ b, err := base64.StdEncoding.DecodeString(f.Content)
+ if err != nil {
+ t.Fatalf("%s: %v", path, err)
+ }
+ return string(b)
+ }
+ return f.Content
+ }
+ }
+ t.Fatalf("cloud-init writes no %s", path)
+ return ""
+}
+
+// host is one host's boot under a scratch root.
+type host struct {
+ t *testing.T
+ root, bucket, release, log string
+ env []string
+}
+
+// newHost writes cc's files under a fresh root, makes the shims, and
+// returns the host. Objects go in h.bucket/<bucket>/<key>; release assets
+// in h.release.
+func newHost(t *testing.T, cc cloudConfig) *host {
+ t.Helper()
+ for _, tool := range []string{"bash", "python3", "sha256sum", "tar", "install", "base64"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Skipf("the boot scripts need %s", tool)
+ }
+ }
+ base := t.TempDir()
+ h := &host{t: t, root: filepath.Join(base, "root"), bucket: filepath.Join(base, "bucket"),
+ release: filepath.Join(base, "release"), log: filepath.Join(base, "log")}
+ for _, d := range []string{h.root, h.bucket, h.release, h.log, filepath.Join(base, "bin")} {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, f := range cc.WriteFiles {
+ mode := os.FileMode(0o644)
+ if f.Permissions == "0755" {
+ mode = 0o755
+ }
+ content := cc.file(t, f.Path)
+ dest := filepath.Join(h.root, f.Path)
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(dest, []byte(content), mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for name, body := range shims {
+ if err := os.WriteFile(filepath.Join(base, "bin", name), []byte(body), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ u, err := user.Current()
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.env = []string{"PATH=" + filepath.Join(base, "bin") + ":/usr/local/bin:/usr/bin:/bin", "HOME=" + base, "LC_ALL=C",
+ "EQUIPO_HOSTED_ROOT=" + h.root, "EQUIPO_HOSTED_OWNER=" + u.Username, "EQUIPO_HOSTED_POLL_SECONDS=0",
+ "SHIM_BUCKET=" + h.bucket, "SHIM_RELEASE=" + h.release, "SHIM_RELEASE_URL=" + testReleaseURL,
+ "SHIM_ACCOUNT=" + testAccount, "SHIM_LOG=" + h.log}
+ return h
+}
+
+// put stores an object in the config bucket.
+func (h *host) put(key string, body []byte) {
+ h.t.Helper()
+ p := filepath.Join(h.bucket, testConfigBucket, key)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ h.t.Fatal(err)
+ }
+ if err := os.WriteFile(p, body, 0o600); err != nil {
+ h.t.Fatal(err)
+ }
+}
+
+// asset publishes a release asset and returns its SHA-256.
+func (h *host) asset(name string, body []byte) string {
+ h.t.Helper()
+ if err := os.WriteFile(filepath.Join(h.release, name), body, 0o644); err != nil {
+ h.t.Fatal(err)
+ }
+ sum := sha256.Sum256(body)
+ return hex.EncodeToString(sum[:])
+}
+
+// run runs the boot script at path (on the host) with extra environment,
+// and returns its combined output and whether it succeeded.
+func (h *host) run(path string, extra ...string) (string, bool) {
+ h.t.Helper()
+ cmd := exec.Command("bash", filepath.Join(h.root, path))
+ cmd.Env = append(slices.Clone(h.env), extra...)
+ out, err := cmd.CombinedOutput()
+ return string(out), err == nil
+}
+
+// systemctl returns every systemctl call the shim saw.
+func (h *host) systemctl() string {
+ b, _ := os.ReadFile(filepath.Join(h.log, "systemctl.log"))
+ return string(b)
+}
+
+func (h *host) exists(path string) bool {
+ _, err := os.Stat(filepath.Join(h.root, path))
+ return err == nil
+}
+
+// shims stand in for the host's tools. aws answers s3api get-object and
+// head-object from $SHIM_BUCKET, checking the expected owner; an object
+// with a <key>.after file holding n is refused n times first, as S3 refuses
+// a missing object to a reader that may not list. curl serves release
+// assets from $SHIM_RELEASE and IMDSv2's private address.
+var shims = map[string]string{
+ "aws": `#!/bin/bash
+echo "$*" >>"$SHIM_LOG/aws.log"
+[[ $1 == s3api ]] || exit 2
+op=$2; shift 2; out=
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --bucket) b=$2; shift 2 ;;
+ --key) k=$2; shift 2 ;;
+ --expected-bucket-owner) o=$2; shift 2 ;;
+ --*) echo "aws shim: unknown flag $1" >&2; exit 2 ;;
+ *) out=$1; shift ;;
+ esac
+done
+[[ $o == "$SHIM_ACCOUNT" ]] || { echo "An error occurred (AccessDenied): wrong owner" >&2; exit 254; }
+f=$SHIM_BUCKET/$b/$k
+if [[ -f $f.after ]]; then
+ n=$(cat "$f.after")
+ if ((n > 0)); then echo $((n - 1)) >"$f.after"; echo "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied" >&2; exit 254; fi
+fi
+[[ -f $f.unreachable ]] && { echo "Could not connect to the endpoint URL" >&2; exit 255; }
+[[ -f $f ]] || { echo "An error occurred (NoSuchKey) when calling the GetObject operation: The specified key does not exist." >&2; exit 254; }
+case $op in
+get-object) cp "$f" "$out" && echo '{}' ;;
+head-object) echo '{}' ;;
+*) exit 2 ;;
+esac
+`,
+ "curl": `#!/bin/bash
+echo "$*" >>"$SHIM_LOG/curl.log"
+out= url=
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --output | -o) out=$2; shift 2 ;;
+ --header | -H | --request | -X | --max-time | --retry | --max-redirs | --proto | --proto-redir | --connect-timeout) shift 2 ;;
+ http://* | https://*) url=$1; shift ;;
+ *) shift ;;
+ esac
+done
+case $url in
+http://169.254.169.254/latest/api/token) printf token ;;
+http://169.254.169.254/latest/meta-data/local-ipv4) printf 10.42.0.25 ;;
+"$SHIM_RELEASE_URL"/*)
+ f=$SHIM_RELEASE/${url##*/}
+ [[ -f $f ]] || { echo "curl: (22) The requested URL returned error: 404" >&2; exit 22; }
+ cp "$f" "$out" ;;
+*) echo "curl shim: no such URL $url" >&2; exit 6 ;;
+esac
+`,
+ "systemctl": "#!/bin/bash\necho \"$*\" >>\"$SHIM_LOG/systemctl.log\"\n",
+ "useradd": "#!/bin/bash\necho \"$*\" >>\"$SHIM_LOG/useradd.log\"\n",
+}
+
+// tarball is a gzipped tar holding one file.
+func tarball(t *testing.T, name string, body []byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// controllerHost renders the controller template with its release assets
+// published (mutate, when set, edits them after their digests are taken)
+// and the private keys in the bucket, and returns the host.
+func controllerHost(t *testing.T, mutate func(controller, litestream []byte) ([]byte, []byte)) (*host, cloudConfig) {
+ t.Helper()
+ keys := t.TempDir()
+ var out bytes.Buffer
+ for _, k := range [][]string{{"-ed25519", "controller"}, {"-ca", "client-ca"}} {
+ if err := keygen([]string{k[0], "-out", filepath.Join(keys, k[1])}, &out, &out); err != nil {
+ t.Fatal(err)
+ }
+ }
+ caCert, err := os.ReadFile(filepath.Join(keys, "client-ca.pub"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctlBin := []byte("#!/bin/sh\necho controller \"$EQUIPO_HOSTED_ENABLED\" \"$@\"\n")
+ lsTar := tarball(t, "litestream", []byte("#!/bin/sh\necho litestream\n"))
+ ctlSum, lsSum := sha256.Sum256(ctlBin), sha256.Sum256(lsTar)
+ vars := map[string]string{
+ "release_url": testReleaseURL, "controller_sha256": hex.EncodeToString(ctlSum[:]),
+ "litestream_asset": litestreamAsset, "litestream_sha256": hex.EncodeToString(lsSum[:]),
+ "account_id": testAccount, "region": "eu-west-1", "config_bucket": testConfigBucket,
+ "litestream_bucket": "equipo-hosted-litestream-149757027610",
+ "verify_keys_json": `[{"id":"inst-1","role":"instance","public_key":"` + pubB64(1) + `"},{"id":"proxy-a","role":"proxy","public_key":"` + pubB64(3) + `"}]`,
+ "images_json": `[{"digest":"` + testDigest + `","arn":"` + testImageARN + `","versions":{"small":"1","large":"2"}}]`,
+ "vpc_id": "vpc-1", "vm_subnet_id": "subnet-1", "vm_security_group_id": "sg-1",
+ "connector_arn": "arn:aws:lambda:eu-west-1:149757027610:network-connector:egress:1",
+ "egress_json": `["10.42.1.10:8443","10.42.1.10:8444"]`,
+ "sns_topic_arn": "arn:aws:sns:eu-west-1:149757027610:equipo-hosted-alerts",
+ "peering_id": "pcx-1", "services_vpc_id": "vpc-svc", "services_route_table_id": "rtb-svc",
+ "proxy_routes_json": `["10.42.1.10/32"]`,
+ "egress_manifest_b64": base64.StdEncoding.EncodeToString(manifestBody("equipo.example.com")),
+ "client_ca_cert_b64": base64.StdEncoding.EncodeToString(caCert),
+ }
+ text := renderTemplate(t, controllerTemplate, vars)
+ if len(text) > maxUserData-userDataHeadroom {
+ t.Fatalf("the controller's user data is %d bytes; EC2 takes at most %d, and real deployments need %d more", len(text), maxUserData, userDataHeadroom)
+ }
+ cc := parseCloudConfig(t, text)
+ h := newHost(t, cc)
+ if mutate != nil {
+ ctlBin, lsTar = mutate(ctlBin, lsTar)
+ }
+ h.asset("equipo-hosted-controller-linux-arm64", ctlBin)
+ h.asset(litestreamAsset, lsTar)
+ for _, name := range []string{"controller.key", "client-ca.key"} {
+ b, err := os.ReadFile(filepath.Join(keys, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.put("controller/"+name, b)
+ }
+ h.put("controller/operators.json", []byte(`{"operators":[{"id":"op-run1","public_key":"`+pubB64(2)+`"}]}`))
+ h.put("controller/cert-keys.json", ctlcerttest.KeysJSON())
+ return h, cc
+}
+
+// TestCloudInitChecksDigest: each host's first boot downloads its binaries
+// from the release by URL and installs them only when their SHA-256 is the
+// one pinned in its user data; a mismatch, or private keys still absent
+// from the config bucket after the wait, leaves every unit off. The wait
+// is 15 minutes on a host, and cloud-init's only command is the install.
+func TestCloudInitChecksDigest(t *testing.T) {
+ t.Parallel()
+ const ctlUnits = "enable --now equipo-hosted-controller.service equipo-hosted-litestream.service"
+
+ h, cc := controllerHost(t, nil)
+ if !slices.EqualFunc(cc.Runcmd, [][]string{{"/usr/local/libexec/equipo-hosted/install.sh"}}, slices.Equal) {
+ t.Fatalf("runcmd = %v, want the install script alone", cc.Runcmd)
+ }
+ lib := cc.file(t, "/usr/local/libexec/equipo-hosted/lib.sh")
+ if !strings.Contains(lib, "WAIT_SECONDS=${EQUIPO_HOSTED_WAIT_SECONDS:-900}") {
+ t.Fatal("lib.sh does not wait 900 s (15 minutes) by default")
+ }
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/install.sh"); !ok {
+ t.Fatalf("install with good digests failed:\n%s", out)
+ }
+ if got, _ := os.ReadFile(filepath.Join(h.root, "usr/local/bin/equipo-hosted-controller")); !strings.HasPrefix(string(got), "#!/bin/sh\necho controller") {
+ t.Fatal("the controller binary was not installed")
+ }
+ if !h.exists("usr/local/bin/litestream") {
+ t.Fatal("litestream was not installed")
+ }
+ if !strings.Contains(h.systemctl(), ctlUnits) {
+ t.Fatalf("the units were not enabled: %q", h.systemctl())
+ }
+ if conf := readRoot(t, h, "etc/equipo-hosted/controller.json"); !strings.Contains(conf, `"listen": "10.42.0.25:443"`) {
+ t.Fatalf("controller.json does not listen on the host's private address:\n%s", conf)
+ }
+
+ for name, mutate := range map[string]func(c, l []byte) ([]byte, []byte){
+ "controller": func(c, l []byte) ([]byte, []byte) { return append(c, '#'), l },
+ "litestream": func(c, l []byte) ([]byte, []byte) { return c, tarball(t, "litestream", []byte("evil")) },
+ } {
+ h, _ := controllerHost(t, mutate)
+ out, ok := h.run("usr/local/libexec/equipo-hosted/install.sh")
+ if ok || !strings.Contains(out, "SHA-256") {
+ t.Fatalf("%s mismatch: install succeeded or said nothing of the digest:\n%s", name, out)
+ }
+ if h.systemctl() != "" || h.exists("usr/local/bin/equipo-hosted-controller") || h.exists("usr/local/bin/litestream") {
+ t.Fatalf("%s mismatch: something was installed or enabled (systemctl %q)", name, h.systemctl())
+ }
+ }
+
+ h, _ = controllerHost(t, nil)
+ if err := os.Remove(filepath.Join(h.bucket, testConfigBucket, "controller/client-ca.key")); err != nil {
+ t.Fatal(err)
+ }
+ out, ok := h.run("usr/local/libexec/equipo-hosted/install.sh", "EQUIPO_HOSTED_WAIT_SECONDS=1")
+ if ok || !strings.Contains(out, "controller/client-ca.key") {
+ t.Fatalf("install with a private key absent succeeded or did not name it:\n%s", out)
+ }
+ if h.systemctl() != "" {
+ t.Fatalf("a unit was enabled with a private key absent: %q", h.systemctl())
+ }
+
+ // The proxy: the same rule for its binary and its two private keys.
+ p, pcc := proxyHost(t, false)
+ if !slices.EqualFunc(pcc.Runcmd, [][]string{{"/usr/local/libexec/equipo-hosted/install.sh"}}, slices.Equal) {
+ t.Fatalf("proxy runcmd = %v, want the install script alone", pcc.Runcmd)
+ }
+ if pcc.file(t, "/usr/local/libexec/equipo-hosted/lib.sh") != lib {
+ t.Fatal("the proxy's lib.sh differs from the controller's")
+ }
+ if out, ok := p.run("usr/local/libexec/equipo-hosted/install.sh"); !ok || !strings.Contains(p.systemctl(), "enable --now equipo-hosted-proxy.service") {
+ t.Fatalf("proxy install failed or enabled nothing (%q):\n%s", p.systemctl(), out)
+ }
+ p, _ = proxyHost(t, true)
+ if out, ok := p.run("usr/local/libexec/equipo-hosted/install.sh"); ok || p.systemctl() != "" || p.exists("usr/local/bin/equipo-hosted-proxy") {
+ t.Fatalf("proxy install with a wrong digest succeeded or installed something:\n%s", out)
+ }
+ p, _ = proxyHost(t, false)
+ if err := os.Remove(filepath.Join(p.bucket, testConfigBucket, "proxy/a/intercept.key")); err != nil {
+ t.Fatal(err)
+ }
+ if out, ok := p.run("usr/local/libexec/equipo-hosted/install.sh", "EQUIPO_HOSTED_WAIT_SECONDS=1"); ok || p.systemctl() != "" {
+ t.Fatalf("proxy install with its intercept key absent succeeded or enabled the unit:\n%s", out)
+ }
+}
+
+func readRoot(t *testing.T, h *host, path string) string {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(h.root, path))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+// unit returns the values of key in a systemd unit, in order.
+func unitValues(unit, key string) []string {
+ var out []string
+ for _, line := range strings.Split(unit, "\n") {
+ if v, ok := strings.CutPrefix(line, key+"="); ok {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+// TestRestoreBeforeStart: the controller unit fetches its config, then runs
+// litestream restore (only when there is a replica and no local database)
+// on the database the controller opens, and only then starts the
+// controller; it restarts always, so POST /v1/admin/restart's exit 0 starts
+// it again through both steps. Litestream replicates as a unit of its own,
+// started after the controller, to the Litestream bucket.
+func TestRestoreBeforeStart(t *testing.T) {
+ t.Parallel()
+ _, cc := controllerHost(t, nil)
+ unit := cc.file(t, "/etc/systemd/system/equipo-hosted-controller.service")
+ pre := unitValues(unit, "ExecStartPre")
+ conf := cc.file(t, "/etc/equipo-hosted/controller.json.in")
+ var fc map[string]any
+ if err := json.Unmarshal([]byte(conf), &fc); err != nil {
+ t.Fatalf("controller.json.in: %v", err)
+ }
+ db, _ := fc["database"].(string)
+ if len(pre) != 2 || pre[0] != "+/usr/local/libexec/equipo-hosted/fetch-config.sh" {
+ t.Fatalf("ExecStartPre = %q, want the config fetch (as root) and then the restore", pre)
+ }
+ restore := strings.Fields(pre[1])
+ if restore[0] != "/usr/local/bin/litestream" || restore[1] != "restore" || !slices.Contains(restore, "-if-replica-exists") ||
+ !slices.Contains(restore, "-if-db-not-exists") || restore[len(restore)-1] != db || db == "" {
+ t.Fatalf("the second ExecStartPre is %q; want litestream restore -if-replica-exists -if-db-not-exists of %q", pre[1], db)
+ }
+ if got := unitValues(unit, "ExecStart"); len(got) != 1 || got[0] != "/usr/local/libexec/equipo-hosted/start-controller.sh" {
+ t.Fatalf("ExecStart = %q", got)
+ }
+ if got := unitValues(unit, "Restart"); len(got) != 1 || got[0] != "always" {
+ t.Fatalf("Restart = %q, want always", got)
+ }
+ start := cc.file(t, "/usr/local/libexec/equipo-hosted/start-controller.sh")
+ if !strings.Contains(start, `exec "$BIN/equipo-hosted-controller" -config "$ETC/controller.json"`) {
+ t.Fatalf("start-controller.sh does not exec the controller on controller.json:\n%s", start)
+ }
+
+ ls := cc.file(t, "/etc/systemd/system/equipo-hosted-litestream.service")
+ if got := unitValues(ls, "After"); !slices.Contains(got, "equipo-hosted-controller.service") {
+ t.Fatalf("litestream unit After = %q, want after the controller", got)
+ }
+ if got := unitValues(ls, "ExecStart"); len(got) != 1 || !strings.HasPrefix(got[0], "/usr/local/bin/litestream replicate -config /etc/equipo-hosted/litestream.yml") {
+ t.Fatalf("litestream ExecStart = %q", got)
+ }
+ var lc struct {
+ HeartbeatURL string `yaml:"heartbeat-url"`
+ HeartbeatInterval string `yaml:"heartbeat-interval"`
+ DBs []struct {
+ Path string `yaml:"path"`
+ Replica struct {
+ Type, Bucket, Path, Region string
+ } `yaml:"replica"`
+ } `yaml:"dbs"`
+ }
+ dec := yaml.NewDecoder(strings.NewReader(cc.file(t, "/etc/equipo-hosted/litestream.yml")))
+ dec.KnownFields(true)
+ if err := dec.Decode(&lc); err != nil {
+ t.Fatalf("litestream.yml: %v", err)
+ }
+ if len(lc.DBs) != 1 || lc.DBs[0].Path != db || lc.DBs[0].Replica.Type != "s3" ||
+ lc.DBs[0].Replica.Bucket != "equipo-hosted-litestream-149757027610" || lc.DBs[0].Replica.Region != "eu-west-1" {
+ t.Fatalf("litestream.yml replicates %+v; want the controller database to the Litestream bucket", lc.DBs)
+ }
+ metrics, _ := fc["metrics_listen"].(string)
+ if lc.HeartbeatURL != "http://"+metrics+"/litestream/heartbeat" || lc.HeartbeatInterval != "1m" {
+ t.Fatalf("litestream heartbeat %q every %q; want the metrics listener's /litestream/heartbeat every minute", lc.HeartbeatURL, lc.HeartbeatInterval)
+ }
+}
+
+// TestControllerReadsManifest: the controller loads the config its user
+// data writes, with the deployment's egress manifest and the files its
+// ExecStartPre fetched from the config bucket: the signing key, the client
+// CA key, the operator keys (as operator verify keys), the certificate keys;
+// absent optional objects become their closed defaults (no certificates, no
+// certification images, launches off); and the env object switches
+// launches on and may hold nothing else.
+func TestControllerReadsManifest(t *testing.T) {
+ t.Parallel()
+ h, _ := controllerHost(t, nil)
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/install.sh"); !ok {
+ t.Fatalf("install:\n%s", out)
+ }
+ h.put("controller/env", []byte("EQUIPO_HOSTED_ENABLED=1\n"))
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-config.sh"); !ok {
+ t.Fatalf("fetch-config:\n%s", out)
+ }
+ for _, name := range []string{"controller.key", "client-ca.key", "operators.json", "cert-keys.json", "certificates.json",
+ "certification-images.json", "env", "proxy-code.key"} {
+ info, err := os.Stat(filepath.Join(h.root, "var/lib/equipo-hosted/config", name))
+ if err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("config/%s: %v, mode %v; want it fetched at 0600", name, err, info)
+ }
+ }
+ // start-controller.sh passes the env object's switch, and nothing else.
+ out, ok := h.run("usr/local/libexec/equipo-hosted/start-controller.sh")
+ if !ok || strings.TrimSpace(out) != "controller 1 -config "+filepath.Join(h.root, "etc/equipo-hosted/controller.json") {
+ t.Fatalf("start-controller.sh ran %q", out)
+ }
+
+ // The config, with the host's paths moved under the scratch root.
+ conf := readRoot(t, h, "etc/equipo-hosted/controller.json")
+ for _, dir := range []string{"/etc/equipo-hosted/", "/var/lib/equipo-hosted/"} {
+ conf = strings.ReplaceAll(conf, `"`+dir, `"`+filepath.Join(h.root, dir)+"/")
+ }
+ path := filepath.Join(t.TempDir(), "controller.json")
+ if err := os.WriteFile(path, []byte(conf), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ c, err := loadConfig(path, func(k string) string { return map[string]string{enabledEnv: "1"}[k] })
+ if err != nil {
+ t.Fatalf("the controller refuses the config its user data and ExecStartPre wrote: %v", err)
+ }
+ if got, err := c.ctl.Manifest.For(hostedwire.PurposeChecks); err != nil || len(got) != 1 || got[0].Host != "equipo.example.com" {
+ t.Fatalf("manifest services = %+v, %v; want the deployment's", got, err)
+ }
+ if k, ok := c.keys["op-run1"]; !ok || k.Role != hostedwire.RoleOperator {
+ t.Fatalf("operators.json's key is not an operator verify key: %+v", c.keys)
+ }
+ if k, ok := c.keys["proxy-a"]; !ok || k.Role != hostedwire.RoleProxy {
+ t.Fatalf("the deployment's proxy key is missing: %+v", c.keys)
+ }
+ if c.ctl.ProxyCA == nil || len(c.ctl.ProxyCodeKey) != 32 || c.bucket != testConfigBucket || c.prefix != "controller/" {
+ t.Fatalf("proxy CA %v, code key %d bytes, bucket %q, prefix %q", c.ctl.ProxyCA != nil, len(c.ctl.ProxyCodeKey), c.bucket, c.prefix)
+ }
+ if c.ctl.Candidates.Allows(testDigest, "large") == nil {
+ t.Fatal("an absent certification-images.json allowed a candidate")
+ }
+
+ // A second start keeps the proxy code key.
+ before := readRoot(t, h, "var/lib/equipo-hosted/config/proxy-code.key")
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-config.sh"); !ok || readRoot(t, h, "var/lib/equipo-hosted/config/proxy-code.key") != before {
+ t.Fatalf("a second fetch failed or replaced the proxy code key:\n%s", out)
+ }
+
+ // env may switch launches and do nothing else.
+ h.put("controller/env", []byte("EQUIPO_HOSTED_ENABLED=1\nLD_PRELOAD=/tmp/x.so\n"))
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-config.sh"); ok {
+ t.Fatalf("fetch-config took an env object with LD_PRELOAD:\n%s", out)
+ }
+ // An optional object the bucket cannot be reached for is not defaulted.
+ h.put("controller/env", []byte("EQUIPO_HOSTED_ENABLED=1\n"))
+ h.put("controller/certificates.json.unreachable", nil)
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-config.sh"); ok {
+ t.Fatalf("fetch-config defaulted an object it could not reach:\n%s", out)
+ }
+ // A required object absent: the start fails.
+ if err := os.Remove(filepath.Join(h.bucket, testConfigBucket, "controller/certificates.json.unreachable")); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(filepath.Join(h.bucket, testConfigBucket, "controller/operators.json")); err != nil {
+ t.Fatal(err)
+ }
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-config.sh"); ok {
+ t.Fatalf("fetch-config started with operators.json absent:\n%s", out)
+ }
+}
+
+// proxyHost renders the proxy template for proxy a with its release
+// binary (with a digest that does not match when wrongDigest) and its two
+// private keys in the bucket.
+func proxyHost(t *testing.T, wrongDigest bool) (*host, cloudConfig) {
+ t.Helper()
+ keys := t.TempDir()
+ var out bytes.Buffer
+ for _, k := range [][]string{{"-ed25519", "proxy-a"}, {"-ca", "intercept-ca"}, {"-ca", "client-ca"}} {
+ if err := keygen([]string{k[0], "-out", filepath.Join(keys, k[1])}, &out, &out); err != nil {
+ t.Fatal(err)
+ }
+ }
+ read := func(name string) []byte {
+ b, err := os.ReadFile(filepath.Join(keys, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ bin := []byte("#!/bin/sh\necho proxy \"$@\"\n")
+ sum := sha256.Sum256(bin)
+ vars := map[string]string{
+ "release_url": testReleaseURL, "proxy_sha256": hex.EncodeToString(sum[:]),
+ "account_id": testAccount, "region": "eu-west-1", "config_bucket": testConfigBucket,
+ "proxy_name": "a", "proxy_ip": "10.42.1.10", "proxy_key_id": "proxy-a",
+ "client_ca_cert_b64": base64.StdEncoding.EncodeToString(read("client-ca.pub")),
+ "intercept_ca_cert_b64": base64.StdEncoding.EncodeToString(read("intercept-ca.pub")),
+ }
+ text := renderTemplate(t, proxyTemplate, vars)
+ if len(text) > maxUserData-userDataHeadroom {
+ t.Fatalf("the proxy's user data is %d bytes; EC2 takes at most %d, and real deployments need %d more", len(text), maxUserData, userDataHeadroom)
+ }
+ cc := parseCloudConfig(t, text)
+ h := newHost(t, cc)
+ if wrongDigest {
+ bin = append(bin, '#')
+ }
+ h.asset("equipo-hosted-proxy-linux-arm64", bin)
+ h.put("proxy/a/proxy.key", read("proxy-a.key"))
+ h.put("proxy/a/intercept.key", read("intercept-ca.key"))
+ return h, cc
+}
+
+// TestCloudInitProxyWaitsForControllerJSON: the proxy's ExecStartPre
+// fetches its keys, waits for proxy/<name>/controller.json (S3 refuses it,
+// as it refuses a missing object to a reader that may not list, until the
+// controller's pin is placed), checks it, and writes the proxy's config from
+// it; past the wait, or with a malformed controller.json, the start fails
+// and writes nothing. The unit allows the wait.
+func TestCloudInitProxyWaitsForControllerJSON(t *testing.T) {
+ t.Parallel()
+ h, cc := proxyHost(t, false)
+ unit := cc.file(t, "/etc/systemd/system/equipo-hosted-proxy.service")
+ if pre := unitValues(unit, "ExecStartPre"); len(pre) != 1 || pre[0] != "+/usr/local/libexec/equipo-hosted/fetch-proxy.sh" {
+ t.Fatalf("proxy ExecStartPre = %q", pre)
+ }
+ if got := unitValues(unit, "ExecStart"); len(got) != 1 || got[0] != "/usr/local/bin/equipo-hosted-proxy -config /var/lib/equipo-hosted/config/proxy.json" {
+ t.Fatalf("proxy ExecStart = %q", got)
+ }
+ if got := unitValues(unit, "TimeoutStartSec"); len(got) != 1 || got[0] != "20min" {
+ t.Fatalf("proxy TimeoutStartSec = %q, want 20min (the 15-minute wait and the fetches)", got)
+ }
+
+ pin := strings.Repeat("ab", 32)
+ cj := `{"url":"https://203.0.113.7","pin":"` + pin + `","key":"` + pubB64(4) + `"}`
+ h.put("proxy/a/controller.json", []byte(cj))
+ h.put("proxy/a/controller.json.after", []byte("3"))
+ out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-proxy.sh", "EQUIPO_HOSTED_WAIT_SECONDS=30")
+ if !ok {
+ t.Fatalf("fetch-proxy did not wait for controller.json:\n%s", out)
+ }
+ var pc map[string]string
+ if err := json.Unmarshal([]byte(readRoot(t, h, "var/lib/equipo-hosted/config/proxy.json")), &pc); err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]string{
+ "egress_listen": "10.42.1.10:8443", "boot_listen": "10.42.1.10:8444",
+ "controller_url": "https://203.0.113.7", "controller_tls_pin": pin, "controller_public_key": pubB64(4),
+ "key_id": "proxy-a", "signing_key_file": "/var/lib/equipo-hosted/config/proxy.key",
+ "client_ca_file": "/etc/equipo-hosted/client-ca.crt", "intercept_ca_cert_file": "/etc/equipo-hosted/intercept-ca.crt",
+ "intercept_ca_key_file": "/var/lib/equipo-hosted/config/intercept.key",
+ }
+ if len(pc) != len(want) {
+ t.Fatalf("proxy.json = %v, want %v", pc, want)
+ }
+ for k, v := range want {
+ if pc[k] != v {
+ t.Fatalf("proxy.json %s = %q, want %q", k, pc[k], v)
+ }
+ }
+ for _, name := range []string{"proxy.key", "intercept.key"} {
+ if info, err := os.Stat(filepath.Join(h.root, "var/lib/equipo-hosted/config", name)); err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("%s: %v %v, want 0600", name, err, info)
+ }
+ }
+
+ // Never placed: the wait ends and the start fails, writing nothing.
+ h, _ = proxyHost(t, false)
+ out, ok = h.run("usr/local/libexec/equipo-hosted/fetch-proxy.sh", "EQUIPO_HOSTED_WAIT_SECONDS=1")
+ if ok || !strings.Contains(out, "controller.json") || h.exists("var/lib/equipo-hosted/config/proxy.json") {
+ t.Fatalf("fetch-proxy with no controller.json succeeded or wrote a config:\n%s", out)
+ }
+
+ for name, body := range map[string]string{
+ "a pin that is not hex": `{"url":"https://203.0.113.7","pin":"` + strings.Repeat("zz", 32) + `","key":"` + pubB64(4) + `"}`,
+ "plain http": `{"url":"http://203.0.113.7","pin":"` + pin + `","key":"` + pubB64(4) + `"}`,
+ "a short key": `{"url":"https://203.0.113.7","pin":"` + pin + `","key":"AAAA"}`,
+ "an extra field": `{"url":"https://203.0.113.7","pin":"` + pin + `","key":"` + pubB64(4) + `","extra":1}`,
+ } {
+ h, _ := proxyHost(t, false)
+ h.put("proxy/a/controller.json", []byte(body))
+ if out, ok := h.run("usr/local/libexec/equipo-hosted/fetch-proxy.sh", "EQUIPO_HOSTED_WAIT_SECONDS=1"); ok ||
+ h.exists("var/lib/equipo-hosted/config/proxy.json") {
+ t.Fatalf("fetch-proxy took controller.json with %s:\n%s", name, out)
+ }
+ }
+}
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index f439e098..dfcdb83a 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -93,8 +93,11 @@ type fileConfig struct {
// two certificate files; a file that does not check stops the
// controller starting, or fails the reload and keeps the old sets.
CertificationImagesFile string `json:"certification_images_file"`
- // OperatorsFile is the local copy of the operator keys object, which a
- // reload fetches and writes for the next start.
+ // OperatorsFile is the local copy of the operator keys object
+ // (controller/operators.json, which ExecStartPre fetches and a reload
+ // writes for the next start): {"operators": [{"id", "public_key"}]},
+ // each key added to verify_keys with the operator role. Start reads it;
+ // a reload does not change the API's keys.
OperatorsFile string `json:"operators_file"`
// ConfigBucket and ConfigPrefix (ending in "/", for example
// "controller/") name where POST /v1/admin/reload fetches
@@ -195,7 +198,11 @@ func (fc fileConfig) check() (config, error) {
if c.signing, err = readSigningKey(fc.SigningKeyFile); err != nil {
return config{}, err
}
- if c.keys, err = verifyKeys(fc.VerifyKeys); err != nil {
+ operators, err := readOperators(fc.OperatorsFile)
+ if err != nil {
+ return config{}, err
+ }
+ if c.keys, err = verifyKeys(append(slices.Clone(fc.VerifyKeys), operators...)); err != nil {
return config{}, err
}
if c.aws, err = fc.awsConfig(); err != nil {
@@ -349,6 +356,34 @@ func readSigningKey(path string) (ed25519.PrivateKey, error) {
return ed25519.NewKeyFromSeed(seed), nil
}
+// operatorsFile is the operator keys object.
+type operatorsFile struct {
+ Operators []struct {
+ ID string `json:"id"`
+ PublicKey string `json:"public_key"`
+ } `json:"operators"`
+}
+
+// readOperators reads the operator keys at path as verify key entries with
+// the operator role. Rotating the operator key (account plan 9.3) is a new
+// object and a restart; no existing operator key is needed.
+func readOperators(path string) ([]keyEntry, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("operator keys: %w", err)
+ }
+ defer f.Close()
+ var of operatorsFile
+ if err := hostedwire.DecodeStrict(f, &of); err != nil {
+ return nil, fmt.Errorf("operator keys %s: %w", path, err)
+ }
+ out := make([]keyEntry, 0, len(of.Operators))
+ for _, o := range of.Operators {
+ out = append(out, keyEntry{ID: o.ID, Role: string(hostedwire.RoleOperator), PublicKey: o.PublicKey})
+ }
+ return out, 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) {
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index a34ad9df..be1e60e4 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -64,6 +64,9 @@ func validConfig(t *testing.T, dir string) fileConfig {
if err := os.WriteFile(caKeyPath, caKey, 0o600); err != nil {
t.Fatal(err)
}
+ if err := os.WriteFile(filepath.Join(dir, "operators.json"), []byte(`{"operators":[]}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
codeKeyPath := filepath.Join(dir, "proxy-code.key")
if err := os.WriteFile(codeKeyPath, []byte(base64.StdEncoding.EncodeToString(ctlproxytest.CodeKey())+"\n"), 0o600); err != nil {
t.Fatal(err)
diff --git a/cmd/equipo-hosted-controller/healthz_test.go b/cmd/equipo-hosted-controller/healthz_test.go
new file mode 100644
index 00000000..c0f81161
--- /dev/null
+++ b/cmd/equipo-hosted-controller/healthz_test.go
@@ -0,0 +1,68 @@
+package main
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+)
+
+// TestHealthzOnMetricsOnly: GET /healthz answers on the metrics listener,
+// as the controller wires it (metricsMux), and not on the API listener,
+// where an unsigned request is refused like any other. It answers 503 once
+// the store no longer answers a read.
+func TestHealthzOnMetricsOnly(t *testing.T) {
+ t.Parallel()
+ tc := newTestCtl(t, nil)
+ cert, client := testTLS(t)
+ apiLn, metricsLn := listen(t), listen(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ served := make(chan error, 1)
+ go func() {
+ served <- serve(ctx, tc.c, newAPIServer(tc.api, cert), apiLn,
+ newMetricsServer(metricsMux(hostedctl.NewMetrics(), tc.c, newLitestreamLag(time.Now))), metricsLn, 10*time.Second)
+ }()
+ get := func(c *http.Client, url string) (int, string) {
+ t.Helper()
+ resp, err := c.Get(url)
+ if err != nil {
+ t.Fatalf("GET %s: %v", url, err)
+ }
+ return resp.StatusCode, string(readAll(t, resp))
+ }
+
+ if code, body := get(http.DefaultClient, "http://"+metricsLn.Addr().String()+"/healthz"); code != http.StatusOK || body != "ok\n" {
+ t.Fatalf("metrics /healthz = %d %q, want 200 ok", code, body)
+ }
+ if code, _ := get(client, "https://"+apiLn.Addr().String()+"/healthz"); code == http.StatusOK {
+ t.Fatal("the API listener answered /healthz unsigned")
+ }
+ req, err := http.NewRequest(http.MethodPost, "http://"+metricsLn.Addr().String()+"/healthz", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if readAll(t, resp); resp.StatusCode != http.StatusMethodNotAllowed {
+ t.Fatalf("POST /healthz = %d, want 405", resp.StatusCode)
+ }
+
+ cancel()
+ if err := <-served; err != nil {
+ t.Fatalf("serve: %v", err)
+ }
+ // After shutdown the store closes; the handler then reports it.
+ if err := tc.store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ rec := httptest.NewRecorder()
+ metricsMux(hostedctl.NewMetrics(), tc.c, newLitestreamLag(time.Now)).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("/healthz on a closed store = %d, want 503", rec.Code)
+ }
+}
diff --git a/cmd/equipo-hosted-controller/keygen.go b/cmd/equipo-hosted-controller/keygen.go
new file mode 100644
index 00000000..3ef25369
--- /dev/null
+++ b/cmd/equipo-hosted-controller/keygen.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/base64"
+ "encoding/pem"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "math/big"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// caLifetime is how long a CA keygen -ca makes is valid. Its certificate is
+// pinned by SPKI or trusted as the one CA, and replacing it means new keys
+// for every host, so it outlives any deployment.
+const caLifetime = 10 * 365 * 24 * time.Hour
+
+// keygen is the keygen subcommand (account plan 1.2):
+//
+// equipo-hosted-controller keygen -ed25519 -out PREFIX
+// equipo-hosted-controller keygen -ca -out PREFIX
+//
+// -ed25519 writes PREFIX.key, a 32-byte ed25519 seed in standard base64 as
+// the controller and the proxies read signing keys, and PREFIX.pub, the
+// public key in standard base64. -ca writes PREFIX.key, an ECDSA P-256 key
+// in PKCS #8 PEM, and PREFIX.pub, its self-signed CA certificate in PEM
+// (what ctlproxy.NewCA and the proxy's intercept CA load). The private half
+// is mode 0600, the public half 0644; neither file may exist already, and
+// neither key is printed.
+func keygen(args []string, stdout, stderr io.Writer) error {
+ fs := flag.NewFlagSet("keygen", flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ ed := fs.Bool("ed25519", false, "an ed25519 signing key")
+ ca := fs.Bool("ca", false, "an ECDSA P-256 CA key and its self-signed certificate")
+ out := fs.String("out", "", "the path prefix: PREFIX.key and PREFIX.pub are written")
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ switch {
+ case fs.NArg() != 0:
+ return fmt.Errorf("keygen: unexpected arguments %q", fs.Args())
+ case *ed == *ca:
+ return errors.New("keygen: give exactly one of -ed25519 and -ca")
+ case *out == "":
+ return errors.New("keygen: -out is required")
+ }
+ var private, public []byte
+ var err error
+ if *ed {
+ private, public, err = newEd25519()
+ } else {
+ private, public, err = newCA(filepath.Base(*out), time.Now())
+ }
+ if err != nil {
+ return fmt.Errorf("keygen: %w", err)
+ }
+ keyPath, pubPath := *out+".key", *out+".pub"
+ if _, err := os.Lstat(pubPath); !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("keygen: %s already exists (or cannot be checked); keygen never replaces a key", pubPath)
+ }
+ if err := writeNew(keyPath, private, 0o600); err != nil {
+ return fmt.Errorf("keygen: %w", err)
+ }
+ if err := writeNew(pubPath, public, 0o644); err != nil {
+ _ = os.Remove(keyPath)
+ return fmt.Errorf("keygen: %w", err)
+ }
+ fmt.Fprintf(stdout, "wrote %s (private, mode 0600) and %s\n", keyPath, pubPath)
+ return nil
+}
+
+func newEd25519() (private, public []byte, err error) {
+ seed := make([]byte, ed25519.SeedSize)
+ if _, err := rand.Read(seed); err != nil {
+ return nil, nil, err
+ }
+ pub := ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)
+ return []byte(base64.StdEncoding.EncodeToString(seed) + "\n"), []byte(base64.StdEncoding.EncodeToString(pub) + "\n"), nil
+}
+
+// newCA is a P-256 CA key and its self-signed certificate, named name,
+// that may sign leaf certificates only (path length 0).
+func newCA(name string, now time.Time) (private, public []byte, err error) {
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return nil, nil, err
+ }
+ serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
+ if err != nil {
+ return nil, nil, err
+ }
+ tmpl := &x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "equipo-hosted " + name},
+ NotBefore: now.Add(-time.Hour), NotAfter: now.Add(caLifetime),
+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true,
+ MaxPathLen: 0, MaxPathLenZero: true}
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+ if err != nil {
+ return nil, nil, err
+ }
+ keyDER, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ return nil, nil, err
+ }
+ return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}),
+ pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), nil
+}
+
+// writeNew creates path, which must not exist, with b at mode (whatever
+// the umask), and syncs it.
+func writeNew(path string, b []byte, mode os.FileMode) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
+ if err != nil {
+ return err
+ }
+ err = f.Chmod(mode)
+ if err == nil {
+ _, err = f.Write(b)
+ }
+ if err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ _ = os.Remove(path)
+ }
+ return err
+}
diff --git a/cmd/equipo-hosted-controller/keygen_test.go b/cmd/equipo-hosted-controller/keygen_test.go
new file mode 100644
index 00000000..cf4dce70
--- /dev/null
+++ b/cmd/equipo-hosted-controller/keygen_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/pem"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+)
+
+// TestKeygenWritesPrivate0600: keygen -ed25519 and keygen -ca write the
+// private half at mode 0600 and the public half beside it (.pub, 0644),
+// print neither key, and write files the controller and the proxies read:
+// the ed25519 seed as the signing key loader reads it, and the CA as a
+// P-256 key and a self-signed CA certificate that may sign certificates.
+func TestKeygenWritesPrivate0600(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ run := func(kind, name string) (key, pub []byte, printed string) {
+ t.Helper()
+ prefix := filepath.Join(dir, name)
+ var out, errOut bytes.Buffer
+ if err := keygen([]string{kind, "-out", prefix}, &out, &errOut); err != nil {
+ t.Fatalf("keygen %s: %v", kind, err)
+ }
+ for file, want := range map[string]os.FileMode{prefix + ".key": 0o600, prefix + ".pub": 0o644} {
+ info, err := os.Stat(file)
+ if err != nil {
+ t.Fatalf("keygen %s: %v", kind, err)
+ }
+ if info.Mode().Perm() != want {
+ t.Fatalf("keygen %s wrote %s at mode %v, want %v", kind, file, info.Mode().Perm(), want)
+ }
+ }
+ key, err := os.ReadFile(prefix + ".key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err = os.ReadFile(prefix + ".pub")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return key, pub, out.String() + errOut.String()
+ }
+
+ seed, pubB64, printed := run("-ed25519", "controller")
+ if s := strings.TrimSpace(string(seed)); s == "" || strings.Contains(printed, s) {
+ t.Fatalf("keygen -ed25519 printed its private key: %q", printed)
+ }
+ k, err := readSigningKey(filepath.Join(dir, "controller.key"))
+ if err != nil {
+ t.Fatalf("the controller cannot read the key keygen wrote: %v", err)
+ }
+ if want := strings.TrimSpace(string(pubB64)); want != pubB64Of(k) {
+ t.Fatalf("controller.pub = %q, want the key's public half %q", want, pubB64Of(k))
+ }
+ if _, err := verifyKeys([]keyEntry{{ID: "inst-1", Role: "instance", PublicKey: strings.TrimSpace(string(pubB64))}}); err != nil {
+ t.Fatalf("the controller refuses the public half as a verify key: %v", err)
+ }
+
+ caKey, caCert, printed := run("-ca", "client-ca")
+ block, _ := pem.Decode(caKey)
+ if block == nil || !strings.Contains(string(caKey), "PRIVATE KEY") {
+ t.Fatalf("client-ca.key is not a PEM private key")
+ }
+ body := strings.Split(strings.TrimSpace(string(caKey)), "\n")[1]
+ if strings.Contains(printed, body) {
+ t.Fatalf("keygen -ca printed its private key: %q", printed)
+ }
+ if _, err := ctlproxy.NewCA(caCert, caKey); err != nil {
+ t.Fatalf("the controller refuses the client CA keygen wrote: %v", err)
+ }
+ pair, err := tls.X509KeyPair(caCert, caKey)
+ if err != nil {
+ t.Fatalf("the proxy cannot load the intercept CA keygen wrote: %v", err)
+ }
+ cert, err := x509.ParseCertificate(pair.Certificate[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !cert.IsCA || cert.KeyUsage&x509.KeyUsageCertSign == 0 || cert.CheckSignatureFrom(cert) != nil {
+ t.Fatalf("client-ca.pub is not a self-signed CA that may sign certificates: %+v", cert)
+ }
+}
+
+// TestKeygenRefusesOverwrite: keygen never replaces a key, and a refusal
+// leaves no half-written pair; it needs exactly one of -ed25519 and -ca,
+// and -out.
+func TestKeygenRefusesOverwrite(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ prefix := filepath.Join(dir, "operator")
+ var out bytes.Buffer
+ if err := keygen([]string{"-ed25519", "-out", prefix}, &out, &out); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := os.ReadFile(prefix + ".key")
+ if err := keygen([]string{"-ed25519", "-out", prefix}, &out, &out); err == nil {
+ t.Fatal("keygen replaced an existing key")
+ }
+ if after, _ := os.ReadFile(prefix + ".key"); !bytes.Equal(before, after) {
+ t.Fatal("a refused keygen changed the existing key")
+ }
+
+ // Only the public half exists: refused, and no private half is left.
+ lone := filepath.Join(dir, "lone")
+ if err := os.WriteFile(lone+".pub", []byte("x\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := keygen([]string{"-ca", "-out", lone}, &out, &out); err == nil {
+ t.Fatal("keygen wrote a key beside an existing .pub")
+ }
+ if _, err := os.Stat(lone + ".key"); !os.IsNotExist(err) {
+ t.Fatalf("a refused keygen left %s.key behind (%v)", lone, err)
+ }
+
+ for name, args := range map[string][]string{
+ "both kinds": {"-ed25519", "-ca", "-out", filepath.Join(dir, "a")},
+ "no kind": {"-out", filepath.Join(dir, "b")},
+ "no out": {"-ed25519"},
+ "extra": {"-ed25519", "-out", filepath.Join(dir, "c"), "more"},
+ } {
+ if err := keygen(args, &out, &out); err == nil {
+ t.Errorf("keygen %s (%v) = nil, want a usage error", name, args)
+ }
+ }
+}
+
+func pubB64Of(k ed25519.PrivateKey) string {
+ return base64.StdEncoding.EncodeToString(k.Public().(ed25519.PublicKey))
+}
diff --git a/cmd/equipo-hosted-controller/main.go b/cmd/equipo-hosted-controller/main.go
index 961fa031..885eba32 100644
--- a/cmd/equipo-hosted-controller/main.go
+++ b/cmd/equipo-hosted-controller/main.go
@@ -4,14 +4,19 @@
// wired in.
//
// equipo-hosted-controller -config /etc/equipo-hosted/controller.json
+// equipo-hosted-controller keygen -ed25519|-ca -out PREFIX
//
// Launches stay off unless EQUIPO_HOSTED_ENABLED=1; stops, reads and the
-// reaper run either way.
+// reaper run either way. At start it makes its TLS key and certificate if
+// there are none (first boot), writes the certificate's SPKI pin to the
+// config bucket once (pins/controller.spki), and then publishes its alarm
+// metrics to CloudWatch every minute.
package main
import (
"context"
"crypto/tls"
+ "crypto/x509"
"errors"
"flag"
"fmt"
@@ -30,6 +35,7 @@ import (
"amadan.net/oficina/equipo/internal/isolatedjob/awsjob"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
"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"
@@ -43,6 +49,13 @@ import (
const shutdownTimeout = 30 * time.Second
func main() {
+ if len(os.Args) > 1 && os.Args[1] == "keygen" {
+ if err := keygen(os.Args[2:], os.Stdout, os.Stderr); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ exit(2)
+ }
+ return
+ }
path := flag.String("config", "", "path of the controller's JSON config file")
flag.Parse()
exitWith(run(*path))
@@ -76,11 +89,18 @@ func run(path string) error {
defer restart()
// Bad TLS files or a busy address fail here, before the store is
- // opened or any startup alert is sent.
+ // opened or any startup alert is sent. The first boot makes the pair.
+ if err := ensureTLS(cfg.tlsCert, cfg.tlsKey, net.ParseIP(listenHost(cfg.listen))); err != nil {
+ return err
+ }
cert, err := tls.LoadX509KeyPair(cfg.tlsCert, cfg.tlsKey)
if err != nil {
return fmt.Errorf("TLS key pair: %w", err)
}
+ leaf, err := x509.ParseCertificate(cert.Certificate[0])
+ if err != nil {
+ return fmt.Errorf("TLS certificate: %w", err)
+ }
apiLn, err := net.Listen("tcp", cfg.listen)
if err != nil {
return err
@@ -130,7 +150,11 @@ func run(path string) error {
if err != nil {
return err
}
- fetcher := s3Fetcher{client: s3.NewFromConfig(awsCfg), bucket: cfg.bucket, prefix: cfg.prefix, owner: owner, timeout: fetchTimeout}
+ s3c := s3.NewFromConfig(awsCfg)
+ if err := publishPin(ctx, s3c, cfg.bucket, owner, spkiPin(leaf)); err != nil {
+ return err
+ }
+ fetcher := s3Fetcher{client: s3c, bucket: cfg.bucket, prefix: cfg.prefix, owner: owner, timeout: fetchTimeout}
c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: jobs, Auditor: runner, Alerter: alerter, Fetcher: fetcher, Log: opLog})
if err != nil {
return err
@@ -143,8 +167,26 @@ func run(path string) error {
if err != nil {
return err
}
- 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, newAPIServer(api, cert), apiLn, newMetricsServer(metrics.Handler(c)), metricsLn, shutdownTimeout)
+ // The CloudWatch publisher stops (deferred after the store's close, so
+ // it runs first) before the store closes.
+ lag := newLitestreamLag(time.Now)
+ watchCtx, stopWatch := context.WithCancel(ctx)
+ watched := make(chan struct{})
+ tick := time.NewTicker(publishEvery)
+ defer tick.Stop()
+ go func() {
+ defer close(watched)
+ newWatcher(c, cloudwatch.NewFromConfig(awsCfg), lag, time.Now).loop(watchCtx, tick.C)
+ }()
+ defer func() { stopWatch(); <-watched }()
+ log.Printf("equipo-hosted-controller: API on %s, metrics on %s, launches enabled: %v, TLS pin %s", cfg.listen, cfg.metricsListen, cfg.ctl.Enabled, spkiPin(leaf))
+ return serve(ctx, c, newAPIServer(api, cert), apiLn, newMetricsServer(metricsMux(metrics, c, lag)), metricsLn, shutdownTimeout)
+}
+
+// listenHost is the IP of an "IP:port" the config has already checked.
+func listenHost(addr string) string {
+ host, _, _ := net.SplitHostPort(addr)
+ return host
}
// runnerHook, when set, wraps the runner the controller calls. Only a build
diff --git a/cmd/equipo-hosted-controller/pin_test.go b/cmd/equipo-hosted-controller/pin_test.go
new file mode 100644
index 00000000..ca187dd9
--- /dev/null
+++ b/cmd/equipo-hosted-controller/pin_test.go
@@ -0,0 +1,152 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/hex"
+ "errors"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/smithy-go"
+)
+
+// fakePins is the config bucket as the pin writer sees it: a conditional
+// put (If-None-Match: *) of an object that exists fails PreconditionFailed,
+// as S3 answers it; an unconditional put replaces.
+type fakePins struct {
+ mu sync.Mutex
+ objects map[string][]byte
+ puts []s3.PutObjectInput
+ getErr error
+}
+
+func (f *fakePins) PutObject(_ context.Context, in *s3.PutObjectInput, _ ...func(*s3.Options)) (*s3.PutObjectOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.puts = append(f.puts, *in)
+ key := aws.ToString(in.Bucket) + "/" + aws.ToString(in.Key)
+ if _, ok := f.objects[key]; ok && aws.ToString(in.IfNoneMatch) == "*" {
+ return nil, &smithy.GenericAPIError{Code: "PreconditionFailed", Message: "At least one of the pre-conditions you specified did not hold"}
+ }
+ b, err := io.ReadAll(in.Body)
+ if err != nil {
+ return nil, err
+ }
+ f.objects[key] = b
+ return &s3.PutObjectOutput{}, nil
+}
+
+func (f *fakePins) GetObject(_ context.Context, in *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.getErr != nil {
+ return nil, f.getErr
+ }
+ b, ok := f.objects[aws.ToString(in.Bucket)+"/"+aws.ToString(in.Key)]
+ if !ok {
+ return nil, &smithy.GenericAPIError{Code: "NoSuchKey"}
+ }
+ return &s3.GetObjectOutput{Body: io.NopCloser(bytes.NewReader(b))}, nil
+}
+
+// bootTLS is a boot's TLS step: the key pair made on first boot (or kept),
+// and its pin.
+func bootTLS(t *testing.T, dir string) string {
+ t.Helper()
+ certPath, keyPath := filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key")
+ if err := ensureTLS(certPath, keyPath, net.ParseIP("10.0.0.5")); err != nil {
+ t.Fatalf("ensureTLS: %v", err)
+ }
+ pair, err := tls.LoadX509KeyPair(certPath, keyPath)
+ if err != nil {
+ t.Fatalf("the TLS pair ensureTLS made does not load: %v", err)
+ }
+ leaf, err := x509.ParseCertificate(pair.Certificate[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ pin := spkiPin(leaf)
+ sum := sha256.Sum256(leaf.RawSubjectPublicKeyInfo)
+ if pin != hex.EncodeToString(sum[:]) {
+ t.Fatalf("spkiPin = %q, want the hex SHA-256 of the SPKI", pin)
+ }
+ return pin
+}
+
+// TestPinWrittenOnce: the first boot makes the TLS key (0600) and its
+// self-signed certificate and writes the SPKI pin to pins/controller.spki
+// with a conditional put, in the controller's account; a later boot keeps
+// the same key, so the same pin, and leaves the object alone; a different
+// key's pin is refused and never replaces the written one.
+func TestPinWrittenOnce(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ const bucket, owner = "equipo-hosted-config-149757027610", "149757027610"
+ f := &fakePins{objects: map[string][]byte{}}
+ dir := t.TempDir()
+
+ pin := bootTLS(t, dir)
+ if info, err := os.Stat(filepath.Join(dir, "tls.key")); err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("tls.key mode = %v (%v), want 0600", info.Mode().Perm(), err)
+ }
+ if err := publishPin(ctx, f, bucket, owner, pin); err != nil {
+ t.Fatalf("first boot: %v", err)
+ }
+ if got := string(f.objects[bucket+"/"+pinKey]); got != pin {
+ t.Fatalf("pins/controller.spki = %q, want %q", got, pin)
+ }
+ p := f.puts[0]
+ if aws.ToString(p.Key) != "pins/controller.spki" || aws.ToString(p.IfNoneMatch) != "*" || aws.ToString(p.ExpectedBucketOwner) != owner {
+ t.Fatalf("pin put = key %q, If-None-Match %q, owner %q; want a conditional put of pins/controller.spki in %s",
+ aws.ToString(p.Key), aws.ToString(p.IfNoneMatch), aws.ToString(p.ExpectedBucketOwner), owner)
+ }
+
+ // The next boot: the same key pair, the same pin, nothing replaced.
+ if again := bootTLS(t, dir); again != pin {
+ t.Fatalf("a second boot made a new TLS key: pin %s, then %s", pin, again)
+ }
+ if err := publishPin(ctx, f, bucket, owner, pin); err != nil {
+ t.Fatalf("second boot with the same pin: %v", err)
+ }
+ for _, p := range f.puts {
+ if aws.ToString(p.IfNoneMatch) != "*" {
+ t.Fatalf("a pin put without If-None-Match: %+v", p)
+ }
+ }
+
+ // Another key (a replaced host): refused, the written pin kept.
+ other := bootTLS(t, t.TempDir())
+ err := publishPin(ctx, f, bucket, owner, other)
+ if err == nil || !strings.Contains(err.Error(), "differ") {
+ t.Fatalf("a different pin = %v, want a refusal", err)
+ }
+ if got := string(f.objects[bucket+"/"+pinKey]); got != pin {
+ t.Fatalf("pins/controller.spki became %q, want %q kept", got, pin)
+ }
+
+ // The written pin cannot be read back: refused, not taken as equal.
+ f.getErr = errors.New("connection reset")
+ if err := publishPin(ctx, f, bucket, owner, pin); err == nil {
+ t.Fatal("a pin that could not be read back was taken as written")
+ }
+
+ // Half a key pair on disk: refused rather than replaced.
+ half := t.TempDir()
+ if err := os.WriteFile(filepath.Join(half, "tls.crt"), []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := ensureTLS(filepath.Join(half, "tls.crt"), filepath.Join(half, "tls.key"), net.ParseIP("10.0.0.5")); err == nil {
+ t.Fatal("ensureTLS made a key beside a lone certificate")
+ }
+}
diff --git a/cmd/equipo-hosted-controller/tlspin.go b/cmd/equipo-hosted-controller/tlspin.go
new file mode 100644
index 00000000..317c494d
--- /dev/null
+++ b/cmd/equipo-hosted-controller/tlspin.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/hex"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/aws/smithy-go"
+)
+
+// The controller's TLS identity. The instance and the proxies trust it only
+// by its pin, the hex SHA-256 of the certificate's SubjectPublicKeyInfo (the
+// form of hostedproxy's ControllerTLSPin), so the certificate is
+// self-signed and made on the host at first boot; the key never leaves it.
+// The pin goes to the config bucket once, for the bring-up to read
+// (account plan 5.2) and for every later boot to check against.
+
+// pinKey is the config bucket object holding the controller's pin.
+const pinKey = "pins/controller.spki"
+
+// tlsLifetime is how long the first boot's certificate is valid. Clients
+// check the pin, not the dates, but Go's TLS stack still parses them.
+const tlsLifetime = 20 * 365 * 24 * time.Hour
+
+// ensureTLS makes the TLS key (P-256, PKCS #8 PEM, mode 0600) and a
+// self-signed certificate for ip when neither file exists, and leaves an
+// existing pair alone. One without the other is refused: a key made beside
+// a stray certificate would change the pin.
+func ensureTLS(certPath, keyPath string, ip net.IP) error {
+ _, certErr := os.Lstat(certPath)
+ _, keyErr := os.Lstat(keyPath)
+ switch {
+ case certErr == nil && keyErr == nil:
+ return nil
+ case !errors.Is(certErr, os.ErrNotExist) || !errors.Is(keyErr, os.ErrNotExist):
+ return fmt.Errorf("TLS: %s and %s must both exist or neither (cert: %v, key: %v)", certPath, keyPath, certErr, keyErr)
+ }
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return err
+ }
+ serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
+ if err != nil {
+ return err
+ }
+ now := time.Now()
+ tmpl := &x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "equipo-hosted-controller"},
+ NotBefore: now.Add(-time.Hour), NotAfter: now.Add(tlsLifetime), IPAddresses: []net.IP{ip},
+ KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+ if err != nil {
+ return err
+ }
+ keyDER, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ return err
+ }
+ if err := writeNew(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
+ return fmt.Errorf("TLS key: %w", err)
+ }
+ if err := writeNew(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
+ _ = os.Remove(keyPath)
+ return fmt.Errorf("TLS certificate: %w", err)
+ }
+ return nil
+}
+
+// spkiPin is c's pin: the hex SHA-256 of its SubjectPublicKeyInfo.
+func spkiPin(c *x509.Certificate) string {
+ sum := sha256.Sum256(c.RawSubjectPublicKeyInfo)
+ return hex.EncodeToString(sum[:])
+}
+
+// pinObjects is the S3 calls publishPin makes. *s3.Client satisfies it.
+type pinObjects interface {
+ PutObject(context.Context, *s3.PutObjectInput, ...func(*s3.Options)) (*s3.PutObjectOutput, error)
+ GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error)
+}
+
+// publishPin writes pin to pinKey in bucket, which must belong to owner,
+// exactly once: the put is conditional (If-None-Match: *), so it never
+// replaces an object. When one is there already it is read back, and the
+// controller starts only if it holds this pin; a different pin (a new key
+// on a replaced host) is refused, since every client pins the old one.
+func publishPin(ctx context.Context, c pinObjects, bucket, owner, pin string) error {
+ ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
+ defer cancel()
+ _, err := c.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(pinKey),
+ Body: strings.NewReader(pin), ContentType: aws.String("text/plain"), IfNoneMatch: aws.String("*"),
+ ExpectedBucketOwner: aws.String(owner), ServerSideEncryption: types.ServerSideEncryptionAes256})
+ var apiErr smithy.APIError
+ switch {
+ case err == nil:
+ return nil
+ case !errors.As(err, &apiErr) || apiErr.ErrorCode() != "PreconditionFailed":
+ return fmt.Errorf("write s3://%s/%s: %w", bucket, pinKey, err)
+ }
+ out, err := c.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(pinKey), ExpectedBucketOwner: aws.String(owner)})
+ if err != nil {
+ return fmt.Errorf("read back s3://%s/%s: %w", bucket, pinKey, err)
+ }
+ defer out.Body.Close()
+ have, err := io.ReadAll(io.LimitReader(out.Body, 1024))
+ if err != nil {
+ return fmt.Errorf("read back s3://%s/%s: %w", bucket, pinKey, err)
+ }
+ if !bytes.Equal(bytes.TrimSpace(have), []byte(pin)) {
+ return fmt.Errorf("s3://%s/%s holds pin %q and this controller's TLS key has pin %s; they differ, and the written pin is never replaced",
+ bucket, pinKey, bytes.TrimSpace(have), pin)
+ }
+ return nil
+}
diff --git a/cmd/equipo-hosted-controller/watch.go b/cmd/equipo-hosted-controller/watch.go
new file mode 100644
index 00000000..6aac0b8f
--- /dev/null
+++ b/cmd/equipo-hosted-controller/watch.go
@@ -0,0 +1,175 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net/http"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+)
+
+// What the alarms read (infra/hosted/modules/alerts): the controller
+// publishes these to CloudWatch every minute, in one namespace with no
+// dimensions.
+const (
+ metricNamespace = "EquipoHosted"
+ publishEvery = time.Minute
+ // heartbeatFresh is how recent the last reaper pass must be, and
+ // clean, for Heartbeat to be published (account plan 5.3: a clean pass
+ // in the last two minutes). The alarm breaches after three minutes
+ // without one.
+ heartbeatFresh = 2 * hostedctl.ReapInterval
+)
+
+// metricPutter is the CloudWatch call the watcher makes.
+// *cloudwatch.Client satisfies it.
+type metricPutter interface {
+ PutMetricData(context.Context, *cloudwatch.PutMetricDataInput, ...func(*cloudwatch.Options)) (*cloudwatch.PutMetricDataOutput, error)
+}
+
+// litestreamLag tracks Litestream's heartbeat. Litestream (0.5) requests
+// heartbeat-url at most once per heartbeat-interval, and only when every
+// database has synced to its replica within that interval; the controller
+// host points it at GET /litestream/heartbeat on the metrics listener. The
+// lag is the time since the last such request, or since the controller
+// started when there has been none: an upper bound on how far the replica
+// trails, which grows while replication is down.
+type litestreamLag struct {
+ now func() time.Time
+ mu sync.Mutex
+ since time.Time
+}
+
+func newLitestreamLag(now func() time.Time) *litestreamLag {
+ return &litestreamLag{now: now, since: now()}
+}
+
+func (l *litestreamLag) beat() {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.since = l.now()
+}
+
+// seconds is the lag in whole seconds.
+func (l *litestreamLag) seconds() float64 {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return float64(int64(l.now().Sub(l.since).Seconds()))
+}
+
+// metricsMux is the metrics listener's handler: the controller's GET
+// /metrics with litestream_lag_seconds after it, GET /healthz, and
+// Litestream's heartbeat. The API listener serves none of these.
+func metricsMux(m *hostedctl.Metrics, c *hostedctl.Controller, lag *litestreamLag) http.Handler {
+ metrics := m.Handler(c)
+ mux := http.NewServeMux()
+ mux.Handle("/healthz", c.Healthz())
+ mux.HandleFunc("/litestream/heartbeat", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ lag.beat()
+ w.WriteHeader(http.StatusOK)
+ })
+ mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
+ metrics.ServeHTTP(w, r)
+ if r.Method == http.MethodGet {
+ fmt.Fprintf(w, "# HELP litestream_lag_seconds Seconds since Litestream last confirmed every database synced to its replica (its heartbeat), or since the controller started.\n"+
+ "# TYPE litestream_lag_seconds gauge\nlitestream_lag_seconds %v\n", lag.seconds())
+ }
+ })
+ return mux
+}
+
+// watcher publishes the alarms' metrics.
+type watcher struct {
+ c *hostedctl.Controller
+ cw metricPutter
+ lag *litestreamLag
+ now func() time.Time
+ start time.Time
+}
+
+func newWatcher(c *hostedctl.Controller, cw metricPutter, lag *litestreamLag, now func() time.Time) *watcher {
+ return &watcher{c: c, cw: cw, lag: lag, now: now, start: now()}
+}
+
+// datums are this minute's values. A value the controller does not know is
+// left out, never sent as zero: Heartbeat unless the last reaper pass was
+// clean and recent; AuditPassing before the first audit; OrphansSeen before
+// the first pass, or when its List was incomplete.
+func (w *watcher) datums(ctx context.Context) ([]types.MetricDatum, error) {
+ s, err := w.c.Status(ctx)
+ if err != nil {
+ return nil, err
+ }
+ now := w.now()
+ var out []types.MetricDatum
+ add := func(name string, v float64, unit types.StandardUnit) {
+ out = append(out, types.MetricDatum{MetricName: aws.String(name), Value: aws.Float64(v), Unit: unit, Timestamp: aws.Time(now)})
+ }
+ last, ran := w.c.LastReap()
+ if ran && last.Err == nil && time.Duration(s.NowNS-int64(last.At)) <= heartbeatFresh {
+ add("Heartbeat", 1, types.StandardUnitCount)
+ }
+ if s.NetworkAudit.Ran {
+ add("AuditPassing", boolMetric(s.NetworkAudit.Passing), types.StandardUnitCount)
+ }
+ if ran && !last.Report.Skipped {
+ add("OrphansSeen", float64(last.Report.OrphansSeen), types.StandardUnitCount)
+ }
+ silent := 0
+ for _, p := range s.Proxies {
+ if p.Fed && time.Duration(p.LastFeedAgeMS)*time.Millisecond > ctlproxy.SilentAfter ||
+ !p.Fed && now.Sub(w.start) > ctlproxy.SilentAfter {
+ silent++
+ }
+ }
+ add("ProxySilent", float64(silent), types.StandardUnitCount)
+ add("LitestreamLag", w.lag.seconds(), types.StandardUnitSeconds)
+ return out, nil
+}
+
+func boolMetric(b bool) float64 {
+ if b {
+ return 1
+ }
+ return 0
+}
+
+// publish sends this minute's datums in one call, bounded in time.
+func (w *watcher) publish(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, alertTimeout)
+ defer cancel()
+ d, err := w.datums(ctx)
+ if err != nil {
+ return fmt.Errorf("read the controller's status: %w", err)
+ }
+ if _, err := w.cw.PutMetricData(ctx, &cloudwatch.PutMetricDataInput{Namespace: aws.String(metricNamespace), MetricData: d}); err != nil {
+ return fmt.Errorf("publish to CloudWatch: %w", err)
+ }
+ return nil
+}
+
+// loop publishes at once and then on every tick until ctx ends. A failed
+// publish is logged; the next tick tries again.
+func (w *watcher) loop(ctx context.Context, ticks <-chan time.Time) {
+ for {
+ if err := w.publish(ctx); err != nil && ctx.Err() == nil {
+ log.Printf("equipo-hosted-controller: metrics: %v", err)
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticks:
+ }
+ }
+}
diff --git a/cmd/equipo-hosted-controller/watch_test.go b/cmd/equipo-hosted-controller/watch_test.go
new file mode 100644
index 00000000..6084d167
--- /dev/null
+++ b/cmd/equipo-hosted-controller/watch_test.go
@@ -0,0 +1,213 @@
+package main
+
+import (
+ "context"
+ "crypto/ed25519"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+)
+
+// fakeCW records PutMetricData calls.
+type fakeCW struct {
+ mu sync.Mutex
+ puts []*cloudwatch.PutMetricDataInput
+ err error
+}
+
+func (f *fakeCW) PutMetricData(_ context.Context, in *cloudwatch.PutMetricDataInput, _ ...func(*cloudwatch.Options)) (*cloudwatch.PutMetricDataOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.puts = append(f.puts, in)
+ return &cloudwatch.PutMetricDataOutput{}, f.err
+}
+
+// last returns the last put's datums by name, and checks that every put
+// went to the EquipoHosted namespace with no dimensions (the alarms have
+// none) and a timestamp.
+func (f *fakeCW) last(t *testing.T) map[string]float64 {
+ t.Helper()
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if len(f.puts) == 0 {
+ t.Fatal("nothing was published")
+ }
+ in := f.puts[len(f.puts)-1]
+ if aws.ToString(in.Namespace) != "EquipoHosted" {
+ t.Fatalf("namespace %q, want EquipoHosted", aws.ToString(in.Namespace))
+ }
+ out := map[string]float64{}
+ for _, d := range in.MetricData {
+ if len(d.Dimensions) != 0 || d.Timestamp == nil || d.Value == nil {
+ t.Fatalf("datum %s has dimensions %v, timestamp %v, value %v; the alarms want none, and a time and value", aws.ToString(d.MetricName), d.Dimensions, d.Timestamp, d.Value)
+ }
+ out[aws.ToString(d.MetricName)] = *d.Value
+ }
+ return out
+}
+
+// manualClock is the watcher's wall clock in tests.
+type manualClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func (c *manualClock) now() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.t
+}
+
+func (c *manualClock) advance(d time.Duration) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.t = c.t.Add(d)
+}
+
+// TestHeartbeatOnlyAfterCleanPass: Heartbeat is published only while the
+// last reaper pass finished with no error and recently (account plan 5.3's
+// two minutes): not before the first pass, not after a failed pass, and not
+// once the last clean pass has gone stale.
+func TestHeartbeatOnlyAfterCleanPass(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ var fake *isolatedjob.Fake
+ tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { fake = f; return f })
+ cw := &fakeCW{}
+ clock := &manualClock{t: time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC)}
+ w := newWatcher(tc.c, cw, newLitestreamLag(clock.now), clock.now)
+ heartbeat := func() (float64, bool) {
+ t.Helper()
+ if err := w.publish(ctx); err != nil {
+ t.Fatalf("publish: %v", err)
+ }
+ v, ok := cw.last(t)["Heartbeat"]
+ return v, ok
+ }
+
+ if _, ok := heartbeat(); ok {
+ t.Fatal("Heartbeat published before any reaper pass")
+ }
+
+ fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("describe route tables: throttled"))
+ if _, err := tc.c.Reap(ctx); err == nil {
+ t.Fatal("the reaper pass with a failing audit returned no error; the test needs a failed pass")
+ }
+ if _, ok := heartbeat(); ok {
+ t.Fatal("Heartbeat published after a failed reaper pass")
+ }
+
+ fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true}, nil)
+ if _, err := tc.c.Reap(ctx); err != nil {
+ t.Fatalf("clean pass: %v", err)
+ }
+ if v, ok := heartbeat(); !ok || v != 1 {
+ t.Fatalf("Heartbeat after a clean pass = %v, %v; want 1", v, ok)
+ }
+
+ tc.clk.AdvanceMono(heartbeatFresh + time.Second)
+ if _, ok := heartbeat(); ok {
+ t.Fatalf("Heartbeat published %v after the last clean pass", heartbeatFresh+time.Second)
+ }
+ if _, err := tc.c.Reap(ctx); err != nil {
+ t.Fatalf("clean pass: %v", err)
+ }
+ if v, ok := heartbeat(); !ok || v != 1 {
+ t.Fatalf("Heartbeat after a fresh clean pass = %v, %v; want 1", v, ok)
+ }
+}
+
+// TestHeartbeatPublishesAlarmMetrics: one publish carries what the alarms
+// read: AuditPassing, OrphansSeen from the last pass, ProxySilent (proxies
+// late on the feed, counting one that never asked only once the watcher
+// has run ctlproxy's silence window) and LitestreamLag (seconds since
+// Litestream last confirmed a sync, or since start); loop publishes every
+// tick until its context ends, and a failed put does not end it.
+func TestHeartbeatPublishesAlarmMetrics(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ var fake *isolatedjob.Fake
+ tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { fake = f; return f })
+ proxyKey := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
+ if _, err := tc.c.Handler(hostedctl.HandlerConfig{Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{
+ instID: {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance},
+ "proxy-a": {Public: proxyKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy},
+ }, Signing: ctlKey, Wall: tc.clk.Wall}); err != nil {
+ t.Fatal(err)
+ }
+ fake.Plant(isolatedjob.LaunchSpec{AttemptID: "nobody-owns-this", Image: testDigest, Size: isolatedjob.SizeSmall})
+ if _, err := tc.c.Reap(ctx); err != nil {
+ t.Fatalf("clean pass: %v", err)
+ }
+ cw := &fakeCW{}
+ clock := &manualClock{t: time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC)}
+ lag := newLitestreamLag(clock.now)
+ w := newWatcher(tc.c, cw, lag, clock.now)
+
+ if err := w.publish(ctx); err != nil {
+ t.Fatal(err)
+ }
+ got := cw.last(t)
+ if got["AuditPassing"] != 1 || got["OrphansSeen"] != 1 || got["ProxySilent"] != 0 || got["LitestreamLag"] != 0 {
+ t.Fatalf("published %v; want AuditPassing 1, OrphansSeen 1, ProxySilent 0 (just started), LitestreamLag 0", got)
+ }
+
+ clock.advance(4 * time.Minute)
+ if err := w.publish(ctx); err != nil {
+ t.Fatal(err)
+ }
+ got = cw.last(t)
+ if got["ProxySilent"] != 1 || got["LitestreamLag"] != 240 {
+ t.Fatalf("four minutes on with no feed and no Litestream heartbeat: %v; want ProxySilent 1, LitestreamLag 240", got)
+ }
+
+ // Litestream's heartbeat (GET /litestream/heartbeat on the metrics
+ // listener) resets the lag, which /metrics also shows.
+ h := metricsMux(hostedctl.NewMetrics(), tc.c, lag)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/litestream/heartbeat", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("heartbeat answered %d", rec.Code)
+ }
+ clock.advance(30 * time.Second)
+ if err := w.publish(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if got := cw.last(t)["LitestreamLag"]; got != 30 {
+ t.Fatalf("LitestreamLag 30 s after a heartbeat = %v", got)
+ }
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
+ body, _ := io.ReadAll(rec.Body)
+ if !strings.Contains(string(body), "\nlitestream_lag_seconds 30\n") || !strings.Contains(string(body), "equipo_hosted_jobs") {
+ t.Fatalf("/metrics lacks litestream_lag_seconds 30 or the controller's metrics:\n%s", body)
+ }
+
+ // The loop: a failing put is logged and the loop goes on, until ctx ends.
+ cw.err = errors.New("throttled")
+ loopCtx, cancel := context.WithCancel(ctx)
+ done := make(chan struct{})
+ ticks := make(chan time.Time)
+ go func() { w.loop(loopCtx, ticks); close(done) }()
+ ticks <- time.Time{}
+ ticks <- time.Time{}
+ cancel()
+ <-done
+ cw.mu.Lock()
+ n := len(cw.puts)
+ cw.mu.Unlock()
+ if n < 5 {
+ t.Fatalf("%d puts after two loop ticks (and the first publish at start), want at least 5 in all", n)
+ }
+}
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index cd84758f..0a1c431e 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -2337,3 +2337,44 @@ Mutations (each restored and checked identical with `cmp`):
- **S2** inputs not checked before proving (the `check_inputs` refusals dropped). Same command: exit 1, `FAIL` on all three `SourceInputs` tests, `'the configuration is not provable' not found in ...`. Restored.
- **S3** a module variable taken from the plan's dependency again (`argument_value` replaced by `module_var_value`). Same command: exit 1, `FAIL: test_transformed_account_argument_refused: the plan was accepted`; `test_interpolated_argument_refused: 'region' not found`; `test_argument_literal_differing_from_the_plan_refused: 'account_id' not found`. Restored.
- **S4** an argument the reader cannot evaluate falls back to the plan's dependency (the refusal replaced by `value = self.module_var_value(prefix, name)`). Same command: exit 1, `FAIL: test_transformed_account_argument_refused: the plan was accepted` and `test_interpolated_argument_refused: 'region' not found`. Restored.
+
+## Task 29
+
+Release artifacts and host configuration by digest. No AWS call; nothing published. The release script ran only with `--dry-run`, into a `mktemp -d` directory that was then removed. It downloaded the two pinned Litestream 0.5.18 tarballs from GitHub and checked them against `infra/hosted/release-pins.json`. Those digests match GitHub's own asset digests, and I checked the arm64 one again by hand.
+
+RED, with compile stubs (`zz_stubs.go`, since deleted) in place:
+`go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestCloudInit|TestControllerReads|TestKeygen|TestPinWritten|TestHealthz|TestHeartbeat|TestRestoreBeforeStart' -count=1`
+- `TestKeygenWritesPrivate0600` (`keygen -ed25519: stub`) and `TestKeygenRefusesOverwrite` failed.
+- `TestPinWrittenOnce` failed (`ensureTLS: stub`).
+- `TestHeartbeatOnlyAfterCleanPass` and `TestHeartbeatPublishesAlarmMetrics` failed (`namespace "", want EquipoHosted`).
+- `TestHealthzOnMetricsOnly` failed (`metrics /healthz = 404`).
+- `TestCloudInitChecksDigest`, `TestRestoreBeforeStart`, `TestControllerReadsManifest` and `TestCloudInitProxyWaitsForControllerJSON` failed in keygen (`stub`), before any template existed.
+
+GREEN:
+- The command above: both packages `ok`.
+- `go test ./internal/hostedctl ./cmd/equipo-hosted-controller ./internal/isolatedjob -count=1`: `ok`.
+- `scripts/release-hosted.sh --dry-run --out <mktemp -d>/out`: exit 0 in 71 s. It wrote 11 assets and SHA256SUMS (`sha256sum -c` clean) and `hosted-0.0.0.json`. Its notes record the gaps: a dirty tree, no `cmd/equipo-hosted-ops` yet, a plain-built runner (no `--runner-kit`), no IMAGE_DIGEST (no `--image-inputs`) and BaseImageVersion unpinned.
+- `make budget build vet hosted-infra-check`: exit 0. Budget: 141 directories within budget. plan-check: 92 tests OK. Seven roots are valid and all their tofu tests passed.
+- staticcheck on both packages is clean.
+- Both templates render under real `tofu console` `templatefile`.
+
+Budget: `internal/hostedctl` goes from 6050 to 6079 source lines for `healthz.go`, which is wiring only. The reason is recorded in its budget record.
+
+Mutations. Each was applied with a one-line replacement, then the named test was run, then the file was restored and checked identical by SHA-256.
+- **M1** keygen's private key at 0644. `TestKeygenWritesPrivate0600` FAIL: `keygen_test.go:53: keygen -ed25519 wrote .../controller.key at mode -rw-r--r--, want -rw-------`.
+- **M2** pin put without `IfNoneMatch: "*"`. `TestPinWrittenOnce` FAIL: `pin_test.go:111: pin put = key "pins/controller.spki", If-None-Match "", ...`.
+- **M3** read-back comparison skipped (`if false && ...`). `TestPinWrittenOnce` FAIL: `pin_test.go:132: a different pin = <nil>, want a refusal`.
+- **M4** Heartbeat without `last.Err == nil`. `TestHeartbeatOnlyAfterCleanPass` FAIL: `watch_test.go:108: Heartbeat published after a failed reaper pass`.
+- **M5** Heartbeat without the freshness bound. `TestHeartbeatOnlyAfterCleanPass` FAIL: `watch_test.go:121: Heartbeat published 2m1s after the last clean pass`.
+- **M6** `/healthz` not mounted on the metrics mux. `TestHealthzOnMetricsOnly` FAIL: `healthz_test.go:38: metrics /healthz = 404`.
+- **M7** operator keys from operators.json dropped. `TestControllerReadsManifest` FAIL: `cloudinit_test.go:596: operators.json's key is not an operator verify key`.
+- **M8** lib.sh digest check replaced by `if false`. `TestCloudInitChecksDigest` FAIL: `cloudinit_test.go:418: controller mismatch: install succeeded or said nothing of the digest`.
+- **M9** controller install without `wait_for` for the keys. `TestCloudInitChecksDigest` FAIL: `cloudinit_test.go:431: install with a private key absent succeeded or did not name it`.
+- **M10** fetch ExecStartPre removed, so the restore runs first. `TestRestoreBeforeStart` FAIL: `cloudinit_test.go:499: ExecStartPre = [...litestream restore...], want the config fetch (as root) and then the restore`.
+- **M11** `-if-replica-exists` dropped. `TestRestoreBeforeStart` FAIL: `cloudinit_test.go:504: the second ExecStartPre is ...; want litestream restore -if-replica-exists ...`.
+- **M12** env validation replaced by `if false`. `TestControllerReadsManifest` FAIL: `cloudinit_test.go:617: fetch-config took an env object with LD_PRELOAD`.
+- **M13** fetch_or_default defaults on any failure. `TestControllerReadsManifest` FAIL: `cloudinit_test.go:623: fetch-config defaulted an object it could not reach`.
+- **M14** the proxy gives up on the first controller.json miss. `TestCloudInitProxyWaitsForControllerJSON` FAIL: `cloudinit_test.go:706: fetch-proxy did not wait for controller.json`.
+- **M15** the proxy's pin check removed. `TestCloudInitProxyWaitsForControllerJSON` FAIL: `cloudinit_test.go:750: fetch-proxy took controller.json with a pin that is not hex`.
+- **M16** proxy install without `wait_for` for its keys. `TestCloudInitChecksDigest` FAIL: `cloudinit_test.go:457: proxy install with its intercept key absent succeeded or enabled the unit`.
+- **M17** ensureTLS never keeps an existing pair. `TestPinWrittenOnce` FAIL: `pin_test.go:116: ensureTLS: TLS: ... must both exist or neither`.
diff --git a/go.mod b/go.mod
index b9c3cca8..9521c715 100644
--- a/go.mod
+++ b/go.mod
@@ -23,6 +23,7 @@ require (
amadan.net/rastrillo/fiesta v1.6.1
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2/config v1.33.21
+ github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0
github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0
github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0
@@ -37,6 +38,7 @@ require (
github.com/ulikunitz/xz v0.5.15
golang.org/x/crypto v0.55.0
golang.org/x/net v0.58.0
+ gopkg.in/yaml.v3 v3.0.1
)
require (
@@ -122,7 +124,6 @@ require (
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/time v0.15.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
- gopkg.in/yaml.v3 v3.0.1 // indirect
)
require (
diff --git a/go.sum b/go.sum
index a708d8a9..91bd4eee 100644
--- a/go.sum
+++ b/go.sum
@@ -63,6 +63,8 @@ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosIm
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
+github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 h1:RdWMeCVaJfu4hCPyRNVQMKMP/Y5J04zB5LF45DmHhRg=
+github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0/go.mod h1:HfsU8PQ6mHewSJNS77IPAFMZZgFaYSHjAhSOAFXdu9M=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 h1:EjAV+HmAnHedN+iYZF+b4SQYtMGlMdjURLbZc3q32fs=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0/go.mod h1:uMJiOkxaT3pV+LAeAvEaXToZ2x3nEnN53HnPdj+pcNo=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
diff --git a/infra/hosted/README.md b/infra/hosted/README.md
index 455fd575..3e0b100b 100644
--- a/infra/hosted/README.md
+++ b/infra/hosted/README.md
@@ -120,6 +120,54 @@ changing a module or root. plan-check compares the configuration
each proof uses with the source, so a fixture that no longer matches
those parts fails its test.
+## Host configuration
+
+The hosts boot from `modules/controller/cloud-init.yaml.tmpl` and
+`modules/proxy/cloud-init.yaml.tmpl` (slice 2 Task 29), rendered with
+`templatefile`. Their values are all public. Private keys reach a host only
+from the config bucket, never through user data. EC2 takes at most 16 KiB
+of user data; `cmd/equipo-hosted-controller/cloudinit_test.go` renders
+both with real-sized values and holds them 2 KiB under that.
+
+- Controller variables: `release_url` (the release, https, no trailing
+ slash), `controller_sha256`, `litestream_asset`, `litestream_sha256` (from
+ the release manifest), `account_id`, `region`, `config_bucket`,
+ `litestream_bucket`, `verify_keys_json`, `images_json`, `egress_json` and
+ `proxy_routes_json` (one-line JSON), `vpc_id`, `vm_subnet_id`,
+ `vm_security_group_id`, `connector_arn`, `sns_topic_arn`, `peering_id`,
+ `services_vpc_id`, `services_route_table_id`, `egress_manifest_b64` and
+ `client_ca_cert_b64` (base64).
+- Proxy variables: `release_url`, `proxy_sha256`, `account_id`, `region`,
+ `config_bucket`, `proxy_name` (`a` or `b`), `proxy_ip`, `proxy_key_id`,
+ `client_ca_cert_b64` and `intercept_ca_cert_b64`.
+
+First boot runs `install.sh` alone. It downloads the binaries from the
+release by URL and installs them only at their pinned SHA-256. It waits up
+to 15 minutes for the host's private keys in the config bucket, and only
+then enables the units. A digest mismatch or a missing key leaves every
+unit off.
+
+Every start of `equipo-hosted-controller.service` runs two steps first.
+`fetch-config.sh` fetches the `controller/` objects. An absent
+`certificates.json`, `certification-images.json` or `env` gets its closed
+default, and `env` may hold only `EQUIPO_HOSTED_ENABLED=0|1`. Then
+`litestream restore -if-replica-exists -if-db-not-exists` runs. A reboot
+and `POST /v1/admin/restart` (exit 0 under `Restart=always`) both go
+through these steps.
+
+The controller makes its TLS key on first boot and writes its SPKI pin to
+`pins/controller.spki` once. It refuses to start if a different pin is
+already there. `equipo-hosted-litestream.service` replicates the database
+to the Litestream bucket. Its heartbeat to the metrics listener drives
+`litestream_lag_seconds` and `LitestreamLag`.
+
+Every start of `equipo-hosted-proxy.service` fetches the proxy's keys and
+waits up to 15 minutes for `proxy/<name>/controller.json`
+(`{"url", "pin", "key"}`). It checks that file and writes the proxy's
+config from it.
+
+The templates are not yet wired into `aws_instance.user_data`.
+
## Checks
```
diff --git a/infra/hosted/modules/controller/cloud-init.yaml.tmpl b/infra/hosted/modules/controller/cloud-init.yaml.tmpl
new file mode 100644
index 00000000..3e223453
--- /dev/null
+++ b/infra/hosted/modules/controller/cloud-init.yaml.tmpl
@@ -0,0 +1,281 @@
+#cloud-config
+# The controller host's user data (slice 2 Task 29; templatefile). Values
+# are public; private keys come from the config bucket. Variables and the
+# boot order are in infra/hosted/README.md ("Host configuration"). EC2
+# takes at most 16 KiB of user data; the tests hold it under that.
+write_files:
+ - path: /etc/equipo-hosted/release.env
+ permissions: "0644"
+ content: |
+ RELEASE_URL=${release_url}
+ CONTROLLER_SHA256=${controller_sha256}
+ LITESTREAM_ASSET=${litestream_asset}
+ LITESTREAM_SHA256=${litestream_sha256}
+ CONFIG_BUCKET=${config_bucket}
+ ACCOUNT_ID=${account_id}
+ REGION=${region}
+ - path: /etc/equipo-hosted/controller.json.in
+ permissions: "0644"
+ content: |
+ {
+ "listen": "@LISTEN@",
+ "metrics_listen": "127.0.0.1:9090",
+ "tls_cert_file": "/var/lib/equipo-hosted/tls.crt",
+ "tls_key_file": "/var/lib/equipo-hosted/tls.key",
+ "database": "/var/lib/equipo-hosted/db/controller.db",
+ "signing_key_file": "/var/lib/equipo-hosted/config/controller.key",
+ "verify_keys": ${verify_keys_json},
+ "images": ${images_json},
+ "region": "${region}",
+ "vpc_id": "${vpc_id}",
+ "vm_subnet_id": "${vm_subnet_id}",
+ "vm_security_group_id": "${vm_security_group_id}",
+ "connector_arn": "${connector_arn}",
+ "egress": ${egress_json},
+ "sns_topic_arn": "${sns_topic_arn}",
+ "peering_id": "${peering_id}",
+ "services_vpc_id": "${services_vpc_id}",
+ "services_route_table_id": "${services_route_table_id}",
+ "proxy_routes": ${proxy_routes_json},
+ "egress_manifest_file": "/etc/equipo-hosted/egress-manifest.json",
+ "cert_keys_file": "/var/lib/equipo-hosted/config/cert-keys.json",
+ "certificates_file": "/var/lib/equipo-hosted/config/certificates.json",
+ "certification_images_file": "/var/lib/equipo-hosted/config/certification-images.json",
+ "operators_file": "/var/lib/equipo-hosted/config/operators.json",
+ "config_bucket": "${config_bucket}",
+ "config_prefix": "controller/",
+ "proxy_ca_cert_file": "/etc/equipo-hosted/client-ca.crt",
+ "proxy_ca_key_file": "/var/lib/equipo-hosted/config/client-ca.key",
+ "proxy_code_key_file": "/var/lib/equipo-hosted/config/proxy-code.key"
+ }
+ - path: /etc/equipo-hosted/egress-manifest.json
+ permissions: "0644"
+ encoding: b64
+ content: ${egress_manifest_b64}
+ - path: /etc/equipo-hosted/client-ca.crt
+ permissions: "0644"
+ encoding: b64
+ content: ${client_ca_cert_b64}
+ - path: /etc/equipo-hosted/litestream.yml
+ permissions: "0644"
+ content: |
+ heartbeat-url: http://127.0.0.1:9090/litestream/heartbeat
+ heartbeat-interval: 1m
+ dbs:
+ - path: /var/lib/equipo-hosted/db/controller.db
+ replica:
+ type: s3
+ bucket: ${litestream_bucket}
+ path: controller
+ region: ${region}
+ - path: /etc/systemd/system/equipo-hosted-controller.service
+ permissions: "0644"
+ content: |
+ [Unit]
+ Description=Equipo hosted runner controller
+ Wants=network-online.target
+ After=network-online.target
+ StartLimitIntervalSec=0
+
+ [Service]
+ User=equipo-hosted
+ Group=equipo-hosted
+ AmbientCapabilities=CAP_NET_BIND_SERVICE
+ CapabilityBoundingSet=CAP_NET_BIND_SERVICE
+ NoNewPrivileges=yes
+ ExecStartPre=+/usr/local/libexec/equipo-hosted/fetch-config.sh
+ ExecStartPre=/usr/local/bin/litestream restore -config /etc/equipo-hosted/litestream.yml -if-replica-exists -if-db-not-exists /var/lib/equipo-hosted/db/controller.db
+ ExecStart=/usr/local/libexec/equipo-hosted/start-controller.sh
+ Restart=always
+ RestartSec=5
+ TimeoutStartSec=10min
+
+ [Install]
+ WantedBy=multi-user.target
+ - path: /etc/systemd/system/equipo-hosted-litestream.service
+ permissions: "0644"
+ content: |
+ [Unit]
+ Description=Litestream replication of the hosted controller database
+ After=equipo-hosted-controller.service
+ StartLimitIntervalSec=0
+
+ [Service]
+ User=equipo-hosted
+ Group=equipo-hosted
+ NoNewPrivileges=yes
+ ExecStartPre=/usr/bin/test -f /var/lib/equipo-hosted/db/controller.db
+ ExecStart=/usr/local/bin/litestream replicate -config /etc/equipo-hosted/litestream.yml
+ Restart=always
+ RestartSec=10
+
+ [Install]
+ WantedBy=multi-user.target
+ - path: /usr/local/libexec/equipo-hosted/lib.sh
+ permissions: "0644"
+ content: |
+ # EQUIPO_HOSTED_* are for the tests; a host leaves them unset.
+ ROOT=$${EQUIPO_HOSTED_ROOT:-}
+ OWNER=$${EQUIPO_HOSTED_OWNER:-equipo-hosted}
+ WAIT_SECONDS=$${EQUIPO_HOSTED_WAIT_SECONDS:-900}
+ POLL_SECONDS=$${EQUIPO_HOSTED_POLL_SECONDS:-15}
+ ETC=$ROOT/etc/equipo-hosted
+ STATE=$ROOT/var/lib/equipo-hosted
+ CONF=$STATE/config
+ BIN=$ROOT/usr/local/bin
+
+ die() {
+ echo "equipo-hosted: $*" >&2
+ exit 1
+ }
+
+ # release.env is read as data, never sourced; each value checked.
+ load_release_env() {
+ local k v
+ while IFS='=' read -r k v; do
+ case $k in
+ RELEASE_URL) [[ $v =~ ^https://[A-Za-z0-9./_-]+$ ]] || die "RELEASE_URL is not an https URL" ;;
+ *_SHA256) [[ $v =~ ^[0-9a-f]{64}$ ]] || die "$k is not a SHA-256" ;;
+ ACCOUNT_ID) [[ $v =~ ^[0-9]{12}$ ]] || die "ACCOUNT_ID is not an account" ;;
+ LITESTREAM_ASSET | CONFIG_BUCKET | REGION | PROXY_NAME | PROXY_IP | PROXY_KEY_ID)
+ [[ $v =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "$k is malformed" ;;
+ *) die "release.env names $k" ;;
+ esac
+ printf -v "$k" '%s' "$v"
+ done <"$ETC/release.env"
+ [[ -n $RELEASE_URL && -n $CONFIG_BUCKET && -n $ACCOUNT_ID && -n $REGION ]] || die "release.env is incomplete"
+ export AWS_REGION=$REGION AWS_DEFAULT_REGION=$REGION
+ }
+
+ ensure_dirs() {
+ local group
+ group=$(id -gn "$OWNER")
+ install -d -m 0700 -o "$OWNER" -g "$group" "$STATE" "$CONF" "$@"
+ }
+
+ ensure_user() {
+ id -u "$OWNER" >/dev/null 2>&1 ||
+ useradd --system --user-group --no-create-home --home-dir /var/lib/equipo-hosted --shell /sbin/nologin "$OWNER"
+ }
+
+ # download_checked NAME SHA256 DEST: DEST only if NAME has SHA256.
+ download_checked() {
+ local name=$1 sum=$2 dest=$3
+ curl --fail --silent --show-error --location --max-redirs 3 --proto =https --proto-redir =https \
+ --retry 5 --max-time 900 --output "$dest.part" "$RELEASE_URL/$name" || die "downloading $name failed"
+ if ! printf '%s %s\n' "$sum" "$dest.part" | sha256sum --check --strict --status; then
+ rm -f "$dest.part"
+ die "$name does not have its pinned SHA-256 $sum; nothing is installed"
+ fi
+ mv "$dest.part" "$dest"
+ }
+
+ # get_object KEY OUT: 0 fetched, 2 absent (S3 answers AccessDenied for
+ # a missing object to a reader that may not list), 1 any other failure.
+ get_object() {
+ local err
+ err=$(aws s3api get-object --bucket "$CONFIG_BUCKET" --key "$1" --expected-bucket-owner "$ACCOUNT_ID" "$2" 2>&1 >/dev/null) && return 0
+ rm -f "$2"
+ case $err in
+ *NoSuchKey* | *AccessDenied* | *"(404)"* | *"(403)"*) return 2 ;;
+ esac
+ echo "equipo-hosted: s3://$CONFIG_BUCKET/$1: $err" >&2
+ return 1
+ }
+
+ wait_for() {
+ local deadline=$((SECONDS + WAIT_SECONDS)) key
+ for key in "$@"; do
+ until aws s3api head-object --bucket "$CONFIG_BUCKET" --key "$key" --expected-bucket-owner "$ACCOUNT_ID" >/dev/null 2>&1; do
+ ((SECONDS < deadline)) || die "s3://$CONFIG_BUCKET/$key is still absent after $WAIT_SECONDS s; the units stay off"
+ sleep "$POLL_SECONDS"
+ done
+ done
+ }
+
+ # install_private SRC NAME: $CONF/NAME, 0600, replaced in one rename.
+ install_private() {
+ install -m 0600 -o "$OWNER" -g "$(id -gn "$OWNER")" "$1" "$CONF/.$2.new"
+ mv -f "$CONF/.$2.new" "$CONF/$2"
+ }
+ - path: /usr/local/libexec/equipo-hosted/install.sh
+ permissions: "0755"
+ content: |
+ #!/bin/bash
+ # First boot, as root: binaries by digest, keys present, units on.
+ set -euo pipefail
+ . "$(dirname "$0")/lib.sh"
+ load_release_env
+ ensure_user
+ ensure_dirs "$STATE/db"
+ work=$(mktemp -d "$STATE/install.XXXXXX")
+ trap 'rm -rf "$work"' EXIT
+ download_checked equipo-hosted-controller-linux-arm64 "$CONTROLLER_SHA256" "$work/equipo-hosted-controller"
+ download_checked "$LITESTREAM_ASSET" "$LITESTREAM_SHA256" "$work/litestream.tar.gz"
+ mkdir "$work/litestream"
+ tar -xzf "$work/litestream.tar.gz" -C "$work/litestream" litestream || die "$LITESTREAM_ASSET holds no litestream"
+ wait_for controller/controller.key controller/client-ca.key
+ token=$(curl --fail --silent --show-error --request PUT --header "X-aws-ec2-metadata-token-ttl-seconds: 60" \
+ http://169.254.169.254/latest/api/token) || die "no IMDSv2 token"
+ ip=$(curl --fail --silent --show-error --header "X-aws-ec2-metadata-token: $token" \
+ http://169.254.169.254/latest/meta-data/local-ipv4) || die "no private address from IMDS"
+ [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || die "the private address $ip is not IPv4"
+ sed "s/@LISTEN@/$ip:443/" "$ETC/controller.json.in" >"$work/controller.json"
+ install -m 0644 "$work/controller.json" "$ETC/controller.json"
+ install -D -m 0755 "$work/equipo-hosted-controller" "$BIN/equipo-hosted-controller"
+ install -D -m 0755 "$work/litestream/litestream" "$BIN/litestream"
+ systemctl daemon-reload
+ systemctl enable --now equipo-hosted-controller.service equipo-hosted-litestream.service
+ - path: /usr/local/libexec/equipo-hosted/fetch-config.sh
+ permissions: "0755"
+ content: |
+ #!/bin/bash
+ # ExecStartPre, as root: every controller/ object fetched before any
+ # is written; absent optional ones get closed defaults.
+ set -euo pipefail
+ . "$(dirname "$0")/lib.sh"
+ load_release_env
+ ensure_dirs "$STATE/db"
+ work=$(mktemp -d "$STATE/fetch.XXXXXX")
+ trap 'rm -rf "$work"' EXIT
+ for name in controller.key client-ca.key operators.json cert-keys.json; do
+ get_object "controller/$name" "$work/$name" || die "controller/$name could not be fetched"
+ done
+ fetch_or_default() {
+ local rc=0
+ get_object "controller/$1" "$work/$1" || rc=$?
+ case $rc in
+ 0) ;;
+ 2)
+ printf '%s\n' "$2" >"$work/$1"
+ echo "equipo-hosted: controller/$1 is absent; using $2" >&2
+ ;;
+ *) die "controller/$1 could not be fetched" ;;
+ esac
+ }
+ fetch_or_default certificates.json '{"certificates":[]}'
+ fetch_or_default certification-images.json '[]'
+ fetch_or_default env 'EQUIPO_HOSTED_ENABLED=0'
+ if grep -Evq '^(EQUIPO_HOSTED_ENABLED=[01])?$' "$work/env"; then
+ die "controller/env may hold only EQUIPO_HOSTED_ENABLED=0 or EQUIPO_HOSTED_ENABLED=1"
+ fi
+ for name in controller.key client-ca.key operators.json cert-keys.json certificates.json certification-images.json env; do
+ install_private "$work/$name" "$name"
+ done
+ if [[ ! -s $CONF/proxy-code.key ]]; then
+ head -c 32 /dev/urandom | base64 >"$work/proxy-code.key"
+ install_private "$work/proxy-code.key" proxy-code.key
+ fi
+ - path: /usr/local/libexec/equipo-hosted/start-controller.sh
+ permissions: "0755"
+ content: |
+ #!/bin/bash
+ set -euo pipefail
+ . "$(dirname "$0")/lib.sh"
+ enabled=0
+ if grep -qx 'EQUIPO_HOSTED_ENABLED=1' "$CONF/env"; then
+ enabled=1
+ fi
+ EQUIPO_HOSTED_ENABLED=$enabled exec "$BIN/equipo-hosted-controller" -config "$ETC/controller.json"
+runcmd:
+ - [/usr/local/libexec/equipo-hosted/install.sh]
diff --git a/infra/hosted/modules/proxy/cloud-init.yaml.tmpl b/infra/hosted/modules/proxy/cloud-init.yaml.tmpl
new file mode 100644
index 00000000..71ac58a4
--- /dev/null
+++ b/infra/hosted/modules/proxy/cloud-init.yaml.tmpl
@@ -0,0 +1,211 @@
+#cloud-config
+# An egress proxy host's user data (slice 2 Task 29; templatefile).
+# Values are public; the private keys and controller.json come from the
+# config bucket (proxy/<name>/). Variables and the boot order are in
+# infra/hosted/README.md ("Host configuration").
+write_files:
+ - path: /etc/equipo-hosted/release.env
+ permissions: "0644"
+ content: |
+ RELEASE_URL=${release_url}
+ PROXY_SHA256=${proxy_sha256}
+ CONFIG_BUCKET=${config_bucket}
+ ACCOUNT_ID=${account_id}
+ REGION=${region}
+ PROXY_NAME=${proxy_name}
+ PROXY_IP=${proxy_ip}
+ PROXY_KEY_ID=${proxy_key_id}
+ - path: /etc/equipo-hosted/client-ca.crt
+ permissions: "0644"
+ encoding: b64
+ content: ${client_ca_cert_b64}
+ - path: /etc/equipo-hosted/intercept-ca.crt
+ permissions: "0644"
+ encoding: b64
+ content: ${intercept_ca_cert_b64}
+ - path: /etc/systemd/system/equipo-hosted-proxy.service
+ permissions: "0644"
+ content: |
+ [Unit]
+ Description=Equipo hosted runner egress proxy
+ Wants=network-online.target
+ After=network-online.target
+ StartLimitIntervalSec=0
+
+ [Service]
+ User=equipo-hosted
+ Group=equipo-hosted
+ NoNewPrivileges=yes
+ ExecStartPre=+/usr/local/libexec/equipo-hosted/fetch-proxy.sh
+ ExecStart=/usr/local/bin/equipo-hosted-proxy -config /var/lib/equipo-hosted/config/proxy.json
+ Restart=always
+ RestartSec=10
+ TimeoutStartSec=20min
+
+ [Install]
+ WantedBy=multi-user.target
+ - path: /usr/local/libexec/equipo-hosted/lib.sh
+ permissions: "0644"
+ content: |
+ # EQUIPO_HOSTED_* are for the tests; a host leaves them unset.
+ ROOT=$${EQUIPO_HOSTED_ROOT:-}
+ OWNER=$${EQUIPO_HOSTED_OWNER:-equipo-hosted}
+ WAIT_SECONDS=$${EQUIPO_HOSTED_WAIT_SECONDS:-900}
+ POLL_SECONDS=$${EQUIPO_HOSTED_POLL_SECONDS:-15}
+ ETC=$ROOT/etc/equipo-hosted
+ STATE=$ROOT/var/lib/equipo-hosted
+ CONF=$STATE/config
+ BIN=$ROOT/usr/local/bin
+
+ die() {
+ echo "equipo-hosted: $*" >&2
+ exit 1
+ }
+
+ # release.env is read as data, never sourced; each value checked.
+ load_release_env() {
+ local k v
+ while IFS='=' read -r k v; do
+ case $k in
+ RELEASE_URL) [[ $v =~ ^https://[A-Za-z0-9./_-]+$ ]] || die "RELEASE_URL is not an https URL" ;;
+ *_SHA256) [[ $v =~ ^[0-9a-f]{64}$ ]] || die "$k is not a SHA-256" ;;
+ ACCOUNT_ID) [[ $v =~ ^[0-9]{12}$ ]] || die "ACCOUNT_ID is not an account" ;;
+ LITESTREAM_ASSET | CONFIG_BUCKET | REGION | PROXY_NAME | PROXY_IP | PROXY_KEY_ID)
+ [[ $v =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "$k is malformed" ;;
+ *) die "release.env names $k" ;;
+ esac
+ printf -v "$k" '%s' "$v"
+ done <"$ETC/release.env"
+ [[ -n $RELEASE_URL && -n $CONFIG_BUCKET && -n $ACCOUNT_ID && -n $REGION ]] || die "release.env is incomplete"
+ export AWS_REGION=$REGION AWS_DEFAULT_REGION=$REGION
+ }
+
+ ensure_dirs() {
+ local group
+ group=$(id -gn "$OWNER")
+ install -d -m 0700 -o "$OWNER" -g "$group" "$STATE" "$CONF" "$@"
+ }
+
+ ensure_user() {
+ id -u "$OWNER" >/dev/null 2>&1 ||
+ useradd --system --user-group --no-create-home --home-dir /var/lib/equipo-hosted --shell /sbin/nologin "$OWNER"
+ }
+
+ # download_checked NAME SHA256 DEST: DEST only if NAME has SHA256.
+ download_checked() {
+ local name=$1 sum=$2 dest=$3
+ curl --fail --silent --show-error --location --max-redirs 3 --proto =https --proto-redir =https \
+ --retry 5 --max-time 900 --output "$dest.part" "$RELEASE_URL/$name" || die "downloading $name failed"
+ if ! printf '%s %s\n' "$sum" "$dest.part" | sha256sum --check --strict --status; then
+ rm -f "$dest.part"
+ die "$name does not have its pinned SHA-256 $sum; nothing is installed"
+ fi
+ mv "$dest.part" "$dest"
+ }
+
+ # get_object KEY OUT: 0 fetched, 2 absent (S3 answers AccessDenied for
+ # a missing object to a reader that may not list), 1 any other failure.
+ get_object() {
+ local err
+ err=$(aws s3api get-object --bucket "$CONFIG_BUCKET" --key "$1" --expected-bucket-owner "$ACCOUNT_ID" "$2" 2>&1 >/dev/null) && return 0
+ rm -f "$2"
+ case $err in
+ *NoSuchKey* | *AccessDenied* | *"(404)"* | *"(403)"*) return 2 ;;
+ esac
+ echo "equipo-hosted: s3://$CONFIG_BUCKET/$1: $err" >&2
+ return 1
+ }
+
+ wait_for() {
+ local deadline=$((SECONDS + WAIT_SECONDS)) key
+ for key in "$@"; do
+ until aws s3api head-object --bucket "$CONFIG_BUCKET" --key "$key" --expected-bucket-owner "$ACCOUNT_ID" >/dev/null 2>&1; do
+ ((SECONDS < deadline)) || die "s3://$CONFIG_BUCKET/$key is still absent after $WAIT_SECONDS s; the units stay off"
+ sleep "$POLL_SECONDS"
+ done
+ done
+ }
+
+ # install_private SRC NAME: $CONF/NAME, 0600, replaced in one rename.
+ install_private() {
+ install -m 0600 -o "$OWNER" -g "$(id -gn "$OWNER")" "$1" "$CONF/.$2.new"
+ mv -f "$CONF/.$2.new" "$CONF/$2"
+ }
+ - path: /usr/local/libexec/equipo-hosted/install.sh
+ permissions: "0755"
+ content: |
+ #!/bin/bash
+ # First boot, as root: binary by digest, keys present, unit on.
+ set -euo pipefail
+ . "$(dirname "$0")/lib.sh"
+ load_release_env
+ ensure_user
+ ensure_dirs
+ work=$(mktemp -d "$STATE/install.XXXXXX")
+ trap 'rm -rf "$work"' EXIT
+ download_checked equipo-hosted-proxy-linux-arm64 "$PROXY_SHA256" "$work/equipo-hosted-proxy"
+ wait_for "proxy/$PROXY_NAME/proxy.key" "proxy/$PROXY_NAME/intercept.key"
+ install -D -m 0755 "$work/equipo-hosted-proxy" "$BIN/equipo-hosted-proxy"
+ systemctl daemon-reload
+ systemctl enable --now equipo-hosted-proxy.service
+ - path: /usr/local/libexec/equipo-hosted/fetch-proxy.sh
+ permissions: "0755"
+ content: |
+ #!/bin/bash
+ # ExecStartPre, as root: keys, then controller.json (waited for),
+ # checked; nothing is written unless every step passes.
+ set -euo pipefail
+ . "$(dirname "$0")/lib.sh"
+ load_release_env
+ ensure_dirs
+ work=$(mktemp -d "$STATE/fetch.XXXXXX")
+ trap 'rm -rf "$work"' EXIT
+ prefix=proxy/$PROXY_NAME
+ for name in proxy.key intercept.key; do
+ get_object "$prefix/$name" "$work/$name" || die "$prefix/$name could not be fetched"
+ done
+ deadline=$((SECONDS + WAIT_SECONDS))
+ until get_object "$prefix/controller.json" "$work/controller.json"; do
+ ((SECONDS < deadline)) || die "$prefix/controller.json is still absent after $WAIT_SECONDS s"
+ sleep "$POLL_SECONDS"
+ done
+ python3 -I - "$work/controller.json" "$work/proxy.json" "$PROXY_IP" "$PROXY_KEY_ID" <<'PY' ||
+ import base64, json, re, sys
+ src, out, ip, key_id = sys.argv[1:]
+ with open(src) as f:
+ c = json.load(f)
+ if not isinstance(c, dict) or sorted(c) != ["key", "pin", "url"]:
+ sys.exit("controller.json must hold exactly url, pin and key")
+ url, pin, key = c["url"], c["pin"], c["key"]
+ if not isinstance(url, str) or not re.fullmatch(r"https://[A-Za-z0-9.:\[\]-]+", url):
+ sys.exit("controller.json url is not an https origin")
+ if not isinstance(pin, str) or not re.fullmatch(r"[0-9a-f]{64}", pin):
+ sys.exit("controller.json pin is not 64 lower-case hex digits")
+ try:
+ raw = base64.b64decode(key, validate=True)
+ except Exception:
+ raw = b""
+ if len(raw) != 32:
+ sys.exit("controller.json key is not an ed25519 public key in base64")
+ conf = {
+ "egress_listen": ip + ":8443",
+ "boot_listen": ip + ":8444",
+ "controller_url": url,
+ "controller_public_key": key,
+ "controller_tls_pin": pin,
+ "key_id": key_id,
+ "signing_key_file": "/var/lib/equipo-hosted/config/proxy.key",
+ "client_ca_file": "/etc/equipo-hosted/client-ca.crt",
+ "intercept_ca_cert_file": "/etc/equipo-hosted/intercept-ca.crt",
+ "intercept_ca_key_file": "/var/lib/equipo-hosted/config/intercept.key",
+ }
+ with open(out, "w") as f:
+ json.dump(conf, f, indent=2)
+ f.write("\n")
+ PY
+ die "$prefix/controller.json is malformed; the proxy is not started"
+ for name in proxy.key intercept.key controller.json proxy.json; do
+ install_private "$work/$name" "$name"
+ done
+runcmd:
+ - [/usr/local/libexec/equipo-hosted/install.sh]
diff --git a/infra/hosted/release-pins.json b/infra/hosted/release-pins.json
new file mode 100644
index 00000000..21c72680
--- /dev/null
+++ b/infra/hosted/release-pins.json
@@ -0,0 +1,17 @@
+{
+ "BaseImageVersion": "",
+ "Litestream": {
+ "Version": "0.5.18",
+ "Source": "https://github.com/benbjohnson/litestream/releases/download/v0.5.18",
+ "Assets": {
+ "linux/arm64": {
+ "Name": "litestream-0.5.18-linux-arm64.tar.gz",
+ "SHA256": "922a09e6a7ac67f2095571894dc6382e94e1dd4cdd9674883ddf1a8e74ab982d"
+ },
+ "linux/amd64": {
+ "Name": "litestream-0.5.18-linux-x86_64.tar.gz",
+ "SHA256": "d3687b9fd0f2e9426bbd3da828429ff3f1dfc5c9b74d54fdf028e4ee510e7dea"
+ }
+ }
+ }
+}
diff --git a/internal/hostedctl/healthz.go b/internal/hostedctl/healthz.go
new file mode 100644
index 00000000..8594f83c
--- /dev/null
+++ b/internal/hostedctl/healthz.go
@@ -0,0 +1,29 @@
+package hostedctl
+
+import (
+ "database/sql"
+ "net/http"
+)
+
+// Healthz serves GET /healthz: 200 "ok" while the store answers a read,
+// else 503. It is for the metrics listener only (the command mounts it
+// there); the API handler has no such route.
+func (c *Controller) Healthz() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ err := c.store.Tx(r.Context(), func(tx *sql.Tx) error {
+ var one int
+ return tx.QueryRowContext(r.Context(), `SELECT 1`).Scan(&one)
+ })
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ if err != nil {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = w.Write([]byte("store unreadable\n"))
+ return
+ }
+ _, _ = w.Write([]byte("ok\n"))
+ })
+}
diff --git a/scripts/release-hosted.sh b/scripts/release-hosted.sh
new file mode 100755
index 00000000..05d2b31f
--- /dev/null
+++ b/scripts/release-hosted.sh
@@ -0,0 +1,249 @@
+#!/usr/bin/env bash
+# Build the hosted runner release, record every artifact's SHA-256 in a
+# release manifest, and publish it on the forge (slice 2 Task 29).
+#
+# scripts/release-hosted.sh [options] VERSION
+# scripts/release-hosted.sh --dry-run [options] [VERSION]
+#
+# --dry-run build and write everything into --out; publish nothing
+# --out DIR where the release is written (default releases/hosted-VERSION)
+# --runner-kit DIR a runner release kit (make release-runner) of the same
+# commit, whose equipo-runner goes into the image
+# --image-inputs DIR the image's other pinned inputs (bwrap, codex, the Go
+# tarball, pkgs/*.rpm), to build the image and record
+# its digest
+#
+# The release, tag hosted-VERSION, holds:
+# equipo-hosted-controller-linux-arm64, equipo-hosted-proxy-linux-arm64
+# the hosts' binaries (t4g, arm64), which their cloud-init downloads by
+# URL and installs only at the SHA-256 the release manifest records
+# equipo-hosted-image-linux-amd64, equipo-hosted-certify-linux-amd64
+# (and equipo-hosted-ops-linux-amd64 once slice 2 Task 33 exists) the
+# operator's tools
+# equipo-runner, equipo-vm-init, containment.test
+# the image inputs this repository builds (linux/amd64, the MicroVM's
+# architecture), under the names equipo-hosted-image build reads
+# litestream-*.tar.gz the pinned Litestream (infra/hosted/release-pins.json),
+# copied byte for byte after its digest is checked
+# image-manifest.json infra/hosted/image/manifest.json with the
+# release-filled pins set (what equipo-hosted-certify judge -release reads)
+# hosted-VERSION.json the release manifest: every artifact and its
+# SHA-256, IMAGE_DIGEST, BaseImageVersion, Litestream's version and digest
+# SHA256SUMS
+#
+# Publishing follows scripts/publish-renderer.sh: an existing release is
+# only checked, never replaced; otherwise the commit is tagged, the tag
+# pushed, the release created with amadan, and every asset downloaded again
+# and compared byte for byte. A publish builds in a fresh clone of HEAD (as
+# scripts/release-isolated.sh does), needs a clean tree, a runner kit, the
+# image inputs and a pinned BaseImageVersion, and then writes the release
+# manifest to release/hosted-VERSION.json for committing. --dry-run builds
+# in place, so it may run on a dirty tree, and records the gaps instead.
+set -euo pipefail
+
+FORGE=https://amadan.net/oficina/equipo/-/releases
+REPO=oficina/equipo
+AMADAN=${AMADAN:-amadan}
+
+die() { echo "release-hosted: $*" >&2; exit 1; }
+note() { echo "release-hosted: $*" >&2; notes+=("$*"); }
+sum() { sha256sum "$1" | cut -d ' ' -f 1; }
+
+dry=0 out= kit= inputs= version=
+notes=()
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --dry-run) dry=1; shift ;;
+ --out) out=${2:?--out needs a directory}; shift 2 ;;
+ --runner-kit) kit=${2:?--runner-kit needs a directory}; shift 2 ;;
+ --image-inputs) inputs=${2:?--image-inputs needs a directory}; shift 2 ;;
+ -*) die "unknown option $1" ;;
+ *) [[ -z $version ]] || die "one VERSION only"; version=$1; shift ;;
+ esac
+done
+if [[ -z $version ]]; then
+ ((dry)) || die "usage: release-hosted.sh [--dry-run] [--out DIR] [--runner-kit DIR] [--image-inputs DIR] VERSION"
+ version=0.0.0
+fi
+[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "VERSION $version is not MAJOR.MINOR.PATCH"
+tag=hosted-$version
+repo=$(git rev-parse --show-toplevel)
+cd "$repo"
+commit=$(git rev-parse HEAD)
+dirty=false
+[[ -z $(git status --porcelain) ]] || dirty=true
+out=${out:-$repo/releases/$tag}
+mkdir -p "$out"
+out=$(cd "$out" && pwd)
+[[ -z $(ls -A "$out") ]] || die "$out is not empty"
+base=${TMPDIR:-${XDG_CACHE_HOME:-$HOME/.cache}/equipo}
+mkdir -p "$base"
+scratch=$(mktemp -d "$base/release-hosted.XXXXXX")
+trap 'rm -rf "$scratch"' EXIT
+trap 'exit 1' HUP INT TERM
+
+# The build tree: a fresh clone at HEAD for a publish, this checkout for a
+# dry run.
+if ((dry)); then
+ src=$repo
+ [[ $dirty == false ]] || note "dry run of a dirty tree at $commit: the binaries are not a release's"
+else
+ [[ $dirty == false ]] || die "refusing to publish from a dirty tree"
+ src=$scratch/src
+ git clone --quiet --no-hardlinks . "$src"
+ git -C "$src" checkout --quiet --detach "$commit"
+fi
+
+export CGO_ENABLED=0
+build() { # GOARCH NAME PACKAGE
+ echo "release-hosted: building $2 (linux/$1)"
+ (cd "$src" && GOOS=linux GOARCH=$1 go build -trimpath -ldflags "-s -w" -o "$out/$2" "$3")
+}
+build arm64 equipo-hosted-controller-linux-arm64 ./cmd/equipo-hosted-controller
+build arm64 equipo-hosted-proxy-linux-arm64 ./cmd/equipo-hosted-proxy
+build amd64 equipo-hosted-image-linux-amd64 ./cmd/equipo-hosted-image
+build amd64 equipo-hosted-certify-linux-amd64 ./cmd/equipo-hosted-certify
+if [[ -d $src/cmd/equipo-hosted-ops ]]; then
+ build amd64 equipo-hosted-ops-linux-amd64 ./cmd/equipo-hosted-ops
+else
+ note "equipo-hosted-ops is not built: cmd/equipo-hosted-ops does not exist yet (slice 2 Task 33)"
+fi
+build amd64 equipo-vm-init ./cmd/equipo-vm-init
+echo "release-hosted: building containment.test (linux/amd64)"
+(cd "$src" && GOOS=linux GOARCH=amd64 go test -c -trimpath -ldflags "-s -w" -o "$out/containment.test" ./internal/runner/containment)
+
+# The runner: a runner release kit's, built from this commit.
+if [[ -n $kit ]]; then
+ [[ -f $kit/equipo-runner && ! -L $kit/equipo-runner && -f $kit/COMMIT ]] || die "$kit is not a runner release kit"
+ [[ $(cat "$kit/COMMIT") == "$commit" ]] || die "$kit was built from $(cat "$kit/COMMIT"), not $commit"
+ cp "$kit/equipo-runner" "$out/equipo-runner"
+ runner_release=$(basename "$kit")
+elif ((dry)); then
+ build amd64 equipo-runner ./cmd/equipo-runner
+ runner_release=dry-run-$(git rev-parse --short HEAD)
+ note "the runner is a plain go build, not a runner release kit's (pass --runner-kit)"
+else
+ die "a publish needs --runner-kit (make release-runner at $commit)"
+fi
+
+# Litestream, by its pinned digests.
+pins=$src/infra/hosted/release-pins.json
+mapfile -t ls_assets < <(python3 -I -c 'import json, sys
+p = json.load(open(sys.argv[1]))["Litestream"]
+for plat in sorted(p["Assets"]):
+ a = p["Assets"][plat]
+ print(p["Source"] + "/" + a["Name"], a["Name"], a["SHA256"])' "$pins")
+for line in "${ls_assets[@]}"; do
+ read -r url name want <<<"$line"
+ [[ $name =~ ^litestream-[0-9A-Za-z._-]+\.tar\.gz$ && $want =~ ^[0-9a-f]{64}$ && $url == https://* ]] || die "release-pins.json: bad Litestream asset $name"
+ echo "release-hosted: fetching $name"
+ curl --fail --silent --show-error --location --max-redirs 5 --proto '=https' --proto-redir '=https' \
+ --max-time 900 --output "$scratch/$name" "$url" || die "downloading $url failed"
+ [[ $(sum "$scratch/$name") == "$want" ]] || die "$name does not have its pinned SHA-256 $want"
+ mv "$scratch/$name" "$out/$name"
+done
+
+# The image manifest with the release-filled pins, and the image's digest
+# when every input is at hand.
+mkdir -p "$scratch/image"
+cp "$src/infra/hosted/image/Dockerfile.tmpl" "$scratch/image/"
+python3 -I -c 'import json, sys
+m = json.load(open(sys.argv[1]))
+m["RunnerRelease"], m["RunnerSHA256"], m["VMInitSHA256"], m["ContainmentTestSHA256"] = sys.argv[3:7]
+with open(sys.argv[2], "w") as f:
+ json.dump(m, f, indent=2)
+ f.write("\n")' "$src/infra/hosted/image/manifest.json" "$out/image-manifest.json" \
+ "$runner_release" "$(sum "$out/equipo-runner")" "$(sum "$out/equipo-vm-init")" "$(sum "$out/containment.test")"
+cp "$out/image-manifest.json" "$scratch/image/manifest.json"
+image_digest=
+if [[ -n $inputs ]]; then
+ mkdir -p "$scratch/inputs"
+ cp -R "$inputs/." "$scratch/inputs/"
+ cp "$out/equipo-runner" "$out/equipo-vm-init" "$out/containment.test" "$scratch/inputs/"
+ (cd "$src" && go run ./cmd/equipo-hosted-image build -manifest "$scratch/image/manifest.json" -inputs "$scratch/inputs" \
+ -gitleaks-config "$src/.gitleaks.toml" -out "$scratch/image.zip") >&2 || die "the image did not build"
+ image_digest=sha256:$(sum "$scratch/image.zip")
+ echo "release-hosted: image $image_digest"
+else
+ note "IMAGE_DIGEST is not recorded: no --image-inputs"
+fi
+base_version=$(python3 -I -c 'import json, sys; print(json.load(open(sys.argv[1]))["BaseImageVersion"])' "$pins")
+[[ -n $base_version ]] || note "BaseImageVersion is not pinned in infra/hosted/release-pins.json (slice 2 Task 34 confirms one)"
+if ((!dry)); then
+ [[ -n $image_digest && -n $base_version ]] || die "a publish needs the image digest and a pinned BaseImageVersion"
+fi
+
+# The release manifest and SHA256SUMS.
+manifest=$out/$tag.json
+(cd "$out" && ls -1) >"$scratch/assets"
+printf '%s\n' "${notes[@]+"${notes[@]}"}" >"$scratch/notes"
+python3 -I -c 'import json, os, sys, hashlib
+out, assets, notes, pins, image = sys.argv[1:6]
+tag, commit, dirty, dry, url, digest, base, runner = sys.argv[6:14]
+def sha(p):
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for b in iter(lambda: f.read(1 << 20), b""):
+ h.update(b)
+ return h.hexdigest()
+platform = {"equipo-runner": "linux/amd64", "equipo-vm-init": "linux/amd64", "containment.test": "linux/amd64",
+ "image-manifest.json": ""}
+art = []
+for name in open(assets).read().split():
+ p = os.path.join(out, name)
+ plat = platform.get(name)
+ if plat is None:
+ plat = "linux/arm64" if name.endswith(("-linux-arm64", "-linux-arm64.tar.gz")) else "linux/amd64"
+ art.append({"Name": name, "Platform": plat, "SHA256": sha(p), "Size": os.path.getsize(p)})
+ls = json.load(open(pins))["Litestream"]
+m = {"Release": tag, "Commit": commit, "Dirty": dirty == "true", "DryRun": dry == "1", "URL": url,
+ "Artifacts": art, "IMAGE_DIGEST": digest or None, "BaseImageVersion": base or None,
+ "RunnerRelease": runner, "Litestream": ls, "ImageManifest": json.load(open(image)),
+ "Notes": [n for n in open(notes).read().split("\n") if n]}
+with open(os.path.join(out, tag + ".json"), "w") as f:
+ json.dump(m, f, indent=2)
+ f.write("\n")' "$out" "$scratch/assets" "$scratch/notes" "$pins" "$out/image-manifest.json" \
+ "$tag" "$commit" "$dirty" "$dry" "$FORGE/$tag" "$image_digest" "$base_version" "$runner_release"
+(cd "$out" && sha256sum -- * >"$scratch/SHA256SUMS" && mv "$scratch/SHA256SUMS" SHA256SUMS)
+echo "release-hosted: wrote $tag into $out ($(wc -l <"$out/SHA256SUMS") assets with SHA256SUMS)"
+
+if ((dry)); then
+ echo "release-hosted: dry run; nothing published"
+ exit 0
+fi
+
+# Publish, as publish-renderer.sh does.
+fetch() { # NAME DEST -> HTTP status
+ curl --silent --show-error --location --max-redirs 1 --proto '=https' --proto-redir '=https' \
+ --max-time 1800 --output "$2" --write-out '%{http_code}' "$FORGE/$tag/$1"
+}
+check_into() {
+ local dir=$1 name status
+ for name in $(cd "$out" && ls -1); do
+ status=$(fetch "$name" "$dir/$name") || die "downloading $tag/$name failed"
+ [[ $status == 200 ]] || die "$FORGE/$tag/$name answered $status"
+ cmp -s "$dir/$name" "$out/$name" || die "the published $tag/$name is not $out/$name"
+ done
+ echo "release-hosted: $tag on the forge matches $out"
+}
+mkdir -p "$scratch/check"
+status=$(fetch SHA256SUMS "$scratch/check/existing") || die "asking the forge for $tag failed"
+if [[ $status == 200 ]]; then
+ check_into "$scratch/check"
+ exit 0
+fi
+[[ $status == 404 ]] || die "$FORGE/$tag/SHA256SUMS answered $status"
+remote=$(git ls-remote --tags origin "refs/tags/$tag" | cut -f 1)
+if [[ -z $remote ]]; then
+ git tag "$tag" "$commit" 2>/dev/null || [[ $(git rev-parse "$tag^{commit}") == "$commit" ]] || die "a local tag $tag names another commit"
+ git push origin "refs/tags/$tag"
+elif [[ $remote != "$commit" ]]; then
+ die "the forge's tag $tag names $remote, not $commit"
+fi
+printf '%s\n' "Hosted runner release $version: the controller, the proxy, the image inputs and the operator tools. Each file's SHA-256 is in SHA256SUMS and $tag.json." >"$scratch/notes.md"
+mapfile -t files < <(cd "$out" && ls -1 | sed "s|^|$out/|")
+"$AMADAN" release create -repo "$REPO" -notes-file "$scratch/notes.md" "$tag" "${files[@]}"
+check_into "$scratch/check"
+mkdir -p "$repo/release"
+cp "$manifest" "$repo/release/$tag.json"
+echo "release-hosted: commit release/$tag.json, the release manifest the account plan reads"