carlos / platform Public

fix: same-fs managed install, durable stable mode, rescrub

Astra R1 P1-1: committed files are installed by rename only. Before the
trade (and on every resume) the boot directory, /etc/carlos, /var/lib and
/opt/carlos must share one filesystem, else bootstrap_failed with the
token unspent. The EXDEV copy-and-shred path is gone; a present
committed source is whole and authoritative, a destination already
holding its bytes only unlinks it. Interruption witnesses cover the
renamed-unsynced, rename-lost, both-present and synced windows for
every file, and a stale destination.

P2-1: the staged stable binary is fsynced after its chmod 0755 and
before the rename and the complete marker; witnessed.

P2-2: cloud-init's user-data copies are shredded by path on every boot
(first boot fails closed, complete path best effort and logged);
obj.pkl is never removed, so cloud-init does not rediscover and rewrite;
the token scan streams any size. carlos-managed-boot.service is ordered
After=cloud-init.service cloud-init-network.service; golden regenerated.

Fable P3s: /dev/console opened O_NONBLOCK; a stop (SIGTERM, cancel)
leaves no failure breadcrumb; enrol transport failures log their class
only; wrong-component pointer case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f0801639b78dcaa8bd4fcfb1bc507e134bd61848 parent 49e7811
8 files changed, +516 −70
  • internal/console/managedseed_linux_test.go +1 −1
  • internal/host/managedboot.go +178 −20
  • internal/host/managedboot_linux.go +38 −38
  • internal/host/managedboot_linux_test.go +287 −8
  • internal/host/managedboot_other.go +4 −0
  • internal/host/managedstable.go +6 −1
  • internal/managedboot/cloudinit_v1.sh.tmpl +1 −1
  • internal/managedboot/testdata/userdata-v1.golden +1 −1
diff --git a/internal/console/managedseed_linux_test.go b/internal/console/managedseed_linux_test.go
index e8755cb7f..712ac8846 100644
--- a/internal/console/managedseed_linux_test.go
+++ b/internal/console/managedseed_linux_test.go
@@ -173,7 +173,7 @@ func TestManagedCloudInitScriptRun(t *testing.T) {
t.Fatalf("boot input %+v %v", in, err)
}
for path, want := range map[string]string{
- "/etc/systemd/system/carlos-managed-boot.service": "[Unit]\nRequires=nftables.service\nAfter=nftables.service\nBefore=carlos-edge.service\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\n" +
+ "/etc/systemd/system/carlos-managed-boot.service": "[Unit]\nRequires=nftables.service\nAfter=nftables.service cloud-init.service cloud-init-network.service\nBefore=carlos-edge.service\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\n" +
"ExecStart=/usr/bin/python3 -I /var/lib/carlos-managed-boot/verify.py seed\nExecStart=/var/lib/carlos-managed-boot/seed system managed-boot --input /var/lib/carlos-managed-boot/boot-input.json\n\n[Install]\nWantedBy=multi-user.target\n",
"/etc/systemd/system/carlos-managed-boot.service.d/10-enrol.conf": "[Unit]\nWants=network-online.target\nAfter=network-online.target\n",
"/etc/systemd/system/carlos-edge.service.d/60-managed.conf": "[Unit]\nRequires=carlos-managed-boot.service\nAfter=carlos-managed-boot.service\n",
diff --git a/internal/host/managedboot.go b/internal/host/managedboot.go
index 957241d53..328f2c4de 100644
--- a/internal/host/managedboot.go
+++ b/internal/host/managedboot.go
@@ -5,6 +5,8 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
@@ -13,6 +15,7 @@ import (
"io"
"io/fs"
"math/big"
+ "net"
"net/http"
"os"
"path/filepath"
@@ -57,7 +60,7 @@ const (
mbIMDSTable = "carlos_managed_imds"
mbIMDSWait = 60 * time.Second
mbReplyLimit = 64 << 10
- mbScanLimit = 16 << 20
+ mbScanChunk = 1 << 20
mbFileLimit = 64 << 10
mbRequestTimeout = 60 * time.Second
)
@@ -96,6 +99,8 @@ type managedBoot struct {
logf func(format string, args ...any)
// openStore opens the store door from the committed host.env.
openStore func(env map[string]string) (release.Store, error)
+ // dev is a directory's filesystem (st_dev).
+ dev func(path string) (uint64, error)
// uid and gid own every root file (0:0 on a box); serviceGID is
// carlos's group, which may read the credentials.
uid, gid, serviceGID int
@@ -122,7 +127,9 @@ func (m *managedBoot) step(name string) error {
func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err error) {
code := managedboot.CodeBootstrapFailed
defer func() {
- if err != nil && !errors.Is(err, errManagedBootHalted) {
+ // A halt (test power loss) or a stop (SIGTERM, shutdown) is not an
+ // outcome: the next boot carries on, so no breadcrumb.
+ if err != nil && !errors.Is(err, errManagedBootHalted) && !errors.Is(err, context.Canceled) && ctx.Err() == nil {
m.breadcrumb(code)
}
}()
@@ -143,6 +150,12 @@ func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err
if err != nil {
return err
}
+ // Installation is by rename only, so every staged file and its final
+ // directory must share one filesystem; checked before the token is
+ // spent, and again on every resume.
+ if err = m.sameFilesystem(); err != nil {
+ return err
+ }
if !committed {
if in.Token == "" {
code = managedboot.CodeEnrolFailed
@@ -229,6 +242,11 @@ func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err
// completePath is every boot after the first: no network, no digest.
func (m *managedBoot) completePath(ctx context.Context) error {
+ // cloud-init writes the user data again each boot; carlos-managed-boot
+ // is ordered after it. Best effort: a serving box never fails on it.
+ if err := m.scrubKnown(); err != nil {
+ m.logf("managed boot: scrub of cloud-init user-data copies: %v", err)
+ }
a, err := managedboot.InstallAdmissionDropIns(m.p(mbSystemdDir), nil)
if err != nil {
return err
@@ -391,8 +409,11 @@ func (m *managedBoot) post(ctx context.Context, url string, body []byte) (int, h
req.Header.Set("Content-Type", "application/json")
resp, err := m.http.Do(req)
if err != nil {
- // The URL is the frozen origin; the token is only in the body.
- return 0, nil, nil, errors.New("managed boot: enrolment request failed")
+ // Only the class reaches the journal: never the URL, body or
+ // headers, though the token is only in the body.
+ class := mbTransportClass(err)
+ m.logf("managed boot: enrolment request failed: %s", class)
+ return 0, nil, nil, errors.New("managed boot: enrolment request failed (" + class + ")")
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, mbReplyLimit+1))
@@ -411,6 +432,32 @@ func retryAfter(h http.Header, def time.Duration) time.Duration {
return time.Duration(min(n, 300)) * time.Second
}
+// mbTransportClass names what kind of transport failure err is, with no
+// value from it: dns, tls-trust, tls, timeout, dial or transport.
+func mbTransportClass(err error) string {
+ var dnsErr *net.DNSError
+ var unknownCA x509.UnknownAuthorityError
+ var hostname x509.HostnameError
+ var invalid x509.CertificateInvalidError
+ var verify *tls.CertificateVerificationError
+ var record tls.RecordHeaderError
+ var opErr *net.OpError
+ var timeout interface{ Timeout() bool }
+ switch {
+ case errors.As(err, &dnsErr):
+ return "dns"
+ case errors.As(err, &unknownCA) || errors.As(err, &hostname) || errors.As(err, &invalid) || errors.As(err, &verify):
+ return "tls-trust"
+ case errors.As(err, &record):
+ return "tls"
+ case errors.As(err, &timeout) && timeout.Timeout():
+ return "timeout"
+ case errors.As(err, &opErr) && opErr.Op == "dial":
+ return "dial"
+ }
+ return "transport"
+}
+
// mbJitter is 1-30 s.
func mbJitter() time.Duration {
n, err := rand.Int(rand.Reader, big.NewInt(30))
@@ -487,13 +534,8 @@ func (m *managedBoot) installCommitted(in managedboot.LaunchInput) (map[string]s
}
bodies := map[string][]byte{}
for _, f := range mbCommitted {
- src := mbCommittedDir + "/" + f.name
- if ok, err := m.present(src); err != nil {
+ if err := m.installOne(f.name, f.final, f.mode); err != nil {
return nil, err
- } else if ok {
- if err = mbMove(m.root, src, f.final); err != nil {
- return nil, err
- }
}
body, err := mbReadRootFile(m.root, f.final, m.uid, mbFileLimit, f.mode)
if err != nil {
@@ -521,10 +563,112 @@ func (m *managedBoot) installCommitted(in managedboot.LaunchInput) (map[string]s
return env, nil
}
+// installOne moves one committed file to its final path by rename alone.
+// A committed source is never modified in place, so it is always whole:
+// present, it is the truth, and it is renamed over whatever the final path
+// holds, unless that already holds the same bytes, when the source is only
+// unlinked. Absent, an earlier boot moved it. Each step is a seam for the
+// interruption witnesses.
+func (m *managedBoot) installOne(name, final string, mode os.FileMode) error {
+ src := mbCommittedDir + "/" + name
+ ok, err := m.present(src)
+ if err != nil || !ok {
+ return err
+ }
+ if have, err := mbReadRootFile(m.root, final, m.uid, mbFileLimit, mode); err == nil {
+ if want, err := mbReadRootFile(m.root, src, m.uid, mbFileLimit, mode); err == nil && bytes.Equal(have, want) {
+ if err = os.Remove(m.p(src)); err != nil {
+ return err
+ }
+ return mbSyncDir(m.p(mbCommittedDir))
+ }
+ }
+ if err = os.Rename(m.p(src), m.p(final)); err != nil {
+ return fmt.Errorf("managed boot: install %s: %w", name, err)
+ }
+ if err = m.step("install-renamed:" + name); err != nil {
+ return err
+ }
+ if err = mbSyncDir(filepath.Dir(m.p(final))); err != nil {
+ return err
+ }
+ if err = mbSyncDir(m.p(mbCommittedDir)); err != nil {
+ return err
+ }
+ return m.step("install-synced:" + name)
+}
+
+// mbSameFS are the directories installation renames between.
+var mbSameFS = []string{managedboot.BootDir, mbEtcCarlos, filepath.Dir(managedboot.RootAdmissionDir), "/opt/carlos"}
+
+// sameFilesystem makes /etc/carlos and /opt/carlos (root-owned) and
+// refuses unless every directory in mbSameFS is on BootDir's filesystem.
+func (m *managedBoot) sameFilesystem() error {
+ for _, d := range []string{mbEtcCarlos, "/opt/carlos"} {
+ if err := mbEnsureDir(m.root, d, 0o755, m.uid); err != nil {
+ return err
+ }
+ }
+ want, err := m.dev(m.p(mbSameFS[0]))
+ if err != nil {
+ return err
+ }
+ for _, d := range mbSameFS[1:] {
+ got, err := m.dev(m.p(d))
+ if err != nil {
+ return err
+ }
+ if got != want {
+ return fmt.Errorf("managed boot: %s is not on the boot directory's filesystem", d)
+ }
+ }
+ return nil
+}
+
+// mbUserDataCopies are cloud-init's copies of the user data, by name under
+// each /var/lib/cloud/instances/<id>/. obj.pkl is not one of them to
+// remove: without it cloud-init rediscovers the datasource and writes
+// every copy again.
+var mbUserDataCopies = []string{"user-data.txt", "user-data.txt.i", "scripts/part-001"}
+
+// scrubKnown shreds cloud-init's user-data copies by path; it needs no token.
+func (m *managedBoot) scrubKnown() error {
+ instances := m.p("/var/lib/cloud/instances")
+ entries, err := os.ReadDir(instances)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ for _, c := range mbUserDataCopies {
+ path := filepath.Join(instances, e.Name(), c)
+ st, err := os.Lstat(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ continue
+ }
+ if err == nil && st.Mode().IsRegular() {
+ err = mbShred(path)
+ }
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
// scrub shreds every copy of the token cloud-init and the seed left on
// disk, removes the seed request and rewrites the boot input without the
-// token, last: a scrubbed boot input means the scrub is done.
+// token, last: a scrubbed boot input means the token-wide scan is done.
+// The by-path shred runs on every incomplete boot, token or not.
func (m *managedBoot) scrub(in managedboot.LaunchInput) error {
+ if err := m.scrubKnown(); err != nil {
+ return fmt.Errorf("managed boot: scrub cloud-init user-data copies: %w", err)
+ }
if in.Token == "" {
return nil
}
@@ -537,7 +681,7 @@ func (m *managedBoot) scrub(in managedboot.LaunchInput) error {
if err != nil {
return err
}
- if !d.Type().IsRegular() || path == m.p(managedboot.BootInputPath) {
+ if !d.Type().IsRegular() || path == m.p(managedboot.BootInputPath) || d.Name() == "obj.pkl" {
return nil
}
holds, err := mbHolds(path, token)
@@ -564,18 +708,32 @@ func (m *managedBoot) scrub(in managedboot.LaunchInput) error {
return mbWriteRootFile(m.root, managedboot.BootInputPath, scrubbed, 0o600, m.uid, -1)
}
-// mbHolds reports whether a regular file of at most mbScanLimit bytes
-// holds needle. Larger files (the seed) cannot be a copy of the user data.
+// mbHolds reports whether a regular file holds needle, reading it in
+// bounded chunks whatever its size; a match across a chunk boundary is
+// found through the carried tail.
func mbHolds(path string, needle []byte) (bool, error) {
- st, err := os.Lstat(path)
- if err != nil || !st.Mode().IsRegular() || st.Size() > mbScanLimit {
- return false, err
- }
- body, err := os.ReadFile(path)
+ f, err := mbOpenRegular(path)
if err != nil {
return false, err
}
- return bytes.Contains(body, needle), nil
+ defer f.Close()
+ buf := make([]byte, mbScanChunk+len(needle))
+ carry := 0
+ for {
+ n, err := f.Read(buf[carry:])
+ if bytes.Contains(buf[:carry+n], needle) {
+ return true, nil
+ }
+ if err == io.EOF {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ keep := min(len(needle)-1, carry+n)
+ copy(buf, buf[carry+n-keep:carry+n])
+ carry = keep
+ }
}
// mbStable is the record of the release this boot installed.
diff --git a/internal/host/managedboot_linux.go b/internal/host/managedboot_linux.go
index 3c2ca7c3f..568b5a892 100644
--- a/internal/host/managedboot_linux.go
+++ b/internal/host/managedboot_linux.go
@@ -73,6 +73,7 @@ func newManagedBoot(root string, uid, gid, serviceGID int) *managedBoot {
jitter: mbJitter,
run: mbRun,
breadcrumb: mbBreadcrumb,
+ dev: mbDev,
logf: log.Printf,
openStore: mbDoorStore,
}
@@ -140,7 +141,8 @@ func mbRun(ctx context.Context, argv []string, env []string) error {
// provider's console output returns) and the journal.
func mbBreadcrumb(code string) {
line := managedboot.Breadcrumb(code) + "\n"
- if f, err := os.OpenFile("/dev/console", os.O_WRONLY|syscall.O_NOCTTY, 0); err == nil {
+ // Non-blocking: a wedged serial console must not hold the boot.
+ if f, err := os.OpenFile("/dev/console", os.O_WRONLY|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0); err == nil {
_, _ = f.WriteString(line)
_ = f.Close()
}
@@ -293,59 +295,57 @@ func mbWriteRootFile(root, abs string, body []byte, mode os.FileMode, uid, group
return unix.Fsync(dir)
}
-// mbMove renames src to dst beneath root and syncs both directories. Across
-// filesystems it copies durably, keeping mode and group, then shreds src.
+// mbMove renames src to dst beneath root and syncs both directories. It is
+// a rename and nothing else: a move across filesystems is refused (EXDEV),
+// never copied, so a source is never half removed.
func mbMove(root, src, dst string) error {
from, to := filepath.Join(root, src), filepath.Join(root, dst)
- err := os.Rename(from, to)
- if errors.Is(err, unix.EXDEV) {
- err = mbCopyDurable(from, to)
- if err == nil {
- err = mbShred(from)
- }
- }
- if err != nil {
+ if err := os.Rename(from, to); err != nil {
return err
}
- if err = mbSyncDir(filepath.Dir(to)); err != nil {
+ if err := mbSyncDir(filepath.Dir(to)); err != nil {
return err
}
return mbSyncDir(filepath.Dir(from))
}
-func mbCopyDurable(from, to string) error {
- in, err := os.OpenFile(from, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
- if err != nil {
- return err
- }
- defer in.Close()
+// mbDev is the st_dev of a directory, not following a symlink.
+func mbDev(path string) (uint64, error) {
var st unix.Stat_t
- if err = unix.Fstat(int(in.Fd()), &st); err != nil {
- return err
+ if err := unix.Lstat(path, &st); err != nil {
+ return 0, err
}
- tmp := to + ".move"
- _ = os.Remove(tmp)
- out, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o600)
+ if st.Mode&unix.S_IFMT != unix.S_IFDIR {
+ return 0, fmt.Errorf("managed boot: %s is not a directory", path)
+ }
+ return uint64(st.Dev), nil
+}
+
+// mbFsyncFile makes a file's data and metadata (its mode) durable. A
+// variable so a witness can record the ordering.
+var mbFsyncFile = func(path string) error {
+ fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
if err != nil {
return err
}
- if err = out.Chown(-1, int(st.Gid)); err == nil {
- if err = out.Chmod(os.FileMode(st.Mode & 0o777)); err == nil {
- if _, err = io.Copy(out, in); err == nil {
- err = out.Sync()
- }
- }
- }
- if cerr := out.Close(); err == nil {
- err = cerr
- }
- if err == nil {
- err = os.Rename(tmp, to)
- }
+ defer unix.Close(fd)
+ return unix.Fsync(fd)
+}
+
+// mbOpenRegular opens a regular file for reading without following a
+// symlink or blocking on a FIFO.
+func mbOpenRegular(path string) (*os.File, error) {
+ fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
if err != nil {
- _ = os.Remove(tmp)
+ return nil, err
+ }
+ f := os.NewFile(uintptr(fd), path)
+ var st unix.Stat_t
+ if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG {
+ f.Close()
+ return nil, errors.Join(fmt.Errorf("%s is not a regular file", path), err)
}
- return err
+ return f, nil
}
func mbSyncDir(path string) error {
diff --git a/internal/host/managedboot_linux_test.go b/internal/host/managedboot_linux_test.go
index b0018f46c..c203cb1c1 100644
--- a/internal/host/managedboot_linux_test.go
+++ b/internal/host/managedboot_linux_test.go
@@ -12,6 +12,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"io/fs"
"net/http"
"net/http/httptest"
@@ -88,6 +89,10 @@ type mbFixture struct {
errs []string
sleptFor time.Duration
failCheck func() string
+ devs map[string]uint64 // st_dev overrides by absolute path
+ client *http.Client // overrides the console client
+ cancel bool // a stop arrives during the first sleep
+ logs []string
}
func newMBFixture(t *testing.T) *mbFixture {
@@ -261,15 +266,33 @@ func (f *mbFixture) boot(crashAt string) error {
if in, _, err = managedboot.DecodeBootInput(raw); err != nil {
f.t.Fatalf("boot input: %v", err)
}
+ client := f.srv.Client()
+ if f.client != nil {
+ client = f.client
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
m := &managedBoot{
root: f.root, uid: os.Getuid(), gid: os.Getgid(), serviceGID: os.Getgid(),
- http: f.srv.Client(),
- now: func() time.Time { f.mu.Lock(); defer f.mu.Unlock(); return f.clock },
+ http: client,
+ dev: func(path string) (uint64, error) {
+ rel, _ := filepath.Rel(f.root, path)
+ if d, ok := f.devs["/"+rel]; ok {
+ return d, nil
+ }
+ return mbDev(path)
+ },
+ now: func() time.Time { f.mu.Lock(); defer f.mu.Unlock(); return f.clock },
sleep: func(ctx context.Context, d time.Duration) error {
f.mu.Lock()
f.clock = f.clock.Add(d)
f.sleptFor += d
+ stop := f.cancel
f.mu.Unlock()
+ if stop {
+ cancel()
+ return ctx.Err()
+ }
return nil
},
jitter: func() time.Duration { return 7 * time.Second },
@@ -312,7 +335,11 @@ func (f *mbFixture) boot(crashAt string) error {
f.crumbs = append(f.crumbs, code)
f.mu.Unlock()
},
- logf: f.t.Logf,
+ logf: func(format string, args ...any) {
+ f.mu.Lock()
+ f.logs = append(f.logs, fmt.Sprintf(format, args...))
+ f.mu.Unlock()
+ },
openStore: func(env map[string]string) (release.Store, error) {
if env["CARLOS_TUNNEL_URL"] != "https://"+mbtTunnelHost || env["CARLOS_TUNNEL_TOKEN"] != mbtTunnelToken {
return nil, errors.New("store door opened without the committed tunnel")
@@ -337,7 +364,7 @@ func (f *mbFixture) boot(crashAt string) error {
return nil
}
}
- err = m.Run(context.Background(), in)
+ err = m.Run(ctx, in)
f.mu.Lock()
errs := f.errs
f.errs = nil
@@ -425,7 +452,7 @@ func TestManagedBootFirewallOrdering(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, want := range []string{"[Unit]\nRequires=nftables.service\nAfter=nftables.service\n", "[Unit]\nWants=network-online.target\nAfter=network-online.target\n"} {
+ for _, want := range []string{"[Unit]\nRequires=nftables.service\nAfter=nftables.service cloud-init.service cloud-init-network.service\n", "[Unit]\nWants=network-online.target\nAfter=network-online.target\n"} {
if !strings.Contains(script, want) {
t.Errorf("unit text lacks %q", want)
}
@@ -990,10 +1017,18 @@ func filesHolding(t *testing.T, root string, needle string) []string {
func TestManagedBootScrub(t *testing.T) {
f := newMBFixture(t)
+ // An oversized log holding the token across a scan-chunk boundary, and
+ // an oversized clean file beside it.
+ big := bytes.Repeat([]byte("x"), 17<<20)
+ copy(big[mbScanChunk-10:], mbtToken)
+ f.write("/var/log/cloud-init.log", big, 0o644)
+ f.write("/var/log/big-clean.log", bytes.Repeat([]byte("y"), 17<<20), 0o644)
if err := f.boot(""); err != nil {
t.Fatal(err)
}
- if hits := filesHolding(t, f.root, mbtToken); len(hits) != 0 {
+ // obj.pkl is cloud-init's datasource cache: removing it makes
+ // cloud-init rediscover and write every copy again, so it stays.
+ if hits := filesHolding(t, f.root, mbtToken); !slices.Equal(hits, []string{"/var/lib/cloud/instances/i-0abc/obj.pkl"}) {
t.Errorf("the enrolment token survives in %v", hits)
}
if hits := filesHolding(t, f.root, mbtSecret); !slices.Equal(hits, []string{managedboot.CredentialsPath}) {
@@ -1009,16 +1044,62 @@ func TestManagedBootScrub(t *testing.T) {
if err != nil || !scrubbed || in != want {
t.Errorf("boot input after the scrub: %+v scrubbed=%v %v", in, scrubbed, err)
}
- for _, p := range []string{managedboot.SeedRequestPath, "/var/lib/cloud/instances/i-0abc/user-data.txt", "/var/lib/cloud/instances/i-0abc/user-data.txt.i", "/var/lib/cloud/instances/i-0abc/scripts/part-001", "/var/lib/cloud/instances/i-0abc/obj.pkl"} {
+ for _, p := range []string{managedboot.SeedRequestPath, "/var/lib/cloud/instances/i-0abc/user-data.txt", "/var/lib/cloud/instances/i-0abc/user-data.txt.i", "/var/lib/cloud/instances/i-0abc/scripts/part-001", "/var/log/cloud-init.log"} {
if f.exists(p) {
t.Errorf("%s survives", p)
}
}
- for _, p := range []string{"/var/lib/cloud/instances/i-0abc/sem/config_scripts_user", "/run/cloud-init/instance-data.json", "/var/log/cloud-init-output.log", "/var/lib/carlos-managed-boot/seed"} {
+ for _, p := range []string{"/var/lib/cloud/instances/i-0abc/sem/config_scripts_user", "/var/lib/cloud/instances/i-0abc/obj.pkl", "/run/cloud-init/instance-data.json", "/var/log/cloud-init-output.log", "/var/lib/carlos-managed-boot/seed", "/var/log/big-clean.log"} {
if !f.exists(p) {
t.Errorf("%s was removed though it holds no token", p)
}
}
+ t.Run("recreated copies on later boots", func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ // cloud-init writes the user data again on every boot.
+ recreate := func() {
+ for _, p := range []string{"user-data.txt", "user-data.txt.i"} {
+ f.write("/var/lib/cloud/instances/i-0abc/"+p, []byte("token "+mbtToken), 0o600)
+ }
+ }
+ recreate()
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ if hits := filesHolding(t, f.root, mbtToken); !slices.Equal(hits, []string{"/var/lib/cloud/instances/i-0abc/obj.pkl"}) {
+ t.Errorf("recreated copies survive the complete path: %v", hits)
+ }
+ // Best effort there: a failing shred is logged, the box still serves.
+ recreate()
+ dir := f.path("/var/lib/cloud/instances/i-0abc")
+ if err := os.Chmod(dir, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })
+ f.calls, f.logs = nil, nil
+ if err := f.boot(""); err != nil {
+ t.Fatalf("a scrub failure failed the complete path: %v", err)
+ }
+ if f.count("systemctl start --no-block carlos-edge.service") != 1 || len(f.logs) == 0 {
+ t.Errorf("calls %q logs %q", f.calls, f.logs)
+ }
+ })
+ t.Run("incomplete boot after the token is gone still shreds copies", func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot("scrubbed"); !errors.Is(err, errManagedBootHalted) {
+ t.Fatal(err)
+ }
+ f.write("/var/lib/cloud/instances/i-0abc/user-data.txt", []byte("token "+mbtToken), 0o600)
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ if f.exists("/var/lib/cloud/instances/i-0abc/user-data.txt") {
+ t.Error("a recreated copy survives a resumed boot")
+ }
+ })
t.Run("scrub failure stops before bootstrap", func(t *testing.T) {
f := newMBFixture(t)
scripts := f.path("/var/lib/cloud/instances/i-0abc/scripts")
@@ -1065,6 +1146,25 @@ func TestManagedBootStableTrust(t *testing.T) {
t.Fatal(err)
}
},
+ "wrong component": func(f *mbFixture) {
+ raw, etag, err := f.dir.Get(context.Background(), stableKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var w struct{ Payload, Sig string }
+ _ = json.Unmarshal(raw, &w)
+ payload, _ := base64.StdEncoding.DecodeString(w.Payload)
+ payload = bytes.Replace(payload, []byte(`"component": "router"`), []byte(`"component": "console"`), 1)
+ if !bytes.Contains(payload, []byte(`"console"`)) {
+ t.Fatal("pointer payload has no component to change")
+ }
+ w.Payload = base64.StdEncoding.EncodeToString(payload)
+ w.Sig = base64.StdEncoding.EncodeToString(ed25519.Sign(f.priv, []byte(w.Payload)))
+ raw, _ = json.Marshal(w)
+ if _, err = f.dir.Put(context.Background(), stableKey, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ },
"no linux-arm64": func(f *mbFixture) {
f.fresh()
f.publish(f.binary, "router", "stable", "linux-amd64", f.priv)
@@ -1190,3 +1290,182 @@ func TestManagedBootNoDeploymentAuthority(t *testing.T) {
t.Errorf("with a secrets key: %v %v", withKey, err)
}
}
+
+func TestManagedBootInstallInterrupted(t *testing.T) {
+ t.Run("another filesystem refused before the trade", func(t *testing.T) {
+ for _, d := range []string{"/etc/carlos", "/var/lib", "/opt/carlos"} {
+ f := newMBFixture(t)
+ f.devs = map[string]uint64{d: 1<<63 + 7}
+ if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeBootstrapFailed {
+ t.Fatalf("%s: err %v crumbs %v", d, err, f.crumbs)
+ }
+ if f.enrols() != 0 || f.used {
+ t.Errorf("%s: the token was spent on a box that cannot install by rename", d)
+ }
+ f.assertNothingStaged()
+ }
+ })
+ t.Run("another filesystem refused on resume", func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot("committed"); !errors.Is(err, errManagedBootHalted) {
+ t.Fatal(err)
+ }
+ f.devs = map[string]uint64{"/etc/carlos": 1<<63 + 7}
+ if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeBootstrapFailed {
+ t.Fatalf("err %v crumbs %v", err, f.crumbs)
+ }
+ for _, c := range mbCommitted {
+ if !f.exists(mbCommittedDir + "/" + c.name) {
+ t.Errorf("committed %s was touched by a refused install", c.name)
+ }
+ }
+ f.devs = nil
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ f.assertSucceeded()
+ })
+ type window struct {
+ name string
+ after func(f *mbFixture, c string, final string)
+ }
+ windows := []window{
+ // The rename happened; neither directory is synced yet. As left.
+ {"renamed unsynced", func(f *mbFixture, c, final string) {}},
+ // The rename did not reach disk: the source is back, no destination.
+ {"rename lost", func(f *mbFixture, c, final string) {
+ if err := os.Rename(f.path(final), f.path(mbCommittedDir+"/"+c)); err != nil {
+ f.t.Fatal(err)
+ }
+ }},
+ // The destination's entry reached disk, the source's removal did
+ // not: both hold the committed bytes.
+ {"both present", func(f *mbFixture, c, final string) {
+ b, err := os.ReadFile(f.path(final))
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ st, _ := os.Stat(f.path(final))
+ f.write(mbCommittedDir+"/"+c, b, st.Mode().Perm())
+ }},
+ }
+ for _, c := range mbCommitted {
+ for _, w := range windows {
+ t.Run(c.name+" "+w.name, func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot("install-renamed:" + c.name); !errors.Is(err, errManagedBootHalted) {
+ t.Fatal(err)
+ }
+ w.after(f, c.name, c.final)
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ f.assertInstalled()
+ })
+ }
+ t.Run(c.name+" synced", func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot("install-synced:" + c.name); !errors.Is(err, errManagedBootHalted) {
+ t.Fatal(err)
+ }
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ f.assertInstalled()
+ })
+ }
+ t.Run("a stale destination is replaced from the commit", func(t *testing.T) {
+ f := newMBFixture(t)
+ if err := f.boot("committed"); !errors.Is(err, errManagedBootHalted) {
+ t.Fatal(err)
+ }
+ f.write(managedboot.HostEnvPath, []byte("CARLOS_FLEET=other\n"), 0o600)
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ f.assertInstalled()
+ })
+}
+
+// assertInstalled: one trade, every file installed whole, and nothing left
+// in the commit.
+func (f *mbFixture) assertInstalled() {
+ f.t.Helper()
+ if f.enrols() != 1 {
+ f.t.Errorf("%d trades", f.enrols())
+ }
+ f.assertSucceeded()
+ entries, err := os.ReadDir(f.path(mbCommittedDir))
+ if err != nil || len(entries) != 0 {
+ f.t.Errorf("the commit still holds %v (%v)", entries, err)
+ }
+ creds, _ := os.ReadFile(f.path(managedboot.CredentialsPath))
+ if c, err := rootaws.ParseStaticCredentials(creds); err != nil || c.SecretAccessKey != mbtSecret {
+ f.t.Errorf("credentials not recovered: %v", err)
+ }
+ env, _ := os.ReadFile(f.path(managedboot.HostEnvPath))
+ if !bytes.Contains(env, []byte("CARLOS_FLEET=shop\n")) || !bytes.Contains(env, []byte(mbtTunnelToken)) {
+ f.t.Errorf("host.env not recovered: %q", env)
+ }
+ if _, err := os.ReadFile(f.path(managedboot.IdentityPath)); err != nil {
+ f.t.Errorf("identity not recovered: %v", err)
+ }
+}
+
+func TestManagedBootStableModeDurable(t *testing.T) {
+ f := newMBFixture(t)
+ var synced []string
+ old := mbFsyncFile
+ mbFsyncFile = func(path string) error {
+ st, err := os.Stat(path)
+ if err != nil {
+ return err
+ }
+ synced = append(synced, fmt.Sprintf("%s %v complete=%v", strings.TrimPrefix(path, f.root), st.Mode().Perm(), f.exists(mbCompleteMarker)))
+ return old(path)
+ }
+ t.Cleanup(func() { mbFsyncFile = old })
+ if err := f.boot(""); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{mbStablePart + " -rwxr-xr-x complete=false"}; !slices.Equal(synced, want) {
+ t.Errorf("stable fsyncs %q, want %q (after its chmod, before the rename and the complete marker)", synced, want)
+ }
+}
+
+func TestManagedBootStopIsNotAnOutcome(t *testing.T) {
+ f := newMBFixture(t)
+ f.cancel = true
+ f.enrol = func(w http.ResponseWriter, n int) bool {
+ w.Header().Set("Retry-After", "5")
+ w.WriteHeader(503)
+ return true
+ }
+ if err := f.boot(""); !errors.Is(err, context.Canceled) {
+ t.Fatalf("err %v", err)
+ }
+ if slices.Contains(f.crumbs, managedboot.CodeEnrolFailed) || slices.Contains(f.crumbs, managedboot.CodeBootstrapFailed) {
+ t.Errorf("a stop left a failure breadcrumb: %v", f.crumbs)
+ }
+}
+
+func TestManagedBootTransportClassLogged(t *testing.T) {
+ f := newMBFixture(t)
+ // A client that does not trust the console's certificate.
+ f.client = &http.Client{Transport: &http.Transport{}}
+ f.in.Expires = f.start.Add(10 * time.Second)
+ input, _ := json.Marshal(f.in)
+ f.write(managedboot.BootInputPath, append(input, '\n'), 0o600)
+ err := f.boot("")
+ if err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed {
+ t.Fatalf("err %v crumbs %v", err, f.crumbs)
+ }
+ if len(f.logs) == 0 || f.logs[0] != "managed boot: enrolment request failed: tls-trust" {
+ t.Errorf("logs %q", f.logs)
+ }
+ for _, l := range f.logs {
+ if strings.Contains(l, mbtToken) || strings.Contains(l, "127.0.0.1") {
+ t.Errorf("a value reached the log: %q", l)
+ }
+ }
+}
diff --git a/internal/host/managedboot_other.go b/internal/host/managedboot_other.go
index d88239d4d..83a69584a 100644
--- a/internal/host/managedboot_other.go
+++ b/internal/host/managedboot_other.go
@@ -28,3 +28,7 @@ func mbSyncDir(path string) error { return errManagedBo
func mbShred(path string) error { return errManagedBootLinux }
func mbRemoveTree(root, abs string, uid int) error { return errManagedBootLinux }
func mbHashExec(path string, uid, gid int) (string, error) { return "", errManagedBootLinux }
+
+func mbOpenRegular(path string) (*os.File, error) { return nil, errManagedBootLinux }
+
+var mbFsyncFile = func(path string) error { return errManagedBootLinux }
diff --git a/internal/host/managedstable.go b/internal/host/managedstable.go
index d4984eb36..c74b8b26f 100644
--- a/internal/host/managedstable.go
+++ b/internal/host/managedstable.go
@@ -51,7 +51,12 @@ func installManagedStableAs(ctx context.Context, s release.Store, pub ed25519.Pu
if err = release.FetchToFile(ctx, s, art.Key, part, mbArtifactLimit, art.SHA256); err != nil {
return "", "", fmt.Errorf("managed boot: stable %s: %w", p.Current.Version, err)
}
- if err = os.Chmod(part, 0o755); err != nil {
+ // The mode is part of what the complete marker vouches for: synced
+ // after the chmod, before the rename (whose directories mbMove syncs).
+ if err = os.Chmod(part, 0o755); err == nil {
+ err = mbFsyncFile(part)
+ }
+ if err != nil {
_ = os.Remove(part)
return "", "", err
}
diff --git a/internal/managedboot/cloudinit_v1.sh.tmpl b/internal/managedboot/cloudinit_v1.sh.tmpl
index 041332a3c..ecc2ac9ce 100644
--- a/internal/managedboot/cloudinit_v1.sh.tmpl
+++ b/internal/managedboot/cloudinit_v1.sh.tmpl
@@ -180,7 +180,7 @@ crumb seed_verified
put /etc/systemd/system/carlos-managed-boot.service 644 <<'UNIT'
[Unit]
Requires=nftables.service
-After=nftables.service
+After=nftables.service cloud-init.service cloud-init-network.service
Before=carlos-edge.service
[Service]
diff --git a/internal/managedboot/testdata/userdata-v1.golden b/internal/managedboot/testdata/userdata-v1.golden
index ae581ea92..ad4ade7d4 100644
--- a/internal/managedboot/testdata/userdata-v1.golden
+++ b/internal/managedboot/testdata/userdata-v1.golden
@@ -180,7 +180,7 @@ crumb seed_verified
put /etc/systemd/system/carlos-managed-boot.service 644 <<'UNIT'
[Unit]
Requires=nftables.service
-After=nftables.service
+After=nftables.service cloud-init.service cloud-init-network.service
Before=carlos-edge.service
[Service]