system: guard guard-exec, group permits, restore copy, invalid key
Review fixes for the activation guard. guard-exec apply/recover passes over a carlos.prev without ingress-proxy-v2 (in the boot judge's reader under a moves floor, directly without one). Group rollback and recovery check the permit read-only and run the guard before groupTarget consumes the permit or clears the hairpin. The restore copy is not run again: it must match the carlos.prev the guard passed, byte for byte. The guard arms on any non-empty CARLOS_INGRESS_PROXY_SOURCES, valid or not.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+550
−82
internal/host/group_maintenance.go+38 −0internal/host/guardexec.go+80 −27internal/host/proxyfeature.go+97 −26internal/host/proxyfeature_linux_test.go+86 −0internal/host/proxyfeature_test.go+191 −12internal/host/rootmovesfloor_boot.go+19 −3internal/host/systemapply.go+39 −14
Intent
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go| index 15b5cfe21..af2e9abae 100644 |
| --- a/internal/host/group_maintenance.go |
| +++ b/internal/host/group_maintenance.go |
| @@ -181,6 +181,44 @@ func (a *systemApplier) maintenanceUnconsumed(p groupMaintenancePermit) error { |
| return nil |
| } |
| +// groupTargetCheck is groupTarget's checks without its effects: the |
| +// permit's fields, its action, the installed artifact and path's digest, |
| +// read and compared, with nothing consumed and the hairpin left alone. |
| +// The activation guard (proxyfeature.go) runs between it and groupTarget, |
| +// so a refusal leaves the permit as it was. |
| +func (a *systemApplier) groupTargetCheck(path string, rollback bool) error { |
| + c, err := a.maintenanceConfig() |
| + if err != nil || c == nil { |
| + return err |
| + } |
| + g := a.maintenance() |
| + if err := checkGroupMaintenanceDirectory(g.dir, g.owner); err != nil { |
| + return err |
| + } |
| + b, err := g.read(filepath.Join(g.dir, "permit.json"), g.owner, 0600) |
| + if err != nil { |
| + return errors.Join(errGroupMaintenance, err) |
| + } |
| + p, err := a.validateMaintenancePermit(b, c) |
| + if err != nil { |
| + return err |
| + } |
| + action, want := "apply", p.NewSHA256 |
| + if rollback { |
| + action, want = "rollback", p.OldSHA256 |
| + } |
| + if action != p.Action && !(action == "rollback" && p.AllowRollback && p.Action == "apply") { |
| + return errGroupMaintenance |
| + } |
| + if err := a.validateMaintenanceArtifact(p); err != nil { |
| + return err |
| + } |
| + if !groupArtifactHolds(path, want) { |
| + return errGroupMaintenance |
| + } |
| + return nil |
| +} |
| + |
| func (a *systemApplier) groupTarget(path string, rollback bool) error { |
| if !groupMarkerPresent(a.etcDir) { |
| return nil |
diff --git a/internal/host/guardexec.go b/internal/host/guardexec.go| index 862940e90..c15872c91 100644 |
| --- a/internal/host/guardexec.go |
| +++ b/internal/host/guardexec.go |
| @@ -67,19 +67,29 @@ func RunSystemGuardExec(args []string) { |
| current := systemBinaryPath(release.OptDir()) |
| candidate := current |
| component := "router" |
| + platform := runtime.GOOS + "-" + runtime.GOARCH |
| switch args[0] { |
| case "apply", "recover": |
| - _, err := os.Stat(filepath.Join(systemRootDir(release.OptDir()), "journal.json")) |
| - if err == nil { |
| - candidate = systemPrevPath(release.OptDir()) |
| - } else if !errors.Is(err, os.ErrNotExist) { |
| + err := guardExecRouter(context.Background(), args[0], guardExecRouterBox{ |
| + opt: release.OptDir(), |
| + rootMoves: rootMovesFloorIdentity, |
| + journal: rootFloorJournalPresent, |
| + withFloor: withRootFloorGuardCandidate, |
| + prevAllowed: func(ctx context.Context, prev string) error { |
| + return proxyPrevAllowed(ctx, prev, productionProxyArmed, func(ctx context.Context, name string, args ...string) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, systemVersionWait) |
| + defer cancel() |
| + out, err := d.Run(ctx, name, platform, args...) |
| + return []byte(out), err |
| + }) |
| + }, |
| + exec: func(path string, args []string) error { return d.Exec(path, platform, args, os.Environ(), "router") }, |
| + logf: log.Printf, |
| + }) |
| + if err != nil { |
| log.Fatal(err) |
| } |
| - mode := args[0] |
| - args = []string{"system", "apply"} |
| - if mode == "recover" { |
| - args = append(args, "--recover") |
| - } |
| + return |
| case "console": |
| if len(args) < 2 { |
| log.Fatal(hostfloor.ErrFloor) |
| @@ -92,28 +102,71 @@ func RunSystemGuardExec(args []string) { |
| default: |
| log.Fatal(hostfloor.ErrFloor) |
| } |
| - if component == "router" && len(args) > 1 && args[0] == "system" { |
| - id, required, e := rootMovesFloorIdentity() |
| - if e != nil { |
| - log.Fatal(e) |
| + if err = d.Exec(candidate, platform, args, os.Environ(), component); err != nil { |
| + log.Fatal(err) |
| + } |
| +} |
| + |
| +// guardExecRouterBox is what guardExecRouter needs from the box; the |
| +// production values are RunSystemGuardExec's, tests give their own. |
| +type guardExecRouterBox struct { |
| + opt string |
| + rootMoves func() (rootFloorIdentity, bool, error) |
| + // journal is rootFloorJournalPresent: the journal through root's |
| + // checked open, for the floor judge. |
| + journal func(opt string) (bool, error) |
| + withFloor func(ctx context.Context, opt string, id rootFloorIdentity, journal bool, prevAllowed func(context.Context, string) error, effect func(string) error) error |
| + // prevAllowed is the PROXY protocol activation guard on carlos.prev |
| + // (proxyPrevAllowed): nil, or the refusal. |
| + prevAllowed func(ctx context.Context, prev string) error |
| + exec func(path string, args []string) error |
| + logf func(string, ...any) |
| +} |
| + |
| +// guardExecRouter is guard-exec apply and recover: `system apply |
| +// [--recover]` run from carlos.prev while a journal is open, else from the |
| +// current binary. Under a root moves floor the boot judge chooses, with the |
| +// activation guard in its carlos.prev reader; without one, a carlos.prev |
| +// the guard refuses (a box armed for PROXY protocol, a carlos.prev without |
| +// ingress-proxy-v2) is passed over for the current binary, whose own |
| +// recovery then refuses to restore it (edge PPv2 spec §7.3). |
| +func guardExecRouter(ctx context.Context, mode string, b guardExecRouterBox) error { |
| + current := systemBinaryPath(b.opt) |
| + candidate := current |
| + _, err := os.Stat(filepath.Join(systemRootDir(b.opt), "journal.json")) |
| + if err == nil { |
| + candidate = systemPrevPath(b.opt) |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + args := []string{"system", "apply"} |
| + if mode == "recover" { |
| + args = append(args, "--recover") |
| + } |
| + allowed := func(ctx context.Context, prev string) error { |
| + err := b.prevAllowed(ctx, prev) |
| + if err != nil { |
| + b.logf("system guard-exec %s: %v; not running it", mode, err) |
| } |
| - if required { |
| - journal, e := rootFloorJournalPresent(release.OptDir()) |
| - if e != nil { |
| - log.Fatal(e) |
| - } |
| - e = withRootFloorGuardCandidate(context.Background(), release.OptDir(), id, journal && len(args) > 1 && args[0] == "system", func(selected string) error { |
| - return d.Exec(selected, runtime.GOOS+"-"+runtime.GOARCH, args, os.Environ(), component) |
| - }) |
| - if e != nil { |
| - log.Fatal(e) |
| - } |
| - return |
| + return err |
| + } |
| + id, required, err := b.rootMoves() |
| + if err != nil { |
| + return err |
| + } |
| + if required { |
| + journal, err := b.journal(b.opt) |
| + if err != nil { |
| + return err |
| } |
| + return b.withFloor(ctx, b.opt, id, journal, allowed, func(selected string) error { |
| + return b.exec(selected, args) |
| + }) |
| } |
| - if err = d.Exec(candidate, runtime.GOOS+"-"+runtime.GOARCH, args, os.Environ(), component); err != nil { |
| - log.Fatal(err) |
| + if candidate != current && allowed(ctx, candidate) != nil { |
| + candidate = current |
| } |
| + return b.exec(candidate, args) |
| } |
| // recoverLockHeld reports whether another process holds the apply lock. |
diff --git a/internal/host/proxyfeature.go b/internal/host/proxyfeature.go| index 4a95078fd..3d51d0a6c 100644 |
| --- a/internal/host/proxyfeature.go |
| +++ b/internal/host/proxyfeature.go |
| @@ -11,6 +11,7 @@ import ( |
| "os" |
| "path/filepath" |
| "slices" |
| + "strings" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -61,15 +62,25 @@ func binaryHasFeature(ctx context.Context, run func(ctx context.Context, binary |
| return slices.Contains(v.Features, feature) |
| } |
| -// proxyGuardArmed is whether the guard applies: proxySourcesSet on the |
| -// process environment (the system units load host.env; group maintenance |
| -// and member boot pass its values in), or on host.env itself, read from |
| -// disk so that a run without the file in its environment (a recovery run |
| -// by hand) is guarded too. A host.env that exists but cannot be read |
| -// arms the guard: not knowing restricts activation (a binary with the |
| -// feature still passes); it does not lift the guard. No file is no key. |
| +// proxyKeySet is the guard's own reading of CARLOS_INGRESS_PROXY_SOURCES: |
| +// any value but empty or whitespace arms it, whether or not it parses. A |
| +// value the edge refuses still means the box was set up for PROXY protocol |
| +// (its vN edge will not start on it), so the guard fails closed rather than |
| +// allow a build below vN back. proxySourcesSet, which needs a value that |
| +// parses, stays the edge trust routes' predicate. |
| +func proxyKeySet(getenv func(string) string) bool { |
| + return strings.TrimSpace(getenv("CARLOS_INGRESS_PROXY_SOURCES")) != "" |
| +} |
| + |
| +// proxyGuardArmed is whether the guard applies: proxyKeySet on the process |
| +// environment (the system units load host.env; group maintenance and |
| +// member boot pass its values in), or on host.env itself, read from disk |
| +// so that a run without the file in its environment (a recovery run by |
| +// hand) is guarded too. A host.env that exists but cannot be read arms the |
| +// guard: not knowing restricts activation (a binary with the feature still |
| +// passes); it does not lift the guard. No file is no key. |
| func proxyGuardArmed(getenv func(string) string, readHostEnv func() (func(string) string, error)) bool { |
| - if getenv != nil && proxySourcesSet(getenv) { |
| + if getenv != nil && proxyKeySet(getenv) { |
| return true |
| } |
| if readHostEnv == nil { |
| @@ -79,7 +90,26 @@ func proxyGuardArmed(getenv func(string) string, readHostEnv func() (func(string |
| if err != nil { |
| return true |
| } |
| - return proxySourcesSet(fileEnv) |
| + return proxyKeySet(fileEnv) |
| +} |
| + |
| +// productionProxyArmed is proxyGuardArmed for a root process outside an |
| +// applier: its own environment and /etc/carlos/host.env. |
| +func productionProxyArmed() bool { |
| + return proxyGuardArmed(os.Getenv, func() (func(string) string, error) { |
| + return readProxyHostEnv("/etc/carlos/host.env") |
| + }) |
| +} |
| + |
| +// proxyPrevAllowed is the guard for a predecessor outside an applier (the |
| +// recovery unit's gate and guard-exec's choice of carlos.prev): nil when |
| +// the box is not armed, without running anything, or when prev reports |
| +// the feature; otherwise the refusal. |
| +func proxyPrevAllowed(ctx context.Context, prev string, armed func() bool, run func(ctx context.Context, binary string, args ...string) ([]byte, error)) error { |
| + if !armed() || binaryHasFeature(ctx, run, prev, ingressProxyFeature) { |
| + return nil |
| + } |
| + return &proxyFeatureRefusal{binary: prev} |
| } |
| // readProxyHostEnv reads host.env at path into a getenv, with the |
| @@ -123,20 +153,69 @@ func (a *systemApplier) proxyArmedHere() bool { |
| // binary it activates (guardRun, bounded by systemVersionWait). The |
| // exec-sandbox rule comes first, so a binary it refuses is never run. |
| func (a *systemApplier) requireFeatures(ctx context.Context, binary string) error { |
| + _, err := a.featureDigest(ctx, binary) |
| + return err |
| +} |
| + |
| +// featureDigest is requireFeatures that also returns the "sha256:<hex>" of |
| +// the bytes it found the feature in ("" when the box is not armed). The |
| +// file is hashed before and after the run, and must not change between. |
| +func (a *systemApplier) featureDigest(ctx context.Context, binary string) (string, error) { |
| if !a.proxyArmedHere() { |
| - return nil |
| + return "", nil |
| } |
| if err := a.sandboxAllows(binary); err != nil { |
| - return err |
| + return "", err |
| + } |
| + refused := &proxyFeatureRefusal{binary: binary} |
| + before, err := fileSHA256(binary) |
| + if err != nil { |
| + return "", refused |
| } |
| run := func(ctx context.Context, name string, args ...string) ([]byte, error) { |
| out, err := a.guardRun(ctx, systemVersionWait, name, args...) |
| return []byte(out), err |
| } |
| - if binaryHasFeature(ctx, run, binary, ingressProxyFeature) { |
| + if !binaryHasFeature(ctx, run, binary, ingressProxyFeature) { |
| + return "", refused |
| + } |
| + if after, err := fileSHA256(binary); err != nil || after != before { |
| + return "", refused |
| + } |
| + return before, nil |
| +} |
| + |
| +// requirePrevFeatures is the guard on carlos.prev for rollback and |
| +// recovery, before either changes anything. It records the digest of the |
| +// carlos.prev it passed, for restoreCopyAllowed. |
| +func (a *systemApplier) requirePrevFeatures(ctx context.Context) error { |
| + a.proxyPrevDigest = "" |
| + digest, err := a.featureDigest(ctx, systemPrevPath(a.optDir)) |
| + if err != nil { |
| + return err |
| + } |
| + a.proxyPrevDigest = digest |
| + return nil |
| +} |
| + |
| +// restoreCopyAllowed is the guard's last word on the restore copy, just |
| +// before its rename: on an armed box the copy must be byte for byte the |
| +// carlos.prev requirePrevFeatures passed in this run. The copy is never run |
| +// itself: the box's rules run carlos.prev under its own name (a certified |
| +// predecessor below a raised moves floor, say), and its identical copy |
| +// carries that verdict rather than being judged again under another name. |
| +func (a *systemApplier) restoreCopyAllowed(restore string) error { |
| + if !a.proxyArmedHere() { |
| return nil |
| } |
| - return &proxyFeatureRefusal{binary: binary} |
| + refused := &proxyFeatureRefusal{binary: restore} |
| + if a.proxyPrevDigest == "" { |
| + return refused |
| + } |
| + if digest, err := fileSHA256(restore); err != nil || digest != a.proxyPrevDigest { |
| + return refused |
| + } |
| + return nil |
| } |
| // RunSystemProxyAllowsPrev is `carlos system proxy-allows-prev |
| @@ -151,12 +230,7 @@ func RunSystemProxyAllowsPrev(args []string) { |
| out, err := productionSysOps().run(ctx, systemVersionWait, name, args...) |
| return []byte(out), err |
| } |
| - armed := func() bool { |
| - return proxyGuardArmed(os.Getenv, func() (func(string) string, error) { |
| - return readProxyHostEnv("/etc/carlos/host.env") |
| - }) |
| - } |
| - os.Exit(proxyAllowsPrev(context.Background(), args, "/opt/carlos/carlos.prev", armed, run, log.Printf)) |
| + os.Exit(proxyAllowsPrev(context.Background(), args, "/opt/carlos/carlos.prev", productionProxyArmed, run, log.Printf)) |
| } |
| // proxyAllowsPrev is the verb with its seams: the one path it accepts, |
| @@ -167,12 +241,9 @@ func proxyAllowsPrev(ctx context.Context, args []string, prev string, armed func |
| logf("usage: carlos system proxy-allows-prev %s", prev) |
| return 2 |
| } |
| - if !armed() { |
| - return 0 |
| - } |
| - if binaryHasFeature(ctx, run, prev, ingressProxyFeature) { |
| - return 0 |
| + if err := proxyPrevAllowed(ctx, prev, armed, run); err != nil { |
| + logf("%v", err) |
| + return 1 |
| } |
| - logf("%v", &proxyFeatureRefusal{binary: prev}) |
| - return 1 |
| + return 0 |
| } |
diff --git a/internal/host/proxyfeature_linux_test.go b/internal/host/proxyfeature_linux_test.go| index 6a7ea61e1..048c492db 100644 |
| --- a/internal/host/proxyfeature_linux_test.go |
| +++ b/internal/host/proxyfeature_linux_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "errors" |
| "os" |
| "path/filepath" |
| + "strings" |
| "testing" |
| ) |
| @@ -87,3 +88,88 @@ func TestRollbackRefusedBeforeDisruption(t *testing.T) { |
| t.Fatal("the rollback did not complete once unarmed") |
| } |
| } |
| + |
| +// groupProxyFixture is a group member armed for PROXY protocol whose |
| +// permit authorises a rollback to a carlos.prev without ingress-proxy-v2, |
| +// with the hairpin clear counted. |
| +func groupProxyFixture(t *testing.T) (*applyFixture, groupMaintenancePermit, *int) { |
| + t.Helper() |
| + f, p := maintenanceFixture(t) |
| + if err := os.WriteFile(systemPrevPath(f.a.optDir), []byte("#!/bin/sh\necho carlos v0.9.0\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + old, err := maintenanceBinaryDigest(systemPrevPath(f.a.optDir)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + current, err := maintenanceBinaryDigest(systemBinaryPath(f.a.optDir)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p.Action, p.OldSHA256, p.NewSHA256 = "rollback", old, current |
| + writeMaintenancePermit(t, f, p) |
| + clears := 0 |
| + f.a.maintenance().clearHairpin = func() error { clears++; return nil } |
| + armProxy(t, f.a.etcDir) |
| + answerVersionJSON(f, noFeatures) |
| + writeJSONDurable(filepath.Join(systemRootDir(f.a.optDir), "journal.json"), |
| + systemJournal{Phase: systemPhaseInstalled, Target: "v1.0.0", PrevBuild: "v0.9.0", StartedAt: f.now}, 0o600) |
| + return f, p, &clears |
| +} |
| + |
| +// assertGroupUntouched: the permit is unconsumed, the hairpin uncleared, |
| +// the binary and journal as they were, and systemd untouched. |
| +func assertGroupUntouched(t *testing.T, f *applyFixture, p groupMaintenancePermit, clears int, binary []byte) { |
| + t.Helper() |
| + if _, err := os.Lstat(filepath.Join(f.a.maintenance().dir, "used-"+p.Transaction+"-rollback")); !os.IsNotExist(err) { |
| + t.Fatalf("the refusal consumed the permit: %v", err) |
| + } |
| + if clears != 0 { |
| + t.Fatalf("the refusal cleared the hairpin %d times", clears) |
| + } |
| + if after, _ := os.ReadFile(systemBinaryPath(f.a.optDir)); string(after) != string(binary) { |
| + t.Fatal("the binary changed") |
| + } |
| + if j, _ := readSystemJournal(f.a.optDir); j == nil { |
| + t.Fatal("the journal was closed") |
| + } |
| + if f.called("systemctl") { |
| + t.Fatalf("the refusal touched systemd: %v", f.calls) |
| + } |
| +} |
| + |
| +// TestGroupRollbackRefusedBeforePermit: apply's rollback on a group member |
| +// refuses a featureless carlos.prev before groupTarget consumes the |
| +// rollback permit or clears the hairpin. Unarmed, the same call does |
| +// consume it, which is what makes the order matter. |
| +func TestGroupRollbackRefusedBeforePermit(t *testing.T) { |
| + f, p, clears := groupProxyFixture(t) |
| + binary, _ := os.ReadFile(systemBinaryPath(f.a.optDir)) |
| + j := systemJournal{Phase: systemPhaseInstalled, Target: "v1.0.0", PrevBuild: "v0.9.0"} |
| + err := f.a.rollback(context.Background(), systemRequest{Version: "v1.0.0", PromotedAt: f.now}, "gate", &j) |
| + if err == nil || !strings.Contains(err.Error(), (&proxyFeatureRefusal{binary: systemPrevPath(f.a.optDir)}).Error()) { |
| + t.Fatalf("rollback: %v", err) |
| + } |
| + assertGroupUntouched(t, f, p, *clears, binary) |
| + if err := os.Remove(filepath.Join(f.a.etcDir, "carlos", "host.env")); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = f.a.rollback(context.Background(), systemRequest{Version: "v1.0.0", PromotedAt: f.now}, "gate", &j) |
| + if _, err := os.Lstat(filepath.Join(f.a.maintenance().dir, "used-"+p.Transaction+"-rollback")); err != nil || *clears == 0 { |
| + t.Fatalf("unarmed, the rollback did not reach its permit: %v, clears %d", err, *clears) |
| + } |
| +} |
| + |
| +// TestGroupRecoveryRefusedBeforePermit: recovery on a group member refuses |
| +// a featureless carlos.prev before groupTarget consumes the rollback |
| +// permit or clears the hairpin. |
| +func TestGroupRecoveryRefusedBeforePermit(t *testing.T) { |
| + f, p, clears := groupProxyFixture(t) |
| + binary, _ := os.ReadFile(systemBinaryPath(f.a.optDir)) |
| + _, err := f.a.recoverIfNeeded(context.Background()) |
| + var refusal *proxyFeatureRefusal |
| + if !errors.As(err, &refusal) || refusal.binary != systemPrevPath(f.a.optDir) { |
| + t.Fatalf("recovery: %v", err) |
| + } |
| + assertGroupUntouched(t, f, p, *clears, binary) |
| +} |
diff --git a/internal/host/proxyfeature_test.go b/internal/host/proxyfeature_test.go| index 9fe4ac1ed..de555a5fc 100644 |
| --- a/internal/host/proxyfeature_test.go |
| +++ b/internal/host/proxyfeature_test.go |
| @@ -10,6 +10,8 @@ import ( |
| "strings" |
| "testing" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/moves" |
| ) |
| // proxyFeatureLine is what a build with the feature prints for |
| @@ -19,11 +21,17 @@ const proxyFeatureLine = `{"version":"v9","features":["ingress-proxy-v2"]}` + "\ |
| // armProxy writes a host.env under etcDir that arms the box for PROXY |
| // protocol, as the region's parameters put it there. |
| func armProxy(t *testing.T, etcDir string) { |
| + t.Helper() |
| + armProxyWith(t, etcDir, "10.0.1.5,10.0.2.6") |
| +} |
| + |
| +// armProxyWith is armProxy with the key's value given, valid or not. |
| +func armProxyWith(t *testing.T, etcDir, value string) { |
| t.Helper() |
| if err := os.MkdirAll(filepath.Join(etcDir, "carlos"), 0o755); err != nil { |
| t.Fatal(err) |
| } |
| - if err := os.WriteFile(filepath.Join(etcDir, "carlos", "host.env"), []byte("CARLOS_REGION=ie\nCARLOS_INGRESS_PROXY_SOURCES=10.0.1.5,10.0.2.6\n"), 0o600); err != nil { |
| + if err := os.WriteFile(filepath.Join(etcDir, "carlos", "host.env"), []byte("CARLOS_REGION=ie\nCARLOS_INGRESS_PROXY_SOURCES="+value+"\n"), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| } |
| @@ -105,7 +113,11 @@ func TestProxyGuardArmed(t *testing.T) { |
| {"process environment", env("10.0.1.5"), file("", nil), true}, |
| {"host.env on disk", env(""), file("10.0.1.5", nil), true}, |
| {"host.env unreadable", env(""), file("", errors.New("permission denied")), true}, |
| - {"a value the edge refuses", env("8.8.8.8"), file("", nil), false}, |
| + // The guard fails closed on a value the edge refuses (it reads the |
| + // raw key, not proxySourcesSet), from either source. |
| + {"a value the edge refuses", env("8.8.8.8"), file("", nil), true}, |
| + {"a value the edge refuses, on disk", env(""), file("not-an-address", nil), true}, |
| + {"whitespace only", env(" "), file(" \t", nil), false}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| if got := proxyGuardArmed(tc.getenv, tc.read); got != tc.want { |
| @@ -172,6 +184,21 @@ func TestStageRefusesBinaryWithoutFeature(t *testing.T) { |
| } |
| } |
| +// TestStageRefusesOnAnInvalidKey: a CARLOS_INGRESS_PROXY_SOURCES the edge |
| +// refuses still arms the guard (fail closed), so a candidate without the |
| +// feature is refused. |
| +func TestStageRefusesOnAnInvalidKey(t *testing.T) { |
| + f, _ := applyHappy(t) |
| + armProxyWith(t, f.a.etcDir, "8.8.8.8") |
| + answerVersionJSON(f, noFeatures) |
| + if err := f.a.Run(context.Background(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := f.result(); r == nil || r.Outcome != systemOutcomeRefused || !strings.Contains(r.Reason, "CARLOS_INGRESS_PROXY_SOURCES is set") { |
| + t.Fatalf("result = %+v", r) |
| + } |
| +} |
| + |
| // TestStageAllowsWithoutKey: the same candidate on a box without the key |
| // installs as it always has, and nothing is asked for --json. |
| func TestStageAllowsWithoutKey(t *testing.T) { |
| @@ -319,22 +346,56 @@ func TestRecoveryRestoresPrevWithFeature(t *testing.T) { |
| if !strings.Contains(string(bin), "carlos v1") { |
| t.Fatal("carlos.prev not restored") |
| } |
| - for _, want := range []string{"run carlos.prev version --json", "run carlos.restore version --json"} { |
| - if !f.called(want) { |
| - t.Fatalf("%q not asked: %v", want, f.calls) |
| + if !f.called("run carlos.prev version --json") { |
| + t.Fatalf("carlos.prev not asked: %v", f.calls) |
| + } |
| + if f.called("run carlos.restore") { |
| + t.Fatalf("the restore copy was run: %v", f.calls) |
| + } |
| +} |
| + |
| +// TestRestoreCopyCarriesPrevVerdict: the restore copy is never run; it |
| +// carries the verdict of the carlos.prev it is a byte-for-byte copy of. |
| +// Here the box's run rules refuse the copy under its own name, as guardRun |
| +// does for carlos.restore when a raised moves floor is met only by a |
| +// certified predecessor (allowed as carlos.prev, guardtransaction.go): the |
| +// restore still goes through. |
| +func TestRestoreCopyCarriesPrevVerdict(t *testing.T) { |
| + f := recoveryOnArmedBox(t) |
| + answerVersionJSON(f, func(string) (string, bool) { return proxyFeatureLine, true }) |
| + run := f.a.ops.run |
| + f.a.ops.run = func(ctx context.Context, timeout time.Duration, name string, args ...string) (string, error) { |
| + if filepath.Base(name) == "carlos.restore" { |
| + f.calls = append(f.calls, "run carlos.restore "+strings.Join(args, " ")) |
| + return "", errRootFloorHistory |
| } |
| + return run(ctx, timeout, name, args...) |
| + } |
| + if err := f.a.Run(context.Background(), true); err != nil { |
| + t.Fatal(err) |
| + } |
| + bin, _ := os.ReadFile(systemBinaryPath(f.a.optDir)) |
| + if !strings.Contains(string(bin), "carlos v1") { |
| + t.Fatal("carlos.prev not restored") |
| + } |
| + if f.called("run carlos.restore") { |
| + t.Fatalf("the restore copy was run: %v", f.calls) |
| } |
| } |
| -// TestRestoreRefusesACopyWithoutFeature: the restore copy is asked again |
| -// under the activation guard, just before its rename; a copy that does |
| -// not report the feature is not renamed in, is removed, and the journal |
| -// stays. |
| +// TestRestoreRefusesACopyWithoutFeature: the restore copy is checked again |
| +// under the activation guard, just before its rename; a copy that is not |
| +// the carlos.prev the guard passed, byte for byte, is not renamed in, is |
| +// removed, and the journal stays. |
| func TestRestoreRefusesACopyWithoutFeature(t *testing.T) { |
| f := recoveryOnArmedBox(t) |
| - answerVersionJSON(f, func(name string) (string, bool) { |
| - return proxyFeatureLine, filepath.Base(name) == "carlos.prev" |
| - }) |
| + answerVersionJSON(f, func(string) (string, bool) { return proxyFeatureLine, true }) |
| + restore := systemBinaryPath(f.a.optDir) + ".restore" |
| + f.a.beforeSwap = func() { |
| + if err := os.WriteFile(restore, []byte("#!/bin/sh\necho carlos v0\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| err := f.a.Run(context.Background(), true) |
| var refusal *proxyFeatureRefusal |
| if !errors.As(err, &refusal) || refusal.binary != systemBinaryPath(f.a.optDir)+".restore" { |
| @@ -459,3 +520,121 @@ func TestRecoverUnitGatesPrev(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// TestGuardExecRecoveryPassesOverFeaturelessPrev: guard-exec recover and |
| +// apply on a guarded box (the guard binary and its marker present, so the |
| +// recovery unit never reaches proxy-allows-prev) choose carlos.prev only |
| +// when the activation guard allows it, with or without a root moves |
| +// floor, and run the current binary otherwise. |
| +func TestGuardExecRecoveryPassesOverFeaturelessPrev(t *testing.T) { |
| + oldRun := func(_ context.Context, binary string, args ...string) ([]byte, error) { |
| + return []byte("carlos v0.34.49\n"), nil |
| + } |
| + newRun := func(_ context.Context, binary string, args ...string) ([]byte, error) { |
| + return []byte(proxyFeatureLine), nil |
| + } |
| + armed := func() bool { return true } |
| + for _, tc := range []struct { |
| + name string |
| + mode string |
| + journal bool |
| + required bool |
| + run func(context.Context, string, ...string) ([]byte, error) |
| + want string // "current" or "prev" |
| + }{ |
| + {"recover, featureless prev", "recover", true, false, oldRun, "current"}, |
| + {"apply, featureless prev", "apply", true, false, oldRun, "current"}, |
| + {"recover, prev with the feature", "recover", true, false, newRun, "prev"}, |
| + {"recover, no journal", "recover", false, false, oldRun, "current"}, |
| + {"recover under a moves floor, featureless prev", "recover", true, true, oldRun, "current"}, |
| + {"recover under a moves floor, prev with the feature", "recover", true, true, newRun, "prev"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + opt := t.TempDir() |
| + if tc.journal { |
| + os.MkdirAll(systemRootDir(opt), 0o755) |
| + writeJSONDurable(filepath.Join(systemRootDir(opt), "journal.json"), systemJournal{Phase: systemPhaseInstalled, Target: "v2", PrevBuild: "v1"}, 0o600) |
| + } |
| + var ran, ranArgs string |
| + asked := 0 |
| + b := guardExecRouterBox{ |
| + opt: opt, |
| + rootMoves: func() (rootFloorIdentity, bool, error) { return rootFloorIdentity{}, tc.required, nil }, |
| + journal: func(opt string) (bool, error) { |
| + _, err := os.Stat(filepath.Join(systemRootDir(opt), "journal.json")) |
| + return err == nil, nil |
| + }, |
| + // The floor judge's own choice is prev whenever its reader |
| + // passes; the reader it is handed must carry the guard. |
| + withFloor: func(ctx context.Context, opt string, _ rootFloorIdentity, journal bool, prevAllowed func(context.Context, string) error, effect func(string) error) error { |
| + reader := guardPrevReader(func(context.Context, string) error { return nil }, prevAllowed) |
| + if journal && reader(ctx, systemPrevPath(opt)) == nil { |
| + return effect(systemPrevPath(opt)) |
| + } |
| + return effect(systemBinaryPath(opt)) |
| + }, |
| + prevAllowed: func(ctx context.Context, prev string) error { |
| + asked++ |
| + return proxyPrevAllowed(ctx, prev, armed, tc.run) |
| + }, |
| + exec: func(path string, args []string) error { |
| + ran, ranArgs = path, strings.Join(args, " ") |
| + return nil |
| + }, |
| + logf: t.Logf, |
| + } |
| + if err := guardExecRouter(context.Background(), tc.mode, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := systemBinaryPath(opt) |
| + if tc.want == "prev" { |
| + want = systemPrevPath(opt) |
| + } |
| + wantArgs := "system apply" |
| + if tc.mode == "recover" { |
| + wantArgs += " --recover" |
| + } |
| + if ran != want || ranArgs != wantArgs { |
| + t.Fatalf("ran %s %q, want %s %q", ran, ranArgs, want, wantArgs) |
| + } |
| + if !tc.journal && asked != 0 { |
| + t.Fatal("asked carlos.prev with no journal open") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestGuardBootJudgeRefusesFeaturelessPrev: under a root moves floor the |
| +// real boot judge, given guardPrevReader, passes over a carlos.prev the |
| +// activation guard refuses and falls back to the current binary through |
| +// its own checks; with the guard allowing (or absent) it keeps carlos.prev. |
| +func TestGuardBootJudgeRefusesFeaturelessPrev(t *testing.T) { |
| + f := rootMovesFloors{private: &rollbackMemory{files: map[string][]byte{}}, public: &rollbackMemory{files: map[string][]byte{}}, identity: rootFloorIdentity{Deployment: "d", Box: "b", Enrollment: "e"}} |
| + bound := moves.Floor{Min: 1, MinRelease: "v2.0.0"} |
| + if err := f.reconstruct(t.Context(), rootFloorReconstruction{Identity: f.identity, Floor: &bound, Source: "history", Digest: floorTestDigest, Authorization: floorTestAuthorization(t, f)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := rootFloorBinary{Version: "v2.0.0", Protocol: 1, Digest: floorTestDigest} |
| + j := rootFloorJudge{floors: f, current: "current", prev: "prev", binary: func(string) (rootFloorBinary, error) { return b, nil }, idle: func(context.Context) error { return nil }} |
| + if err := j.judge(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + gate := func(context.Context, string) error { return nil } |
| + idle := func(context.Context) error { return nil } |
| + refuse := func(_ context.Context, prev string) error { return &proxyFeatureRefusal{binary: prev} } |
| + allow := func(context.Context, string) error { return nil } |
| + for _, tc := range []struct { |
| + name string |
| + guard func(context.Context, string) error |
| + want string |
| + }{ |
| + {"refused", refuse, "current"}, |
| + {"allowed", allow, "prev"}, |
| + {"no guard", nil, "prev"}, |
| + } { |
| + got, err := rootFloorBootCandidate(t.Context(), j, true, guardPrevReader(gate, tc.guard), idle) |
| + if err != nil || got != tc.want { |
| + t.Fatalf("%s: got %q %v, want %s", tc.name, got, err, tc.want) |
| + } |
| + } |
| +} |
diff --git a/internal/host/rootmovesfloor_boot.go b/internal/host/rootmovesfloor_boot.go| index 7d105dbc6..d0fe3dede 100644 |
| --- a/internal/host/rootmovesfloor_boot.go |
| +++ b/internal/host/rootmovesfloor_boot.go |
| @@ -120,7 +120,23 @@ func rootFloorAllowsPrevIdentity(opt string, id rootFloorIdentity) error { |
| return rootFloorPrevVerdict(rootFloorJudge{floors: f, current: systemBinaryPath(opt), prev: systemPrevPath(opt), binary: func(path string) (rootFloorBinary, error) { return readRootFloorBinary(opt, path) }}) |
| } |
| -func withRootFloorGuardCandidate(ctx context.Context, opt string, id rootFloorIdentity, journal bool, effect func(string) error) error { |
| +// guardPrevReader is the boot judge's reader for carlos.prev under the |
| +// guard: its own floor gate first, then, when prevAllowed is set, the PROXY |
| +// protocol activation guard (proxyPrevAllowed). Either refusing makes the |
| +// judge fall back to the current binary through its own checks. |
| +func guardPrevReader(floorGate, prevAllowed func(context.Context, string) error) func(context.Context, string) error { |
| + return func(ctx context.Context, path string) error { |
| + if err := floorGate(ctx, path); err != nil { |
| + return err |
| + } |
| + if prevAllowed != nil { |
| + return prevAllowed(ctx, path) |
| + } |
| + return nil |
| + } |
| +} |
| + |
| +func withRootFloorGuardCandidate(ctx context.Context, opt string, id rootFloorIdentity, journal bool, prevAllowed func(context.Context, string) error, effect func(string) error) error { |
| return withClaimRootRelease(ctx, true, func() (rootstate.Store, error) { return rootstate.Open(rootReleasePrivate, true, false) }, func() error { |
| return withPrevLock(opt, func() error { |
| idleErr := rootFloorDowngradeIdle(ctx) |
| @@ -145,10 +161,10 @@ func withRootFloorGuardCandidate(ctx context.Context, opt string, id rootFloorId |
| } |
| defer unlockSeeds() |
| j := rootFloorJudge{floors: f, current: systemBinaryPath(opt), prev: systemPrevPath(opt), binary: func(path string) (rootFloorBinary, error) { return readRootFloorBinary(opt, path) }} |
| - candidate, err := rootFloorBootCandidate(ctx, j, journal, func(ctx context.Context, path string) error { |
| + candidate, err := rootFloorBootCandidate(ctx, j, journal, guardPrevReader(func(ctx context.Context, path string) error { |
| _, err := productionSysOps().run(ctx, systemVersionWait, path, "system", "floor-allows-prev", "--root", opt) |
| return err |
| - }, func(context.Context) error { return idleErr }) |
| + }, prevAllowed), func(context.Context) error { return idleErr }) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index 987b10301..e8678e08b 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -309,6 +309,10 @@ type systemApplier struct { |
| // CARLOS_INGRESS_PROXY_SOURCES from, besides host.env under etcDir |
| // (proxyArmedHere): os.Getenv in production. Nil reads host.env only. |
| proxyEnv func(string) string |
| + // proxyPrevDigest is the carlos.prev requirePrevFeatures last passed |
| + // ("sha256:<hex>", "" when not armed or not passed), which the restore |
| + // copy must match before its rename (restoreCopyAllowed). |
| + proxyPrevDigest string |
| } |
| // ingressDrainConfigured is host.env's half of the drain's arming (spec |
| @@ -2045,21 +2049,27 @@ func (a *systemApplier) arm(plan bootstrapPlan) error { |
| // build's, restoring them again would change nothing, and the box needs a |
| // human rather than a loop. |
| func (a *systemApplier) rollback(ctx context.Context, req systemRequest, reason string, j *systemJournal) error { |
| - if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil { |
| - return err |
| - } |
| - a.ops.logf("system apply: %s %s: rolling back: %s", a.channel, j.Target, reason) |
| failed := func(what string, err error) error { |
| _ = a.writeResult(req, systemOutcomeRollbackFailed, reason+"; "+what+": "+err.Error()) |
| return fmt.Errorf("system apply: rollback of %s failed: %s: %v", j.Target, what, err) |
| } |
| - // The activation guard (edge PPv2 spec §7.3) before the restore's |
| - // drain, quiesce or copy: on a box armed for PROXY protocol, a |
| - // carlos.prev without ingress-proxy-v2 is not rolled back to. The |
| - // journal stays, as for any refused restore. |
| - if err := a.requireFeatures(ctx, systemPrevPath(a.optDir)); err != nil { |
| + // The activation guard (edge PPv2 spec §7.3) before anything changes: |
| + // on a box armed for PROXY protocol, a carlos.prev without |
| + // ingress-proxy-v2 is not rolled back to. On a group member the permit |
| + // and carlos.prev's digest are checked first without consuming the |
| + // permit (groupTargetCheck), so a refusal leaves it unconsumed and the |
| + // hairpin uncleared; groupTarget consumes it only once the guard has |
| + // passed. The journal stays, as for any refused restore. |
| + if err := a.groupTargetCheck(systemPrevPath(a.optDir), true); err != nil { |
| + return err |
| + } |
| + if err := a.requirePrevFeatures(ctx); err != nil { |
| return failed("restore", err) |
| } |
| + if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil { |
| + return err |
| + } |
| + a.ops.logf("system apply: %s %s: rolling back: %s", a.channel, j.Target, reason) |
| // The rollback restarts the edge, so it asks for the ingress drain, |
| // after the restore's refusals and before its quiesce (W6 spec §5.3). |
| plan, err := a.restoreFiles(ctx, j, true) |
| @@ -2198,9 +2208,9 @@ func (a *systemApplier) restoreFiles(ctx context.Context, j *systemJournal, drai |
| return err |
| } |
| // The activation guard once more, on the copy that is renamed in |
| - // (edge PPv2 spec §7.3): rollback and recovery checked carlos.prev |
| - // before anything moved; this is the bytes about to run. |
| - if err := a.requireFeatures(ctx, restore); err != nil { |
| + // (edge PPv2 spec §7.3): rollback and recovery passed carlos.prev |
| + // before anything moved, and the copy must be those same bytes. |
| + if err := a.restoreCopyAllowed(restore); err != nil { |
| return err |
| } |
| renamed = true |
| @@ -2319,7 +2329,20 @@ func (a *systemApplier) recoverIfNeeded(ctx context.Context) (bool, error) { |
| if err != nil || j == nil { |
| return false, err |
| } |
| + // The activation guard (edge PPv2 spec §7.3) runs before the restore |
| + // touches anything. A group member always restores (below), so its |
| + // guard runs here, after a check of the permit and carlos.prev's digest |
| + // that consumes nothing (groupTargetCheck) and before groupTarget |
| + // consumes the permit and clears the hairpin. |
| + prevChecked := false |
| if groupMarkerPresent(a.etcDir) { |
| + if err := a.groupTargetCheck(systemPrevPath(a.optDir), true); err != nil { |
| + return false, err |
| + } |
| + if err := a.requirePrevFeatures(ctx); err != nil { |
| + return false, fmt.Errorf("system apply: recovery: %w", err) // journal kept, permit unconsumed |
| + } |
| + prevChecked = true |
| if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil { |
| return false, err |
| } |
| @@ -2388,8 +2411,10 @@ func (a *systemApplier) recoverIfNeeded(ctx context.Context) (bool, error) { |
| // without ingress-proxy-v2 is not restored. The current binary and the |
| // journal stay, and the run fails with the reason (the recovery unit's |
| // own gate, proxy-allows-prev, sent it here rather than to carlos.prev). |
| - if err := a.requireFeatures(ctx, systemPrevPath(a.optDir)); err != nil { |
| - return false, fmt.Errorf("system apply: recovery: %w", err) // journal kept |
| + if !prevChecked { |
| + if err := a.requirePrevFeatures(ctx); err != nil { |
| + return false, fmt.Errorf("system apply: recovery: %w", err) // journal kept |
| + } |
| } |
| plan, err := a.restoreFiles(ctx, j, false) |
| if err != nil { |