Skip to content

feat(launcher): fetch the static bootstrap body per release behind a verifying stub (#1274, PR A) - #1290

Merged
scttfrdmn merged 5 commits into
mainfrom
feat/1274-release-bootstrap-body
Oct 24, 2026
Merged

scttfrdmn merged 5 commits into
mainfrom
feat/1274-release-bootstrap-body

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1274

PR A of the owner-approved hybrid design: the static bootstrap body is published per release beside spored and fetched by a verifying stub. PR B (staged task wrapper and flush hook) follows. Nothing here is deployed, released or run against AWS.

What changed

  • pkg/launcher: BuildLinuxBootstrap is now prefix + per-launch-pre + (body | stub) + per-launch-post.
    • The static body (BootstrapBody()) is the stripped verified-install funcs, the spot-check func, linuxBootstrapBody and the spot-replacement stop, in today's order.
    • The completion-file placeholder is now the shell variable SPAWN_CMD_COMPLETION_FILE, assigned in the prefix. The name avoids SPAWN_COMPLETION_FILE, which the queue runner already uses.
    • The stub: per-launch vars, KeySetupScript, then the per-launch files (command, flush hook, gates, plugins.json, so Linux bootstrap writes /etc/spawn/plugins.json after starting spored, which reads it only at startup #1023 order holds), then fetch spawn/versions/<v>/bootstrap.sh + .sig from spawn-binaries-<IMDS region> (us-east-1 fallback, 4 tries per source, only curl 7.61-safe flags). It requires the sha256 this build expects (pinned, which also refuses another release's validly-signed body) and openssl dgst -sha256 -verify against the embedded key. Then . /etc/spawn/bootstrap-body.sh, then the post-body inline parts.
    • On failure it runs nothing from the body, writes the reason to stderr/cloud-init-output, /dev/console and logger -p user.crit -t spawn-bootstrap, and then terminates the instance (spawn_fatal_retire, defined in the prefix), so a boot without spored does not keep billing with no TTL.
    • The terminate uses the role's existing TerminateOnlySelf grant (ec2:TerminateInstances with aws:ARN == ${ec2:SourceInstanceARN}, in every spored role via sporedSelfManagementStatements). Instance ID and region come from IMDSv2. It makes 3 tries, bounded by --cli-connect-timeout 10 --cli-read-timeout 30, sleeping 5 s between them.
    • If there is no aws CLI, no instance ID, or no permission, it falls back to shutdown -h now (then poweroff). spawn sets no InstanceInitiatedShutdownBehavior, so that stops the instance rather than terminating it; both the log line and the code comment say so.
    • The inline bootstrap had the same leak: "spored install failed" and "Unsupported architecture" did exit 1 and left the instance running with no spored. Both now go through spawn_fatal_retire (a separate commit).
  • Version pinning: launcher.CallerVersion is set by the CLI's Execute, next to aws.CallerVersion. Library callers (lagotto, MCP) use the spawn module version from debug.ReadBuildInfo().Deps, and a replaced module counts as no version. Only a strict X.Y.Z gets the stub. Dev, pseudo-version and +dirty builds, builds with no signing key, and BootstrapConfig.InlineBody: true get today's inline bootstrap.
  • Generator: a hidden spawn bootstrap-body command, not a go:generate tool. The release runs dist/spawn_linux_amd64_v1/spawn bootstrap-body, so the published bytes come from the exact binary users install. Its stub pins sha256(launcher.BootstrapBody()), so the two cannot disagree.
  • release.yaml: the body is published before GoReleaser publishes the CLI and taps, so no installable spawn exists without its body.
    • A new credentials step and the "Publish the bootstrap body to S3" step run after the version guard. The body is generated from the tagged source with go run -ldflags "-X github.com/spore-host/spawn/cmd.Version=${VERSION}" . bootstrap-body, written to $RUNNER_TEMP (GoReleaser refuses a dirty tree). It is sha256'd, KMS-signed (DIGEST, same key and format as spored) and uploaded to every bucket.
    • The bucket list is now a job-level SPAWN_BINARY_BUCKETS, shared with the spored upload so the two cannot drift.
    • The step fails if the signing key is unset, generation fails or prints nothing, KMS returns nothing, or any copy fails.
    • After GoReleaser, "Check the released spawn prints the published body" (if: !cancelled()) requires the sha256 of dist/spawn_linux_amd64_v1/spawn bootstrap-body to equal the published one, or the job fails with ::error::.
  • Fold-ins:
    • cmd/app.go, lambda/pipeline-orchestrator/main.go and cmd/upgrade_spored.go now splice shellmin.Strip(KeySetupScript())+shellmin.Strip(VerifiedInstallFunc()).
    • cmd/resume.go now uses encodeUserDataForOS. It was base64 of the raw script, 25,389 B decoded / 33,852 B base64, so RunInstances refused every resumed Linux member. That is a real, previously unnoticed bug.

Objects the release publishes per bucket (new)

For each of the 11 buckets spawn-binaries-{us-east-1,us-east-2,us-west-1,us-west-2,ca-central-1,eu-west-1,eu-west-2,eu-central-1,ap-southeast-1,ap-southeast-2,ap-northeast-1}:

  • spawn/versions/<VERSION>/bootstrap.sh: exactly spawn bootstrap-body output (no trailing newline added)
  • spawn/versions/<VERSION>/bootstrap.sh.sig: base64 DER ECDSA_SHA_256 over the body's SHA-256 digest (KMS --message-type DIGEST), the same format as spored's .sig
  • spawn/versions/<VERSION>/bootstrap.sh.sha256: bare hex digest

That is 3 objects × 11 buckets = 33 new objects. The existing spored objects are unchanged. To verify: sha256sum should equal .sha256; it should also equal sha256(spawn bootstrap-body) from the released binary; and base64 -d < .sig > sig.der && openssl dgst -sha256 -verify <SigningKeyPEM> -signature sig.der bootstrap.sh.

Live-test finding fixed here: spored never started on a t4g.nano

In the parent's live test (9.9.9 body in us-west-2, dev account), the stub fetch, sha256 and KMS signature check all worked on real instances, and the 9.9.8 negative (no body) self-terminated in 29 s. The test also exposed a pre-existing bootstrap bug, present in every current release:

  • On t4g.nano (0.5 GiB), dnf was OOM-killed at body line 494, dnf install -y acpid 2>/dev/null || yum install -y acpid 2>/dev/null || true, which was tolerated.
  • Line 495, systemctl enable --now acpid, then FAILED because acpid was absent, and set -e aborted the body.
  • systemctl start spored (line 534) never ran.
  • The task's --command, started earlier in the background, still ran and uploaded its records. But the instance stayed RUNNING with no spored, so no TTL and no on-complete terminate; it had to be terminated by hand.

Fixed in aba223b:

  • spored starts right after its verified install, ahead of the user, session-timeout, array/sweep, hostname, --command, MOTD and acpid steps. plugins.json is still written before spored (Linux bootstrap writes /etc/spawn/plugins.json after starting spored, which reads it only at startup #1023), and the Spot-replacement stop still ends the body.
  • acpid is optional: a failed install or enable is reported, not fatal.
  • Safety net: an EXIT trap, installed in the prefix next to spawn_fatal_retire, retires the instance on any exit before SPAWN_SPORED_UP=1, which is set after systemctl start spored succeeds. The message names the last failed command, recorded by an ERR trap.
    • The trap only acts in the main shell (BASHPID check), and spawn_fatal_retire clears it so it cannot run twice.
    • Background subshells don't run the parent's EXIT trap (bash semantics; checked).
    • Scripts after the body run once spored is up, so their failures don't retire.
  • The behaviour-equivalence gate is unchanged: the reorder is inside the body, which both paths share. Two existing order tests now state the new intent:
    • TestSporedStartsBeforeTheCommandWhichStaysBackgrounded replaces the spored#65 "command before spored" guard; the command must still be backgrounded.
    • The Spot-replacement tail test now starts at the stop script instead of at systemctl start spored.

Sizes (gzip, as EC2 counts)

before after (stub, release build) after (inline, dev)
bare launch 7,253 1,771 7,870
trivial spawn task run (bash -c 'echo hi') 9,324 3,968 9,937

The inline path grows by the variable assignment, the self-terminate function and the exit guard (about 600 B gz). The stub budget is still 3 KiB.

Gates (each watched failing against a revert that compiles)

  • TestStubWithThePublishedBodyIsTheInlineBootstrap: the stub with its fetch block replaced by BootstrapBody() must match the inline bootstrap command for command (mvdan tree with function decls hoisted; the test also checks that nothing before the body calls a body function). It covers 7 configs: plain, key+command, task+flush hook, plugins, storage+gates, container, custom user data. Revert: per-launch-pre moved after the stub, which fails 4 configs.
  • TestStubRunsOnlyAVerifiedBody: runs the real stub under bash against an httptest bucket/IMDS, with the real curl+openssl and a test P-256 key. The PATH holds only the needed tools plus stand-ins for sleep, logger, aws, shutdown and poweroff, so nothing real can be called.
    • Every failure case must log to stderr, console and journal, and make exactly one ec2 terminate-instances --region eu-west-1 --instance-ids i-0test.
    • Two more cases: aws failing (3 tries, then shutdown -h now, with "STOPS" in the log) and no aws CLI (shutdown).
    • Reverts for the self-terminate: no terminate, no shutdown fallback, a single try, and the stub abort as a plain exit 1.
  • TestSporedStartsAndNoFailureLeavesAnInstanceWithoutIt runs the whole inline bootstrap, with a test-key-signed fake spored served from the stand-in bucket, OOM-killed dnf/yum, and stand-ins for systemctl, useradd, su and the rest. Cases:
    • (a) acpid failing: spored still starts, no retire, and the custom user data runs.
    • (b) daemon-reload or start spored failing: retired, with the failing line named.
    • (c) a --command that exits 3 in the background: no retire, and the failure is recorded in SPAWN_COMPLETE.
    • (d) a normal boot: no retire.
    • Reverts, each failing: the original order with a fatal acpid enable (fails a); no EXIT trap (fails b); the guard ignoring SPAWN_SPORED_UP (fails a, c, d); no SPAWN_SPORED_UP=1 (fails a, c, d).
    • Removing the BASHPID check does not fail (c), because bash already doesn't run an EXIT trap in subshells. The check is defence in depth.
  • TestInlineBootstrapRetiresAnInstanceWithoutSpored: the real inline bootstrap against an empty bucket (install fails, terminating or with a failing terminate) and with a stand-in uname returning sparc64. Reverts: each abort back to exit 1. It covers 11 cases plus a retry case: good, regional tampered → fallback, tampered, bad sig, another release's body validly signed, no sig, nothing, non-DER sig, empty regional object, foreign key, and us-east-1 tampered with regional good. Reverts, each failing the relevant cases:
    • sig check → if true
    • sha continue removed
    • abort → || true
    • single try
    • no fallback
  • TestStubBootstrapFitsItsBudget (3 KiB). Revert: the body inlined into the stub path gives 7,895 > 3,072.
  • TestStubIsTheDefault, TestPublishedBodyVersion (12 cases). Revert: _ = PublishedBodyVersion().
  • TestEveryBootstrapCallerGetsTheStub: AST walk of all non-test Go. It finds every BuildLinuxBootstrap call (fails on fewer than 4) and every InlineBody key or assignment. Reverts: InlineBody: true in burst.go, and bc.InlineBody = true in provision.go.
  • TestExecuteTellsTheLauncherItsVersion and TestBootstrapBodyCommandPrintsThePublishedBody. Reverts: assignment removed, and Fprintln.
  • TestEverySplicedInstallerIsStripped: AST walk; every sporedinstall.VerifiedInstallFunc()/KeySetupScript() outside pkg/sporedinstall must be the direct argument of shellmin.Strip. Reverts: app.go, and orchestrator.
  • TestReleasePublishesTheBodyBeforeTheCLI: in step order, credentials precede the body step, which precedes GoReleaser, which precedes the check step (!cancelled()). Revert: the body block moved after GoReleaser.
  • TestReleasePublishesTheSignedBootstrapBodyBesideSpored, ...FailsWithoutASignedBootstrapBody, ...FailsWhenTheShippedBodyDiffers: these execute the body, spored and check steps' run: with the job env, a stand-in go, aws (fake KMS, and s3 cp into a mirror with a region check) and a dist spawn.
    • The body must reach exactly the buckets spored reaches, with exact bytes, KMS sig and sha256, generated with the version ldflag, and nothing may be written into the checkout.
    • A missing key or a failing generation must fail with nothing published.
    • A shipped binary that prints a different body must fail the check.
    • Reverts: .sig upload dropped, key check off, mismatch check off, version ldflag dropped.
  • TestResumedSweepUserDataFitsEC2. Revert to raw base64: 25,389 > 16,384.
  • Shellcheck: stub+sourced body checked for minimal/full configs. bodyStubTemplate was added to the strip-safety template set.

Checks

  • make check passes except check-build-tags, which fails identically on unmodified origin/main (the /private/tmp path issue; verified in a throwaway worktree).
  • make lint: 0 issues in all 10 modules.
  • make check-docs: no drift (the command is hidden).
  • semgrep --config=auto --error: exit 0.
  • make api-snapshot: committed. Additions only: BootstrapConfig.InlineBody, BootstrapBody, BootstrapBodyName, BootstrapBodyKey, PublishedBodyVersion, CallerVersion.

Not verified (needs AWS or a release)

  • That spawn/versions/* is anonymously readable in all 11 buckets. upgrade-spored already fetches versioned objects anonymously over HTTPS, which suggests it is, but I made no AWS call.
  • That the KMS key named by SPORED_SIGNING_KEY_ID matches sporedinstall.SigningKeyPEM. This is already true for spored, and the body uses the same path.
  • A live boot of each shape (plain, task, Provision) on a release build.
  • The body now lands before the CLI does. spored's own upload still runs after GoReleaser, as before; that is unchanged here.
  • That the instance's role has TerminateOnlySelf when the caller supplied their own instance profile. Without it, the fallback is a shutdown, which stops the instance.
  • Downstream: lagotto, spore-host-mcp and calque get the stub once they pin a spawn release with this change. Their tests that assert bootstrap content (spored install strings) would need InlineBody or updating.

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.33333% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/resume.go 37.50% 4 Missing and 1 partial ⚠️
pkg/launcher/bootstrap.go 96.49% 1 Missing and 1 partial ⚠️
cmd/root.go 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…verifying stub

A release build's user data now carries a small stub instead of the static
spored/lifecycle bootstrap body. The release workflow publishes the body,
printed by the release's own spawn binary (hidden `spawn bootstrap-body`) and
KMS-signed with the spored signing key, as spawn/versions/<v>/bootstrap.sh
(+ .sig, .sha256) in all 11 spawn-binaries buckets. The stub fetches it from
the regional bucket (us-east-1 fallback, retries), requires both the sha256
the build expects and a valid signature against the compiled-in key, and
aborts loudly (stderr, console, journal) before running anything otherwise.
Per-launch content stays inline in the same order around the body.

Dev/pseudo-version builds, builds without a signing key, and callers setting
BootstrapConfig.InlineBody keep the inline bootstrap. The completion file is
now a shell variable so the body has no per-launch text.

Fold-ins: strip the verified installer at the app, pipeline-orchestrator and
upgrade-spored splice sites; spawn resume now gzips its user data (it was
25 KB raw base64, over EC2's limit).

Bare launch 7253 -> 1222 bytes gz; trivial task 9324 -> 3454.

Refs #1274
…ance

An aborted stub left a running instance with no spored, so nothing enforced
its TTL. spawn_fatal_retire (defined in the bootstrap prefix) logs to stderr,
console and journal, then self-terminates via the role's TerminateOnlySelf
grant (aws:ARN == ${ec2:SourceInstanceARN}) with IMDSv2 instance ID and
region, 3 bounded tries; failing that it shuts down, which STOPS the instance
since spawn sets no InstanceInitiatedShutdownBehavior.

Refs #1274
… instance too

'spored install failed' and 'Unsupported architecture' exited 1 and left the
instance running with no spored and so no TTL enforcement: the same leak.
Both now go through spawn_fatal_retire.

Refs #1274
…he CLI

The body is generated from the tagged source (go run with the release's
version ldflag) into RUNNER_TEMP, KMS-signed and uploaded to every
SPAWN_BINARY_BUCKETS bucket (now a job env shared with the spored upload)
before GoReleaser runs, so no installable spawn exists without its body.
After GoReleaser, the shipped linux binary's 'spawn bootstrap-body' must match
the published sha256 or the job fails. Also drops an unused exported const
from the previous commit and records the self-terminate in the CHANGELOG.

Refs #1274
…spored exit

Live test of #1290 on a t4g.nano: dnf was OOM-killed installing acpid, the
following `systemctl enable --now acpid` failed under set -e, and the body
ended before `systemctl start spored`, while the backgrounded --command ran
on with no spored, TTL or on-complete. The inline bootstrap had the same lines.

- spored's unit and start now follow its verified install directly, ahead of
  the user, session-timeout, array/sweep, hostname, --command, banner and
  acpid steps (plugins.json is still written before it, #1023; the Spot
  replacement stop still ends the body).
- acpid is optional: install failure and enable failure are reported, not
  fatal.
- An EXIT trap installed with spawn_fatal_retire in the prefix retires the
  instance on any exit before SPAWN_SPORED_UP=1 (set after systemctl start
  spored), naming the last failed command (ERR trap). Only the main shell
  (BASHPID), and spawn_fatal_retire clears it to avoid re-entry.

Refs #1274
@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Live-tested on the head commit aba223b (dev account, us-west-2, 2026-10-24). I built a throwaway version 9.9.9, KMS-signed its body, and published it to spawn-binaries-us-west-2/spawn/versions/9.9.9/ only. All three objects were deleted afterwards.

Leak check: no instances, no available volumes.

@scttfrdmn
scttfrdmn merged commit 7a38162 into main Oct 24, 2026
9 checks passed
@scttfrdmn
scttfrdmn deleted the feat/1274-release-bootstrap-body branch October 24, 2026 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant