Skip to content

Latest commit

 

History

History
503 lines (464 loc) · 44 KB

development.md

File metadata and controls

503 lines (464 loc) · 44 KB

Developing on vm-manager

make build            # binary for the current platform (./vm-manager)
make test             # unit + contract tests, race detector when a C toolchain is present
make test-race        # the same with -race forced
make test-integration # tests tagged `integration`: real QEMU + OVMF + swtpm and the host's storage provider; each skips where its dependency is absent
make lint             # golangci-lint v2 with the pre-commit linters (gosec, goconst, govet)
make agent            # static guest binary bin/vm-agent (attest, pcrs, version); asserted static with file(1) and ldd(1)
make image            # mkosi build of the base image into images/build/ (dev keys generated on first use)
make dev-signing-key  # once per machine: the build key that signs local guest image pushes; `make` compiles its public key into the binaries it builds
make image-verify     # offline checks of the built artifacts (GPT, UKI sections, expected PCR 11 and 13, hwdb, presets, sysext)
make e2e              # tests tagged `e2e` on KVM with the built image (go test -tags e2e -count=1 -timeout 45m -v ./e2e/...)
make serve            # go run . -v serve (SERVE_ARGS="--listen 127.0.0.1:18080" to override)
make help             # every target with its description

make image is make -C images keys base; the Kubernetes sysext and the full artifact set come from make -C images (see images/README.md). The image build stages bin/vm-agent itself (images/Makefile runs make -C .. agent), so a changed agent changes the initrd and with it PCR 11.

Each checkout builds into its own images/build/, with its own development keys: a build that generates new keys changes the PCR 11 values another build expects, so concurrent builds (several worktrees) never share a directory. A checkout that only runs the end-to-end tests points VM_MANAGER_E2E_IMAGE_DIR at another checkout's build instead of building. A new checkout starts from another one's package cache with unshare -Ur cp -a <other checkout>/images/mkosi.cache images/; a plain cp fails on the mode-4110 files mkosi leaves, which the user namespace's root can read. A plain rm -rf of a checkout that built an image fails on files mkosi left in images/build/; sudo rm -rf removes them.

End-to-end tests

make e2e runs the tests below sequentially on the host's KVM against images/build (VM_MANAGER_E2E_IMAGE_DIR points elsewhere); the whole suite takes about 6 min on the development host and go test gets a 45 m ceiling. A host without /dev/kvm, /dev/vhost-vsock, qemu-system-x86_64, swtpm 0.8+, vm-manager's own firmware (make firmware fetches it into firmware/build, VM_MANAGER_E2E_FIRMWARE_DIR points elsewhere), sfdisk or the artifacts skips with a message naming what is missing (e2e/doc.go), and TestHostIsolation skips without Docker; ssh into the guests is dialed over AF_VSOCK from Go, so no ssh client or systemd-ssh-proxy is needed. Every test prints its timings as <name>_seconds= lines; the numbers below are the last full run on the development host.

Test Drives Proves Measured
TestInstallBoot QEMU directly (internal/runtime/qemu, internal/tpm) with user networking, booted as a machine vm-manager did not start (SMBIOS vendor vm-manager-e2e, no IMDS) installer boot, sysinstall onto a blank disk, partition UUIDs, installed boot to READY=1 with the hostname and machine ID it was passed and no credential file on its ESP, ssh over vsock install_seconds=12, boot_to_ready_seconds=11-15
TestInstallBootSystemdBoot as TestInstallBoot, the installer booted through systemd-boot from a copy of the base DDI instead of -kernel (the firmware's fallback) sysinstall finds the UKI on the ESP automounted at /boot and installs; the rest as TestInstallBoot as TestInstallBoot
TestNetworkIMDS vm-manager serve as a child process through /mcp, the image directory without its sysupdate tree create_network, create_vm with wait_for: ready and no Kubernetes version; hostname, ssh key and instance id from the IMDS; is-system-running clean, vm-kubernetes.service succeeded on the missing /kubernetes-version; no TCP or UDP listener on 22, 5353 or 5355, sshd only on its vsock socket and refusing passwords, resolved without LLMNR and mDNS; systemd-report upload arrived; forward_port serves a listener the test starts and reaches no sshd on 22; delete_vm, delete_network, SIGTERM leave no qemu or swtpm api_install_seconds, api_boot_to_ready_seconds in the same range
TestNetworkIMDSOverlappingCIDRs vm-manager serve through /mcp two networks with one CIDR, a VM with its own user-data on each at the same address: each applied its own user-data and reads its own instance id and hostname from the IMDS every time, both attest with their own keys 60 s for two VMs
TestNetworkIMDSUserDataGone MCP attested user-data applied by Ignition, then consumed: userDataConsumedAt recorded, no file below the VM's state directory holds it, /user-data answers 410 from the guest; after reboot_vm the boot attests again, Ignition stays idle, what it wrote is there and /user-data is still 410 46 s
TestIgnition MCP user-data as Ignition JSON: the first installed boot applies its files and unit from the initrd stages, a reboot leaves Ignition idle first installed boot
TestHostIsolation vm-manager serve as root in its container image built from the Dockerfile (--launcher process, the chart's security context), through MCP three VMs, two of them on one network, reach READY=1; from /proc/<pid>/status each VM's QEMU and swtpm run as the VM's own uid and group, distinct per VM, with every capability set empty, NoNewPrivs, QEMU under two seccomp filters (its -sandbox and the io_uring denial) and its network's group; as one VM's user inside the container, the other VM's variable store, vTPM state, disk, port and processes, the port of its neighbour on its own network, and vm-manager's record and key of the VM itself are out of reach VM boot times as TestNetworkIMDS
TestPersistentEtc MCP a file and an enabled unit in /etc survive reboot_vm; host key and machine ID unchanged; var unmounted cleanly (no recovering journal); a reboot from inside the guest comes back ready as a new QEMU process reboot_to_ready_seconds=11
TestKubernetesSysext MCP lockdown at confidentiality (root cannot open /dev/port or /proc/kcore) and kptr_restrict 1 (zeros in /proc/net/unix without CAP_SYSLOG); vm-kubernetes.service pulls the sysext, merges it, containerd and kubelet up, PCR 13 equals policy.json, the root's and the sysext's verity devices verified by the kernel, the Cilium CNI sysext's cilium-cni executes from /usr/lib/cni, cgroup2 is at /sys/fs/cgroup and its sysctl drop-in sets rp_filter 0 on all and on a new lxc* link; with IPE, a copy of cilium-cni in /opt/cni/bin is refused, a sysext file executes but is refused as a kernel module and firmware by IPE and as a kexec image (by kexec_load_disabled, before IPE) while the base root's modules load kubernetes_pull_seconds=2, kubernetes_unit_seconds=2.7
TestGuestNoLogin MCP no getty and no debug shell can start (masked), emergency and rescue mode run no shell, no getty or login process; after root appends systemd.imds=no systemd.debug_shell rd.systemd.debug_shell to the loader entry and reboot_vm, systemd still starts the attestation units, a quote is rejected naming that command line and the boot is killed, its console showing the initrd's attestation unit started and no root shell one install, two boots
TestIPE QEMU directly, as TestInstallBoot, with the image certificate in the VM's db the IPE policy active and enforcing, the certificate on .platform, the root opened with its signature; a copy of an image binary does not run from /var/tmp, /etc, /run, /tmp or /root, nor does a script on var (bash reading it does); no CAP_MAC_ADMIN anywhere, usermode helpers included, so root can neither switch enforcement off (a core_pattern helper tries) nor load a policy; the policy, from the initrd's /run/ipe, pins every operation but EXECUTE to the image's root hash; the layer keyring flags on the command line, kexec off, the .dm-verity keyring sealed with the image's Giant Swarm layer certificate alone, a key from the root refused; after a reboot that root prepared (a mask for the policy in /etc/ipe, a manager drop-in restoring the capability) both are dropped, and var was unmounted cleanly through the exitrd 42 s for install and two boots
TestAttestation servers in turn over a private policy.json: without golden values, after vm-manager image golden recorded them (also a VM with two layer_certificates), on a distribution's Secure Boot build of OVMF in place of vm-manager's a VM of a policy without golden values killed at its initrd quote (no golden value), user-data never released; the recording reproduces the suite's values bit for bit and names golden_firmware; verified initrd and ready quotes, user-data applied; both layer certificates and the Giant Swarm one in the sealed .dm-verity keyring, both digests in the ready verdict (PCR 15), a further layer-certificate: measurement from the root rejected naming the digest and the VM killed; golden mismatch on PCR 0 with the other firmware, naming the recorded build, the VM killed before user-data is released about 3 min
TestAttestationSkipped MCP a boot that skips vm-agent-attest.service is killed and the VM failed, never ready: a loader entry with systemd.imds=no, a loader entry masking the unit on the kernel command line, a mask in the persistent /etc (the initrd quote verifies, the ready quote never comes) three VMs, each installed and rebooted
TestAttestationKeyCertified MCP, a second server on the same state every attestation key is certified against the VM's own endorsement key: two VMs' records hold the TCG RSA EK vm-manager read from each vTPM before its first QEMU, another per VM, and every verdict of their first boots names the key certified against it; one VM's record given the other's EK, its next boot recovers no challenge's nonce (the agent's TPM2_ActivateCredential fails on the console), posts no quote and is refused, never released its user-data two VMs to ready, one refused boot
TestBootConfigAttestation MCP PCRs 1 and 5: the first installed boot verifies and records the VM's boot configuration (bootConfig: BootOrder, the Boot#### options, loader.conf), a reboot_vm verifies against it; then a VM per change root makes, each refused at its next boot (killed, failed, never ready): the description of the boot option bootctl installed changed through efivarfs, rejected naming the option; an empty B slot retyped with sfdisk, rejected as a partition the image does not define; an option added to loader.conf, rejected naming it three VMs, install and two boots each
TestKernelCommandLineAttestation MCP The ESP: the first installed boot runs with Secure Boot on (ignition.firstboot through the stub's SMBIOS extra) and verifies at both stages, as does a reboot_vm. Then a VM per change root makes to the ESP, each refused at its next boot (killed, failed, never ready): options <command line> ipe.enforce=0 appended to the loader entry, which the stub ignores under Secure Boot while systemd-boot measures it, rejected naming PCR 12 and the option with PCR 11 unchanged; a credential added to the entry, rejected on PCR 12; an extension image, its initrd quote rejected on PCR 13 three VMs, install and two boots each
TestKubernetesCluster MCP plus the host's kubectl through forward_port 6443 on the IPE image with kernel lockdown at confidentiality: control plane from CAPI 1.14-shaped Ignition (ExecStart=/bin/bash /etc/kubeadm.sh, ordered After=vm-kubernetes.service), every image from gsoci through a mirror on the host holding copies signed with the build's key, Cilium from cilium-app, a worker joined with a bootstrap token, two Ready nodes with giantswarm-vm:// providerIDs, cross-node DNS, clean units and unmanaged CNI links; on the worker a pod of an image signed with the Giant Swarm key (running as a user named in the image's /etc/passwd) and one signed with the installation's key (layer_certificates) run, every containerd-erofs-* dm-verity device backs a running container, the IMDS refuses /user-data, /attest/challenge and /report from a pod's network namespace while the node reaches it, an image with a layer outside its signatures fails at pull naming that layer, and a file of the running pod's layer is refused as a kernel module, firmware and kexec image; every route to executable memory around IPE (e2e/execroutes: /proc/self/mem, mprotect adding write or execute, READ_IMPLIES_EXEC, ptrace) refused in a pod without a securityContext and in a transient host service, with the kubelet's seccompDefault from the sysext's drop-in cp_ready_seconds, worker_join_seconds, layer_registry_seconds

TestKubernetesCluster runs containers only from signed dm-verity layers (images/README.md). Before the first VM it renders cilium-app with helm template, copies the linux/amd64 manifest of every image kubeadm (imageRepository: gsoci.azurecr.io/giantswarm), the pinned sandbox and Cilium run from gsoci into a registry it serves over HTTPS under a test CA on the host's address, under the same paths, and signs each with pkg/layersign and the build's test Giant Swarm layer key (keys/layer.{key,crt}, enrolled into the .dm-verity keyring); the installation's workload is signed with a test key whose certificate goes to create_vm as layer_certificates. Ignition writes /etc/containerd/certs.d/gsoci.azurecr.io/hosts.toml with that registry as a mirror (and the test CA next to it), the only host with the referrers capability: nodes find the signatures through its referrers API, as production nodes do on gsoci. It needs kubectl, helm and mkfs.erofs on the host, reaches gsoci from the host only, and raises VM_MANAGER_BOOT_TIMEOUT for its server because READY=1 waits for the kubeadm unit. On failure the per-test state directory (consoles, TPM state, disks, the server log) is kept and its path printed; VM_MANAGER_E2E_KEEP=1 keeps it after a pass too. The tests that drive QEMU directly (TestInstallBoot, TestInstallBootSystemdBoot, TestIPE) also keep each boot's guest journal as <phase>-journal.log next to its console <phase>.log: the harness passes journal.forward_to_socket (journald.conf(5) ForwardToSocket=) with a vsock address it listens on and renders the export stream like journalctl -o short-monotonic, from the first second of the initrd, so a boot that never reaches ssh still explains itself. systemd-networkd and systemd-networkd-wait-online log at debug level there (systemd.unit-dropin.* credentials, systemd-debug-generator(8)).

Layout

  • cmd/ — cobra CLI: serve (every flag has an environment fallback named in its help text, VM_MANAGER_* plus the sibling-compatible DEX_*, GOOGLE_*, OAUTH_TRUSTED_AUDIENCES, SSO_ALLOW_PRIVATE_IP_JWKS_HOSTS; the identity provider is required), image golden (records golden PCRs from a VM's verified quote and the server's firmware build into the image's policy.json), version; cmd/vm-agent is the guest binary (attest --stage=initrd|ready, pcrs, version). cmd/logrus.go forwards gvisor-tap-vsock's logrus output into slog and demotes its per-connection teardown errors to debug.
  • internal/agent — the guest side of attestation: nonce, AK, TPM2_Quote over /dev/tpmrm0, event logs, the POST to the IMDS; agent/quote is the TPM plumbing (keys, PCR reads, quotes), tested against swtpm and the go-tpm simulator.
  • internal/api — REST handlers (rest.go) and MCP tools (mcp.go) over the same service methods, wired through api.Services; vm.go holds the create bodies and defaults shared by both. statusFor maps the apierr sentinels to an HTTP status and a stable code; MCP tool errors carry the same code. mcp_test.go is the contract test: an mcp-go client over streamable HTTP against the assembled server.
  • internal/buildinfo — the version, commit and build time the CLI, the MCP server (get_info, serverInfo.version) and vm_manager_build_info report: the -ldflags -X values when the build set them, else the Go build info (the tag at HEAD, vcs.revision, vcs.time); dev without either.
  • internal/apierr — the sentinel errors (ErrNotFound, ErrInvalid, ErrConflict, ErrUnsupported) domain packages wrap so both API surfaces answer the same status and code; statusFor also maps the VM service's milestone errors vm.ErrTimeout (504 timeout) and vm.ErrFailed (500 vm_failed).
  • internal/attest — the imds.Attestor of every server, Verifier: nonces, AK pinning per VM on the first verified initrd quote (restored from the VM's record after a restart, Pin), PCR 11 against the image's policy.json phase paths, PCRs 0, 2-4, 6, 7 (and 13 at ready, SysextPCR) against its golden values, a PCR without one rejected; PCR 1 and 5 replayed from the firmware event log, the GPT against the image's installed disk and the boot variables and loader.conf against the VM's first verified boot (bootconfig.go). Recorder is the reference boot of vm-manager image golden: every check but the golden comparison; serve never builds one.
  • internal/host — the host capability service behind get_host: kernel, CPUs, memory, /dev/kvm and /dev/vhost-vsock access, qemu / swtpm / systemd versions, the OVMF code image VMs boot with (--ovmf-code) and its build (the SHA-256 and the EDK2 line's release its firmware.json names), the io.systemd.StorageProvider sockets, and the ready / missing verdict. Commands go through an injectable Runner, file probes are relative to Options.Root, so tests run on a fixture tree.
  • internal/identity — the authenticated caller on the request context (subject, email, groups, source sso|oauth).
  • internal/images — the image catalog: scans --image-dir for <id>_<version>.efi + .raw pairs, policy.json, and the Kubernetes sysext versions under sysupdate/kubernetes/SHA256SUMS.
  • internal/imds — the instance metadata service handler: the key table (single source of truth for the hwdb record in images/, TestHwdbRecordParity), the attestation endpoints, /user-data gating with Ignition's status codes, the report sink, the sysupdate tree; internal/vm gives every network's IMDS its own resolver, from a lease IP on that network to its VM.
  • internal/metrics — the Prometheus registry: host metrics over the VM service (metrics.Source), the guests' systemd-report uploads (StoreReport, one series per entry with a per-VM cap) and the per-VM summary of get_vm_metrics. doc.go documents the mapping and the cardinality policy.
  • internal/network — rootless virtual networks on gvisor-tap-vsock: one L2 segment per network, one port (unix socket) per VM with port security on its frames, DHCP with static leases derived from the MAC, DNS, NAT, the IMDS virtual IP 169.254.169.254, host port forwards and persisted State for restarts (doc.go has the addressing).
  • internal/nonce — the one nonce store (5 min TTL, single use) the IMDS hands to both attestors.
  • internal/runtime/proc — starts and supervises long-running host processes (QEMU, swtpm) behind the injectable Exec interface, the long-running counterpart of host.Runner. SystemdExec runs each command as a transient systemd service (systemd-run --service-type=exec -p RemainAfterExit=yes, user or system manager) that outlives vm-manager and can be picked up again by Attach from the persisted Handle (unit name + PID; exit via a pidfd, status from systemctl show); SelectLauncher chooses it when a manager is reachable and OSExec (plain children) otherwise. FakeExec is for tests (records commands, the test drives exit codes and signals; it attaches by PID), Tail/TailFile the bounded output capture. Cmd.User starts a process as an unprivileged Identity (root only): OSExec empties the bounding and inheritable capability sets and sets no_new_privs on the locked thread that forks it, SystemdExec passes --uid, --gid, SupplementaryGroups=, an empty CapabilityBoundingSet= and NoNewPrivileges=yes; Identity.VerifyPeer checks who serves a unix socket (SO_PEERCRED). The integration test TestIntegrationSystemdExec drives the host's real user manager; TestOSExecUser needs root (run the package's test binary in the vm-manager container image).
  • internal/runtime/seccomp — the filter serve always installs on vm-manager and every process it starts: Docker's default profile (github.com/moby/profiles/seccomp, which containerd's RuntimeDefault mirrors) resolved for the process' capabilities and kernel, plus socket(AF_VSOCK), compiled for x86-64 alone (other ABIs refused) into a binary search on the syscall number; Check proves it with a keyctl that must fail with EPERM. The tests run the program in x/net/bpf's interpreter against the rules and install it in a child.
  • internal/deviceplugin — vm-manager device-plugin: the kubelet device plugin advertising giantswarm.io/kvm while /dev/kvm and /dev/vhost-vsock exist, each allocation both nodes read-write; registers again when the kubelet removed its socket. Tested against a fake kubelet.
  • internal/runtime/qemu — the VM process runtime. Command(Spec) is a pure function from a Spec (phase install or boot, UKI, installer DDI, target disk, netdevs, SMBIOS type 1, credentials as SMBIOS type 11 io.systemd.credential strings, the io.systemd.stub.kernel-cmdline-extra string, vsock CID, swtpm socket, OVMF paths, serial log, QMP socket) to the exact qemu-system-x86_64 argv; Runtime.Start seeds the per-VM OVMF vars, launches QEMU and returns an Instance (Wait, Stop = QMP system_powerdown -> SIGTERM -> SIGKILL, Kill, QMP); NotifyListener binds AF_VSOCK for the guest's READY=1 and renders the vmm.notify_socket credential (vsock-stream:2:<port>). Every command carries -sandbox (Sandbox); with Spec.User QEMU starts as that identity, the files it writes and its QMP socket's directory are handed to it, the groups of /dev/kvm and /dev/vhost-vsock are added where they are not open to every user, and the QMP socket must be served by that user. integration_test.go boots real OVMF with swtpm and user networking, no image needed.
  • internal/server — the single HTTP listener (/healthz, /readyz, /metrics, /api/v1, /mcp) with the mcp-oauth resource server (Dex or Google) in front of REST, MCP and /metrics, always; /metrics also takes the scrape token (--metrics-token-file); only the probes are open.
  • internal/testidp — a test OpenID provider (discovery and JWKS over TLS on a private address, id_tokens for vm-manager-test) for the tests, the e2e suite and hack/testidp; never part of an installation.
  • internal/storage — volumes for VM disks: the systemd storage provider over varlink when a socket under /run/systemd/io.systemd.StorageProvider/ answers GetInfo, plain files below <state-dir>/volumes otherwise (storage.Detect).
  • internal/tpm — one swtpm per VM: Manager.Start creates the state dir, runs swtpm socket --tpm2 --terminate with a unixio control socket (the process ends once QEMU closes its data channel), returns once swtpm has answered CMD_GET_CAPABILITY on the control socket (tpm.ErrUnresponsive after StartTimeout), logs every command at level 2 to swtpm.log next to the state dir (the previous run's in swtpm.prev.log); Instance stops it.
  • internal/tpmquote — pure parsing and cryptographic verification of a TPM2_Quote (TPMS_ATTEST, TPMT_SIGNATURE, AK TPMT_PUBLIC): magic and type, AK attributes, signature, nonce, PCR digest. tpmquote/quotetest produces real quotes on the go-tpm simulator (cgo) for tests.
  • internal/varlink — the minimal varlink client (JSON over AF_UNIX, passed descriptors) the storage provider uses.
  • internal/vm — the VM service behind every VM and network tool: the lifecycle state machine (doc.go has the states, transitions, milestones and the state directory), persistence below --state-dir, the orchestration of storage, swtpm, the network, the two QEMU phases and one IMDS server per network, WaitFor, Exec over ssh on the guest's vsock CID with a per-VM key and a pinned host key, Forward, the attestation hooks and PolicyFor. vmtest/ holds the in-memory fakes of its dependencies, shared by the vm tests and the API contract tests.
  • api/openapi.yaml — the REST contract; embedded and served at /api/v1/openapi.yaml.
  • images/ — the mkosi build of the guest image and the Kubernetes sysext (images/README.md).
  • e2e/ — the T3 boot tests above; harness.go builds and starts vm-manager serve and speaks MCP to it.
  • deploy/systemd/ — the system service unit and sysusers file of install.md.

Domain packages plug in the same way as internal/host: a Service with context-taking methods, a field on api.Services, one s.AddTool in NewMCPServer and one route in REST.Register per operation, errors wrapped from internal/apierr. cmd/serve.go wires them in the order internal/vm documents: storage.Detect -> network.NewManager -> qemu.ListenNotify -> proc.SelectLauncher -> tpm.New / qemu.New -> images.Load -> vm.New -> Load (which reattaches VMs an earlier server left running), creates the --default-network, serves, and on shutdown leaves the VMs to the next server (--detach-vms-on-exit, the default with the systemd launcher) or stops every one (Close) within --stop-timeout. e2e/restart_test.go proves the handover end to end and prints reattach_seconds. gvisor-tap-vsock logs through logrus; cmd/logrus.go forwards it into slog and demotes its per-connection teardown errors to debug.

Adding a tool

  1. Add the Tool<Name> constant and list it in ToolNames() (registration order: reads first, then writes).
  2. s.AddTool(newTool(Tool<Name>, summary, details, hintRead|hintWrite|hintIdempotent|hintDestructive|hintExec, args...), t.<handler>); the handler returns jsonResult(v) or errResult(err), nil. The summary (at most 120 runes, built with mcp-toolkit's tooldesc.Describe) says what the tool does; the details say what to call first and what a model would otherwise get wrong. The hints set all four MCP annotations, so the text does not repeat read or write. The guideline is mcp-toolkit's docs/conventions.md; TestToolDescriptionBudgets enforces its budgets.
  3. Mirror it in REST.Register with a Go 1.22 mux pattern and document it in api/openapi.yaml; request bodies use the tool's snake_case argument names.
  4. Run make tools-doc to regenerate docs/tools.md. Extend the contract test's expected tool list (mcp_test.go), the README's "API at a glance" table and, when it is a VM operation, the instructions paragraph in mcp.go.

Local loop

vm-manager has no anonymous mode: a local server trusts an identity provider like any other. hack/testidp is a test OpenID provider for that: it serves discovery and its JWKS on a private address of this host (mcp-oauth never fetches a JWKS from loopback) and writes its CA, the serve flags and an id_token for its client into a directory:

make build
idp=$(mktemp -d)
go run ./hack/testidp -dir "$idp" &                       # until killed
./vm-manager serve -v --listen 127.0.0.1:18080 --oauth-base-url http://127.0.0.1:18080 $(cat "$idp/flags")

T="Authorization: Bearer $(cat "$idp/token")"
curl -s localhost:18080/healthz
curl -s -H "$T" localhost:18080/api/v1/host | jq          # ready, missing, versions
curl -s -H "$T" localhost:18080/api/v1/openapi.yaml
curl -s -o /dev/null -w '%{http_code}\n' localhost:18080/api/v1/host   # 401: no token

The full loop with a guest, on a host where GET /api/v1/host says ready. A fresh images/build/policy.json has no golden PCR values and the server rejects every quote without them, so vm-manager image golden records them first, as the release pipeline does: it boots a reference VM on this host's firmware in its own process and then verifies a fresh VM against the values (the e2e suite's TestMain does the same):

make -C images                                            # images/build/giantswarm-vm-base_<v>.{efi,raw}, sysupdate/, policy.json
./vm-manager image golden giantswarm-vm-base --image-dir images/build
./vm-manager serve -v --listen 127.0.0.1:18080 --state-dir /tmp/vmm --image-dir images/build \
    --oauth-base-url http://127.0.0.1:18080 $(cat "$idp/flags")

API=localhost:18080/api/v1
curl -s -H "$T" $API/images | jq '.[] | {id, version, kubernetesVersions}'
curl -s -H "$T" -X POST $API/networks -d '{"name":"lab","cidr":"192.168.130.0/24"}' | jq .gateway
ID=$(curl -s -H "$T" -X POST $API/vms -d '{"name":"node-1","network":"lab","wait_for":"installed"}' | jq -r .id)
curl -s -H "$T" $API/vms/$ID | jq '{state, ip, lastError}'       # booting -> attesting -> ready
curl -s -H "$T" $API/vms/$ID/attestation | jq                     # initrd and ready quote, both verified
curl -s -H "$T" "$API/vms/$ID/console?lines=40" | jq -r .console
curl -s -H "$T" -X POST $API/vms/$ID/exec -d '{"command":["systemctl","is-system-running"]}' | jq .
curl -s -H "$T" -X DELETE $API/vms/$ID -o /dev/null -w '%{http_code}\n'
curl -s -H "$T" -X DELETE $API/networks/lab -o /dev/null -w '%{http_code}\n'

wait_for: ready (the default) blocks until the guest sent READY=1; --install-timeout (5 m) and --boot-timeout (4 m) bound it. Keep --state-dir short: unix socket paths below it are limited to 108 bytes.

The same operation as an MCP tool call over streamable HTTP (initialize, then tools/call; the session id from the initialize response goes into Mcp-Session-Id):

MCP=localhost:18080/mcp
H=(-H content-type:application/json -H accept:application/json,text/event-stream -H "$T")
SID=$(curl -si "${H[@]}" -X POST $MCP -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' | awk 'tolower($1)=="mcp-session-id:"{print $2}' | tr -d '\r')
curl -s "${H[@]}" -H "mcp-session-id: $SID" -X POST $MCP -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
curl -s "${H[@]}" -H "mcp-session-id: $SID" -X POST $MCP -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'
curl -s "${H[@]}" -H "mcp-session-id: $SID" -X POST $MCP -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_host"}}'

With mcp-debug or any MCP client, point it at http://127.0.0.1:18080/mcp with the token as its bearer.

Debugging a guest

  • The serial console first. get_vm_console (GET /vms/{id}/console?lines=) or the file <state-dir>/vms/<id>/console.log. Installer failures put the console tail into lastError; the ignition-* and vm-agent-attest.service units log to journal+console, so a fetch loop or a golden mismatch: pcr 0 expected ..., got ... is visible there without ssh.
  • Inside the guest. exec_vm runs as root over ssh on the VM's vsock: ["journalctl","-b","-u","vm-kubernetes.service"], ["systemctl","--failed"], ["systemd-analyze","pcrs","11","13"], ["cat","/run/log/systemd/tpm2-measure.log"], ["systemd-imds","/kubernetes-version"]. A plain ssh session goes the same way, from the host or the vm-manager pod: ssh -i <state-dir>/vms/<id>/ssh_key root@vsock/<cid> with the cid of get_vm (systemd's ssh_config.d/20-systemd-ssh-proxy.conf runs systemd-ssh-proxy for vsock/*). The guest has no sshd on TCP 22, so forward_port cannot reach one.
  • Attestation. get_vm_attestation shows both stages with the PCRs the agent quoted and the verifier's reason; compare against policy.json (pcr11 per phase path, sysexts with the sha256 per Kubernetes and CNI sysext, golden.sha256). A refused boot's reason is the VM's lastError.
  • e2e leftovers. VM_MANAGER_E2E_KEEP=1 make e2e keeps every test's state directory (consoles, guest journals, TPM state, disks, the server's log) and prints the path; without it only failing tests keep theirs.
  • A boot outside vm-manager. make -C images smoke-boot (systemd-vmspawn, no IMDS: the IMDS, attestation and Kubernetes units skip themselves; there is no login, the console shows the boot). Any firmware that boots the image needs its certificate in db, or PID 1 stops with Failed to load IPE policy: vm-manager image enroll <vars> --cert images/build/<id>_<v>.crt writes it into an OVMF variable store, which smoke-boot hands systemd-vmspawn as --efi-nvram-template.
  • Something does not run. IPE denials are audit records in the guest's journal (journalctl -b | grep IPE_ACCESS: operation, path, device and the rule that denied it); only code from the image's verity root and its sysexts runs (images/README.md, IPE).
  • A vm-manager restart marks every VM that was running as stopped with a note in lastError; start_vm boots them again.
  • A guest's shutdown. Over exec_vm, systemctl log-level debug and systemctl log-target console, then stop_vm and get_vm_console with lines=10000: the console keeps the whole stop sequence. For what is still mounted after the unmount loop, a temporary hook in /usr/lib/systemd/system-shutdown/ (in the image's mkosi.extra) can print /proc/self/mountinfo and the processes that survived.

OAuth against a lab Dex

./vm-manager serve -v --listen 127.0.0.1:18080 \
  --oauth-base-url http://localhost:18080 \
  --dex-issuer-url https://dex.lab.example/dex --dex-client-id agent-platform --dex-client-secret ... \
  --oauth-trusted-audiences agent-platform

/healthz, /readyz and the OAuth endpoints stay public; /api/v1, /mcp and /metrics require a bearer token: an id_token for a trusted audience (what muster forwards) or a token from this server's own OAuth flow; /metrics also takes the scrape token of --metrics-token-file.

CI

Two systems, one job each. CircleCI releases: the devctl-generated pipeline (.circleci/config.yml + workflows.yml, from gen.ci in giantswarm/github's repositories/team-bumblebee.yaml, flavour app, branchPublish, a linux/amd64 image) runs make test (go-build), builds and pushes the container image gsoci.azurecr.io/giantswarm/vm-manager and the chart to the giantswarm catalog — a dev image and dev chart on every branch, the release on every v* tag the Auto Release workflow cuts. It runs no chart tests (gen.ci.skipATS): its kind cluster has no KVM, and the chart does not run without its device plugin. The install smoke runs on a KVM runner instead (chart.yml, job smoke). The repo-owned guest-image job in .circleci/custom.yml builds the guest image on the tag (mkosi in a privileged archlinux container on a machine executor, hack/guest-image-build.sh) and publishes it as the OCI artifact gsoci.azurecr.io/giantswarm/vm-manager-guest-image:<version> with vm-manager image push (pkg/guestimage), signs it at its digest (cosign keyless, the architect orb's cosign-sign-verify) and persists that digest to the workspace as helm/vm-manager/guest-image.digest. The generated push-chart-release waits for the job (gen.ci.chartReleaseGateJob in giantswarm/github) and attaches the workspace before it packages the chart, so a released chart pulls the signed digest; without the file (branch builds) it pulls guestImage.tag, the appVersion by default. A release is complete when that job is green (the image build takes about 30 minutes on a cold cache). vm-manager image pull verifies the release's signature (pkg/guestimage/signature.go: ReleaseIdentity, sigstore-go, the trust root from Sigstore's TUF repository); its tests verify the 0.29.3 release's own bundle offline (pkg/guestimage/testdata). GitHub Actions tests what CircleCI cannot run: the guest image build for the KVM boot tests on the runners' nested virtualization. The devctl-generated zz_generated.* workflows add pre-commit (with the chart schema and README hooks), the values-schema check, gitleaks, semantic PR titles and the release automation. The tiers are those of design.md "Testing strategy".

Workflow Runs on When What
test.yml ubuntu-latest every PR, push to main make test vet-e2e (T0/T1, plus go vet -tags e2e ./e2e/... so the e2e package cannot rot unnoticed) and make lint lint-e2e
image.yml archlinux:latest container (--privileged) on ubuntu-26.04 PRs touching images/**, cmd/vm-agent/**, internal/agent/** or the workflow; push to main with the same paths; manual; called by e2e.yml make -C images (all: keys, base image, every Kubernetes sysext of KUBERNETES_VERSIONS, verify; T2), sizes and the expected PCR 11 values in the job summary, images/build/ (UKI, disk image, split partitions, sysupdate/, policy.json; not base/) as the guest-image artifact, 7 days (30 on main)
e2e.yml ubuntu-26.04 (nested KVM) every PR, push to main: fast subset; nightly 02:17 UTC and manual: full suite T3: go test -tags e2e against the artifact, consoles and logs as the e2e-logs-<suite> artifact
chart.yml ubuntu-latest; the smoke on ubuntu-26.04 (nested KVM) every PR, push to main make helm-lint helm-verify: the chart lints and the render assertions of hack/verify-chart.sh hold (unprivileged with its seven capabilities and the device request, no seccomp switch, the init container under RuntimeDefault, the device plugin's DaemonSet the only node paths, the guest-image init container and its reference, the state claim, OAuth from the identity contract, the MCPServer CR); smoke: the chart installs on a kind cluster whose node has the runner's /dev/kvm and /dev/vhost-vsock (tests/test-values.yaml, the image built from the branch), the device plugin advertises giantswarm.io/kvm, the pod is Ready under its own seccomp filter, and an upgrade that rolls the plugin and the pod together rejects no pod

The image build runs in an Arch container because the image is Arch (mkosi 27, systemd 261, erofs-utils, ukify, systemd-measure) and the hosted Ubuntu runner has none of that at the needed versions. --privileged gives mkosi's sandbox its mount namespaces; the mkosi workspace is placed on the runner's bind-mounted temp directory because the sysext's overlayfs cannot stack on the container's overlay root. No mkosi cache is kept between runs: every build installs the current Arch repositories (three to five minutes), as the release's CircleCI guest-image job does, so the nightly e2e boots the package set a release built at the same time ships. A restored incremental cache would make mkosi skip the metadata sync and copy its cached trees, freezing the package set of the build that seeded it.

e2e.yml has three jobs. plan decides the suite and where the image comes from: a PR or push that touches the image inputs builds it in this run (image.yml via workflow_call); otherwise the newest unexpired guest-image of a green image.yml or e2e.yml run on main is reused (and if there is none, it builds). Nightly and manual runs always build; the image_run_id input of a manual run reuses that run's artifact instead. test enables /dev/kvm (udev rule 99-kvm4all.rules, mode 0666) and vhost_vsock (modprobe, chmod), installs qemu-system-x86 (10.2), swtpm (0.10; internal/tpm passes its terminate ctrl option, swtpm 0.8+) and ovmf from the Ubuntu archive and unloads Ubuntu's AppArmor profile for swtpm, which denies sockets and state outside its allowed paths (the per-test directories under /mnt/e2e are). QEMU 10.2's io_uring main loop loses TPM emulator commands (#84); vm-manager keeps it off by denying the QEMU process io_uring_setup (a seccomp filter, SystemCallFilter= under the systemd launcher), so QEMU falls back to epoll. The harness dials ssh over AF_VSOCK from Go, so the host needs no systemd-ssh-proxy, and vm-manager falls back to file-backed volumes on a host without a systemd storage provider. On a QEMU older than 9.2 (Ubuntu 24.04's 8.2) internal/runtime/qemu passes the network's -netdev stream re-dial option as reconnect=<s> instead of reconnect-ms=. test downloads the artifact to /mnt/e2e/image and runs the tests with TMPDIR=/mnt/e2e (the runner's large data disk, short socket paths) and VM_MANAGER_E2E_KEEP=1.

Fast subset (PRs, 40-minute job timeout): TestInstallBoot, TestInstallBootSystemdBoot, TestNetworkIMDS, TestPersistentEtc, TestKubernetesSysext, TestIPE, TestHostIsolation, TestGuestNoLogin. Full suite (nightly, 60 minutes): those plus TestIgnition, TestKubernetesVersions (one VM per published sysext version), TestAttestation (the tamper case uses Ubuntu's OVMF_CODE_4M.secboot.fd as firmware that is not vm-manager's) and TestKubernetesCluster (needs the runner's kubectl and internet access from the VMs). The job summary lists the results and the *_seconds= budget lines.

Rerun: gh run rerun <id> --failed, or gh workflow run e2e.yml --ref <branch> -f suite=fast (-f image_run_id=<id> to reuse a specific image) and gh workflow run image.yml --ref <branch>. Failures: gh run view <id> --log-failed, then the e2e-logs-<suite> artifact (gh run download <id> -n e2e-logs-fast) for the serial consoles (<phase>.log, vms/<id>/console.log), the guest journals (<phase>-journal.log) and the server logs of the failed test's vmm-e2e-* directory. A PR that conflicts with main gets no pull_request runs at all (GitHub cannot create its merge commit): rebase first.

Testing against the agent platform (agentlab)

agentlab runs the whole agent platform — Dex, the agentgateway edge, muster, Backstage, kagent — on a local kind cluster and, with platform.vmManager in agentlab.yaml, the agent-platform chart's components.vm-manager in it: this chart, as a pod of the kind node (a privileged docker container, so the host's /dev/kvm and /dev/vhost-vsock are in it), with the image directory of this checkout mounted into the node (platform.vmManager.imageDir) and a build of this checkout swapped in through the lab's dev-image loop (platform.devImages.vm-manager). That is the end-to-end test of this repo's platform surface: the person's Dex id_token forwarded by muster and validated here, the tools aggregated as x_vm-manager_<tool> with their annotations, the portal listing the server under Agent Platform, and a VM created, followed to ready, attested and deleted through muster.

make -C images                                       # once: the image directory the pod mounts
make docker-build TAG=vm-manager:dev                 # the image of this checkout
cd ~/projects/giantswarm/agentlab
agentlab configure --vm-manager --vm-manager-image-dir ~/projects/giantswarm/vm-manager/images/build
# platform.devImages: {vm-manager: vm-manager:dev} in agentlab.yaml swaps the build in
agentlab up                                          # the image-dir mount is fixed at kind create: `agentlab down && up` after changing it
agentlab vm-manager-test                             # 401 anonymous -> token accepted -> tools -> create_vm -> ready -> attestation -> delete_vm

The pod's OVMF is the release of the Giant Swarm EDK2 line the Dockerfile pins (firmware/README.md); make firmware fetches the same files for the host. A released guest image artifact carries golden values recorded with its release's container image; a local build records them with the container image the pod runs, hack/guest-image-golden.sh vm-manager:dev images/build before the lab pushes it (no other vm-manager may run on the host: vsock CIDs are host-global), and again after a release that changes the firmware. get_host names the build the pod boots with.