Files
diskless-workstation/files/enrol/enrol_test.go
T
Audiobuzz 6278f2847d tpm-enrol: pivot host enrolment to a Go binary, built out-of-VM
Replaces the shell/openssl-provider host enrolment (a35f2d6) with a static
Go + go-tpm binary, and moves BOTH host Go binaries out of the Packer VM.

fleet-enrol (files/enrol/, Go + go-tpm, no CGO):
  - talks to /dev/tpmrm0 DIRECTLY via transport.FromReadWriter(os.File) — no
    linuxtpm, so go-tpm is the only dep and there is NO tpm2-tools key-gen /
    openssl tpm2 provider / curl in the image (removes the biggest bench risk,
    the provider handle: key-ref).
  - ensures the ECDSA key @0x81010001, builds the CSR (crypto.Signer over the
    TPM key), POSTs CSR+context to the broker, shows the Plymouth fingerprint,
    polls /status, writes the leaf cert to NV 0x01800001.
  - tpmkey/ is an exported package so the TPM ceremony is tested against the
    go-tpm software simulator from a SEPARATE simtest/ module (CGO stays out of
    the shipped build). Transaction logic (mock broker) tested in-package.
  - deps pinned by go.sum (not vendored): the binary now builds on the CI
    runner, which has network — reproducible via pinned Go 1.26.4 + go.sum.

Out-of-VM build (decision): both fleet-enrol AND fleet-hostapi compile in the
CI "Build host Go binaries" step (Go 1.26.4, CGO off, -trimpath) and Packer
FILE-PROVISIONS the static binaries in. Dropped the in-VM `dnf install golang`
+ the 2d removal — the Rocky build image carries no Go toolchain / go-tpm tree.

Wiring:
  - tpm-enrol.sh: now a thin GATE (empty-NV check, pre-auth DHCP on en*,
    exec /usr/sbin/fleet-enrol, reboot-to-converge). module-setup.sh bundles the
    binary (asserted) + reverts the tpm2-openssl/curl installs.
  - diskless.pkr.hcl: file provisioners for both binaries; enrol installed to
    /usr/sbin before the initramfs build + fapolicyd-trusted; lsinitrd asserts
    fleet-enrol; dnf reverted to baseline (no tpm2-openssl/curl).
  - gitea-main-ci.yaml: Set up Go + build both binaries + run the simulator
    ceremony test, before packer validate.

TESTED here: transaction unit tests + the full TPM ceremony (key-gen -> persist
-> ECDSA sign -> CSR verify -> chunked NV write -> re-enrol) against the go-tpm
simulator. BENCH-VERIFY (real/swtpm, empty owner auth, pre-auth DHCP, Plymouth,
reboot-converge, prod HTTPS) tracked in docs/TODO.md #11.
2026-07-02 09:55:54 +00:00

145 lines
4.9 KiB
Go

package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"math/big"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func bigOne() *big.Int { return big.NewInt(1) }
func bigN(n int64) *big.Int { return big.NewInt(n) }
func pkixCN(cn string) pkix.Name { return pkix.Name{CommonName: cn} }
// mockBroker mimics serving/enrol-broker: /request returns a fingerprint +
// enrol-id; /status returns pending until approveAfter polls, then approved with
// a cert signed by an in-process CA over the submitted CSR's public key.
func mockBroker(t *testing.T, approveAfterPolls int) *httptest.Server {
t.Helper()
caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
caTmpl := &x509.Certificate{SerialNumber: bigOne(), Subject: pkixCN("mock CA"), IsCA: true, BasicConstraintsValid: true}
caDER, _ := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
caCert, _ := x509.ParseCertificate(caDER)
var polls int
var certPEM string
mux := http.NewServeMux()
mux.HandleFunc("/request", func(w http.ResponseWriter, r *http.Request) {
var req enrolRequest
json.NewDecoder(r.Body).Decode(&req)
blk, _ := pem.Decode([]byte(req.CSR))
if blk == nil {
t.Errorf("submitted CSR is not PEM")
http.Error(w, "bad csr", 400)
return
}
csr, err := x509.ParseCertificateRequest(blk.Bytes)
if err != nil || csr.CheckSignature() != nil {
t.Errorf("CSR signature invalid: %v", err)
http.Error(w, "bad csr sig", 400)
return
}
// sign a leaf over the CSR's public key
leaf := &x509.Certificate{SerialNumber: bigN(0xabc123), Subject: csr.Subject}
der, _ := x509.CreateCertificate(rand.Reader, leaf, caCert, csr.PublicKey, caKey)
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) +
string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}))
json.NewEncoder(w).Encode(requestResp{EnrolID: "e1", Fingerprint: "cedar-onyx-meadow", State: "pending"})
})
mux.HandleFunc("/status/", func(w http.ResponseWriter, r *http.Request) {
polls++
if polls <= approveAfterPolls {
json.NewEncoder(w).Encode(statusResp{State: "pending"})
return
}
json.NewEncoder(w).Encode(statusResp{
State: "approved", Cert: certPEM,
Hostnqn: "nqn.2026-06.org.example.fleet:host-abc123", CertSerial: "abc123",
})
})
return httptest.NewServer(mux)
}
func TestEnrolHappyPath(t *testing.T) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // stands in for the TPM signer
csrPEM, err := buildCSR(key, "fleet-host")
if err != nil {
t.Fatalf("buildCSR: %v", err)
}
srv := mockBroker(t, 2) // pending twice, then approved
defer srv.Close()
c := &brokerClient{http: srv.Client(), baseURL: srv.URL}
var gotFP string
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
st, err := enrol(ctx, c, csrPEM, deviceContext{MAC: "de:ad:be:ef:00:01"}, 10*time.Millisecond,
func(fp string) { gotFP = fp })
if err != nil {
t.Fatalf("enrol: %v", err)
}
if gotFP != "cedar-onyx-meadow" {
t.Errorf("fingerprint not surfaced: %q", gotFP)
}
der, err := leafDER(st.Cert)
if err != nil {
t.Fatalf("leafDER: %v", err)
}
crt, err := x509.ParseCertificate(der)
if err != nil {
t.Fatalf("parse leaf: %v", err)
}
if crt.Subject.CommonName != "fleet-host" {
t.Errorf("leaf CN = %q, want fleet-host", crt.Subject.CommonName)
}
}
func TestEnrolDenied(t *testing.T) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
csrPEM, _ := buildCSR(key, "fleet-host")
mux := http.NewServeMux()
mux.HandleFunc("/request", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(requestResp{EnrolID: "e1", Fingerprint: "x", State: "pending"})
})
mux.HandleFunc("/status/", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(statusResp{State: "denied"})
})
srv := httptest.NewServer(mux)
defer srv.Close()
c := &brokerClient{http: srv.Client(), baseURL: srv.URL}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := enrol(ctx, c, csrPEM, deviceContext{}, time.Millisecond, nil)
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Fatalf("expected denied error, got %v", err)
}
}
func TestLeafDERChain(t *testing.T) {
// two-cert bundle -> leaf is the first
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
mk := func(cn string) string {
tmpl := &x509.Certificate{SerialNumber: bigOne(), Subject: pkixCN(cn)}
der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
}
der, err := leafDER(mk("leaf") + mk("inter"))
if err != nil {
t.Fatalf("leafDER: %v", err)
}
crt, _ := x509.ParseCertificate(der)
if crt.Subject.CommonName != "leaf" {
t.Errorf("got %q, want leaf", crt.Subject.CommonName)
}
}