carlos / platform Public

host: refuse binaries below the storage generations floor on activation

A fixed box could roll back, by apply, recovery or guard-exec, to a
build that reads a generations lock as an ordinary HA lock (Astra branch
review P1). This mirrors the PPv2 activation floor:

- carlos version --json now reports replica-generations-1.
- A box whose CARLOS_HA_GENERATIONS is anything but empty, 0 or off
  refuses to activate a binary that does not report it, on every path
  the PROXY protocol guard covers (featureDigest, restoreCopyAllowed,
  guard-exec's choice of carlos.prev), and keeps the running binary.
- New box verb carlos system generations-allows-prev, with
  proxy-allows-prev's exit contract (0 allowed or not armed, 1 refused,
  2 bad arguments), gates carlos.prev in the recovery unit straight
  after proxy-allows-prev.
- The floor is sticky: a root pass that sees the switch on (the adopt
  pass's unit repair, or any guard) records /etc/carlos/
  ha-generations-floor (0600, root, beside host.env), and the guard
  stays armed while it is there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0c87efc421b69c5e1d549d5bd92b66197012fcee parent 954f146
16 files changed, +922 −28
  • .amadan/code-health.tsv +1 −0
  • commands_test.go +1 −1
  • docs/parity.md +1 −1
  • internal/host/execsandboxfloor_test.go +4 −2
  • internal/host/genfloor.go +251 −0
  • internal/host/genfloor_linux_test.go +45 −0
  • internal/host/genfloor_test.go +529 −0
  • internal/host/guardexec.go +9 −4
  • internal/host/proxyfeature.go +53 −16
  • internal/host/systemunits.go +4 −0
  • internal/host/units/carlos-system-recover.service +8 −2
  • internal/version/features.go +9 −1
  • parity/cli.tsv +1 −0
  • parity/parity.tsv +1 −1
  • system.go +3 −0
  • testdata/clireg-golden.jsonl +2 −0
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index ae1864170..29788ab43 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2072,6 +2072,7 @@ host-context internal/host RunSystemApply context.Background 1
host-context internal/host RunSystemBoxPublishRecord context.Background 1
host-context internal/host RunSystemEdge context.Background 1
host-context internal/host RunSystemFiles context.Background 1
+host-context internal/host RunSystemGenerationsAllowsPrev context.Background 1 # raised: the recovery unit's generations floor gate, proxy-allows-prev's shape (a box verb entry with no caller context)
host-context internal/host RunSystemGuardArm context.Background 3
host-context internal/host RunSystemGuardExec context.Background 2
host-context internal/host RunSystemInstallChannel context.Background 1
diff --git a/commands_test.go b/commands_test.go
index c39d4dbaf..2b214013b 100644
--- a/commands_test.go
+++ b/commands_test.go
@@ -134,7 +134,7 @@ func TestVersionJSONHasFeatures(t *testing.T) {
t.Errorf("carlos version %v printed %q, want %q", args, got, bare)
}
}
- want := `{"version":"` + version.Build + `","features":["ingress-proxy-v2"]}` + "\n"
+ want := `{"version":"` + version.Build + `","features":["ingress-proxy-v2","replica-generations-1"]}` + "\n"
for _, flag := range []string{"--json", "-json"} {
got := run(flag)
if got != want {
diff --git a/docs/parity.md b/docs/parity.md
index 0e12c449a..a261131a4 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -440,7 +440,7 @@ Discussion #742.
| proof | box | `proof keygen`<br>`proof get`<br>`proof put`<br>`proof history` | | Dev proofs a box needs to adopt. |
| relay-box | box | `relay serve`<br>`relay keygen` | | Runs the relay, or mints a region master key. |
| mailer-serve | box | `mailer serve` | | Runs the box-local mailer; the unit's entry point. |
-| system-box | box | `system apply`<br>`system files`<br>`system guard-arm`<br>`system guard-exec`<br>`system floor-allows-prev`<br>`system exec-sandbox-allows-prev`<br>`system runsc-ensure`<br>`system install-channel`<br>`system host-env`<br>`system named-units`<br>`system db-worker`<br>`system journal-migrate`<br>`system group-maintenance`<br>`system edge trust-barrier`<br>`system edge trust-resume`<br>`system edge trust-status`<br>`system proxy-allows-prev`<br>`system box publish-record` | | Root oneshots and units on a box. |
+| system-box | box | `system apply`<br>`system files`<br>`system guard-arm`<br>`system guard-exec`<br>`system floor-allows-prev`<br>`system exec-sandbox-allows-prev`<br>`system runsc-ensure`<br>`system install-channel`<br>`system host-env`<br>`system named-units`<br>`system db-worker`<br>`system journal-migrate`<br>`system group-maintenance`<br>`system edge trust-barrier`<br>`system edge trust-resume`<br>`system edge trust-status`<br>`system proxy-allows-prev`<br>`system generations-allows-prev`<br>`system box publish-record` | | Root oneshots and units on a box. |
| status-dry-run | box | `status [--dry-run]` | | A leak check against a fixture fleet, run locally. |
| devbox-serve | box | `devbox serve` | | The devbox service under systemd. |
diff --git a/internal/host/execsandboxfloor_test.go b/internal/host/execsandboxfloor_test.go
index d34c627f0..c77813108 100644
--- a/internal/host/execsandboxfloor_test.go
+++ b/internal/host/execsandboxfloor_test.go
@@ -150,9 +150,11 @@ func TestExecSandboxRecoveryUnit(t *testing.T) {
t.Fatalf("bad recovery command %s", command)
}
// Preserve the old expression byte for byte except for the one gate
- // and, after it, the PROXY protocol gate (TestRecoverUnitGatesPrev).
+ // and, after it, the PROXY protocol gate (TestRecoverUnitGatesPrev) and
+ // the storage generations floor gate
+ // (TestRecoverUnitGatesPrevOnGenerations).
original := `if [ -x /opt/carlos/system/guard/carlos ] && { [ -e /var/lib/carlos-claims/authority/exec/census.json ] || [ -L /var/lib/carlos-claims/authority/exec/census.json ] || [ -e /opt/carlos/system/guard/moves ] || [ -L /opt/carlos/system/guard/moves ]; }; then exec /opt/carlos/system/guard/carlos system guard-exec recover; fi; if [ -f /opt/carlos/system/router/journal.json ] && [ -x /opt/carlos/carlos.prev ] && [ ! -L /data/.moves/floor.min-release ] && { [ ! -e /data/.moves/floor.min-release ] || [ -f /data/.moves/floor.min-release ]; } && { ! [ -s /data/.moves/floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/floor.min-release /opt/carlos/carlos.prev.allowed; } && [ ! -L /data/.moves/seeds-floor.min-release ] && { [ ! -e /data/.moves/seeds-floor.min-release ] || [ -f /data/.moves/seeds-floor.min-release ]; } && { ! [ -s /data/.moves/seeds-floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/seeds-floor.min-release /opt/carlos/carlos.prev.seeds-allowed; }; then exec /opt/carlos/carlos.prev system apply --recover; fi; exec /opt/carlos/carlos system apply --recover`
- if strings.Replace(strings.Replace(command, gate+proxyRecoveryGate, gate, 1), gate, "", 1) != original {
+ if strings.Replace(strings.Replace(command, gate+proxyRecoveryGate+generationsRecoveryGate, gate, 1), gate, "", 1) != original {
t.Fatal("recovery changed outside gate")
}
for _, gateBody := range []string{"exit 1\n", "missing"} {
diff --git a/internal/host/genfloor.go b/internal/host/genfloor.go
new file mode 100644
index 000000000..b58338c6e
--- /dev/null
+++ b/internal/host/genfloor.go
@@ -0,0 +1,251 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// The storage generations activation floor (region HA storage generations,
+// branch review P1), the same guard as PROXY protocol's (proxyfeature.go)
+// on its own trigger. A box whose storage-generations switch is on serves
+// hosts whose locks are in generations mode; a build that does not know
+// that mode reads such a lock as an ordinary HA lock, can take it once it
+// expires, restores the stale root replica and replicates over it. So such
+// a box activates no binary that does not report replica-generations-1 in
+// `carlos version --json`, on the same activation paths and with the same
+// checks as the PROXY protocol guard (featureDigest, restoreCopyAllowed,
+// the recovery unit's generations-allows-prev gate and guard-exec's choice
+// of carlos.prev).
+//
+// The guard is sticky. Once a root process on the box has seen the switch
+// on, it records /etc/carlos/ha-generations-floor (beside host.env, owned
+// like it: the process's user, root on a box, mode 0600), and the guard
+// stays armed while that file is there, whatever host.env says later.
+// Hosts that went to generations mode stay in it after the switch is
+// removed, so removing the switch must not lift the floor. The file is
+// recorded by the adopt pass's unit repair (ensureSystemUnits: hourly, at
+// boot and on the agent's stage and config passes), and by every
+// activation guard that finds the switch on. Only root can create
+// or remove it; nothing in the platform removes it.
+
+// generationsFeature is the feature the guard asks a binary for.
+const generationsFeature = version.FeatureReplicaGenerations1
+
+// generationsSwitchKey is the box's storage-generations switch, as the
+// activator reads it (internal/activator, generationsSwitchEnv).
+const generationsSwitchKey = "CARLOS_HA_GENERATIONS"
+
+// generationsFloorMarker is the sticky record's name under <etc>/carlos.
+const generationsFloorMarker = "ha-generations-floor"
+
+// generationsFloorMarkerBody is the record's content. Only its presence
+// is read.
+const generationsFloorMarkerBody = generationsFeature + "\n"
+
+// generationsFeatureRefusal is the guard's refusal of binary.
+type generationsFeatureRefusal struct{ binary string }
+
+func (e *generationsFeatureRefusal) Error() string {
+ return "this box serves region HA storage generations (CARLOS_HA_GENERATIONS is or was on); " + e.binary +
+ " does not, so it cannot run here. Roll forward, or to a build at or above the first one with replica-generations-1."
+}
+
+// generationsSwitchSet is the guard's own reading of the switch: any value
+// but empty, whitespace, "0" or "off" arms it. The activator turns
+// generations on only for "on" and "fast"; the guard fails closed on
+// anything else that is not plainly off, so a mistyped value never lets a
+// build below the floor back.
+func generationsSwitchSet(getenv func(string) string) bool {
+ switch strings.TrimSpace(getenv(generationsSwitchKey)) {
+ case "", "0", "off":
+ return false
+ }
+ return true
+}
+
+// generationsFloorMarkerPath is the sticky record under etcDir.
+func generationsFloorMarkerPath(etcDir string) string {
+ return filepath.Join(etcDir, "carlos", generationsFloorMarker)
+}
+
+// generationsFloorMarked reports whether the sticky record is there:
+// anything at its path counts (it is never opened). An error other than
+// "not there" is reported, and the guard arms on it.
+func generationsFloorMarked(path string) (bool, error) {
+ _, err := os.Lstat(path)
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ return false, err
+}
+
+// recordGenerationsFloor creates the sticky record under etcDir when it
+// is not there: create-only (a symlink or anything else at the path is
+// left alone and already counts), 0600, synced with its directory. It
+// never creates <etc>/carlos: a box without it has no host.env.
+func recordGenerationsFloor(etcDir string) error {
+ path := generationsFloorMarkerPath(etcDir)
+ if marked, err := generationsFloorMarked(path); err != nil || marked {
+ return err
+ }
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if errors.Is(err, os.ErrExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if _, err := f.WriteString(generationsFloorMarkerBody); err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Sync(); err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Close(); err != nil {
+ return err
+ }
+ return syncDir(filepath.Dir(path))
+}
+
+// generationsGuardArmed is whether the guard applies: the switch set in
+// the process environment, or in host.env read from disk (an error arms
+// it, as for PROXY protocol), or the sticky record there (an error
+// reading it arms it too). Seeing the switch on records the sticky record
+// (record; best effort: the guard is armed either way, and the adopt pass
+// logs a failure). A nil seam is a source this caller does not have.
+func generationsGuardArmed(getenv func(string) string, readHostEnv func() (func(string) string, error), marked func() (bool, error), record func() error) bool {
+ on := getenv != nil && generationsSwitchSet(getenv)
+ if !on && readHostEnv != nil {
+ fileEnv, err := readHostEnv()
+ if err != nil {
+ return true
+ }
+ on = generationsSwitchSet(fileEnv)
+ }
+ if on {
+ if record != nil {
+ _ = record()
+ }
+ return true
+ }
+ if marked == nil {
+ return false
+ }
+ m, err := marked()
+ return err != nil || m
+}
+
+// generationsArmedAt is generationsGuardArmed for a root process over
+// etcDir: its environment, <etc>/carlos/host.env through the protected
+// reader (sandboxHostEnvironmentAt) and the sticky record beside it.
+func generationsArmedAt(etcDir string, getenv func(string) string) bool {
+ hostEnv := func() (func(string) string, error) {
+ return sandboxHostEnvironmentAt(filepath.Join(etcDir, "carlos", "host.env"))
+ }
+ marked := func() (bool, error) { return generationsFloorMarked(generationsFloorMarkerPath(etcDir)) }
+ record := func() error { return recordGenerationsFloor(etcDir) }
+ return generationsGuardArmed(getenv, hostEnv, marked, record)
+}
+
+// productionGenerationsArmed is generationsArmedAt for a root process
+// outside an applier: its own environment and /etc.
+func productionGenerationsArmed() bool {
+ return generationsArmedAt("/etc", os.Getenv)
+}
+
+// generationsArmedHere is the guard for this applier: its process
+// environment seam (proxyEnv: os.Getenv in production, nil in tests), and
+// host.env and the sticky record under its etcDir. With no etcDir only
+// the environment counts.
+func (a *systemApplier) generationsArmedHere() bool {
+ if a.etcDir == "" {
+ return generationsGuardArmed(a.proxyEnv, nil, nil, nil)
+ }
+ return generationsArmedAt(a.etcDir, a.proxyEnv)
+}
+
+// generationsPrevAllowed 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 generationsPrevAllowed(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, generationsFeature) {
+ return nil
+ }
+ return &generationsFeatureRefusal{binary: prev}
+}
+
+// noteGenerationsSwitch records the sticky record when the switch is set
+// in getenv: the adopt pass's call (ensureSystemUnits), as root. A failure is
+// logged, never fatal: the pass's own work does not depend on it.
+func noteGenerationsSwitch(etcDir string, getenv func(string) string, logf func(string, ...any)) {
+ if !generationsSwitchSet(getenv) {
+ return
+ }
+ if err := recordGenerationsFloor(etcDir); err != nil {
+ logf("ALERT: storage generations floor: cannot record %s: %v", generationsFloorMarkerPath(etcDir), err)
+ }
+}
+
+// RunSystemGenerationsAllowsPrev is `carlos system generations-allows-prev
+// /opt/carlos/carlos.prev`: the recovery unit's gate on running
+// carlos.prev for the storage generations floor, the same shape and exit
+// contract as proxy-allows-prev. Exit 0 when the box is not armed, without
+// running anything, or when carlos.prev passes the exec-sandbox rule and
+// reports replica-generations-1; 1 when it is armed and carlos.prev does
+// not, or the exec-sandbox rule refuses it (then it is never run); 2 for
+// any other arguments. Any non-zero exit makes the unit run the current
+// binary's recovery, which refuses the same carlos.prev itself.
+func RunSystemGenerationsAllowsPrev(args []string) {
+ run := func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ out, err := productionSysOps().run(ctx, systemVersionWait, name, args...)
+ return []byte(out), err
+ }
+ os.Exit(generationsAllowsPrevAt(context.Background(), args, "/opt/carlos/carlos.prev", "/etc", os.Getenv, run, log.Printf))
+}
+
+// generationsAllowsPrevAt is the verb as production wires it, over the
+// predecessor and etc paths: arming from the process environment, host.env
+// and the sticky record, and the exec-sandbox rule (sandboxAllowsPrev),
+// through the protected host.env reader.
+func generationsAllowsPrevAt(ctx context.Context, args []string, prev, etcDir string, getenv func(string) string, run func(ctx context.Context, binary string, args ...string) ([]byte, error), logf func(string, ...any)) int {
+ hostEnv := func() (func(string) string, error) {
+ return sandboxHostEnvironmentAt(filepath.Join(etcDir, "carlos", "host.env"))
+ }
+ armed := func() bool { return generationsArmedAt(etcDir, getenv) }
+ sandbox := func(path string) error { return sandboxAllowsPrev(hostEnv, path) }
+ return generationsAllowsPrev(ctx, args, prev, armed, sandbox, run, logf)
+}
+
+// generationsAllowsPrev is the verb with its seams, proxyAllowsPrev's
+// shape: the one path it accepts, whether the box is armed, the
+// exec-sandbox rule, how a binary is run, and where a refusal is logged.
+func generationsAllowsPrev(ctx context.Context, args []string, prev string, armed func() bool, sandbox func(string) error, run func(ctx context.Context, binary string, args ...string) ([]byte, error), logf func(string, ...any)) int {
+ if len(args) != 1 || args[0] != prev {
+ logf("usage: carlos system generations-allows-prev %s", prev)
+ return 2
+ }
+ if !armed() {
+ return 0
+ }
+ if err := sandbox(prev); err != nil {
+ logf("%s: %v; not running it", prev, err)
+ return 1
+ }
+ if err := generationsPrevAllowed(ctx, prev, func() bool { return true }, run); err != nil {
+ logf("%v", err)
+ return 1
+ }
+ return 0
+}
diff --git a/internal/host/genfloor_linux_test.go b/internal/host/genfloor_linux_test.go
new file mode 100644
index 000000000..18ff365a1
--- /dev/null
+++ b/internal/host/genfloor_linux_test.go
@@ -0,0 +1,45 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// TestGenerationsAllowsPrevAtIsSticky: the verb as production wires it
+// (host.env through the protected reader, the sticky record beside it)
+// refuses a carlos.prev below the floor with the switch on and records
+// the sticky record; with the switch then removed it still refuses; a box
+// that never had it on runs nothing and allows.
+func TestGenerationsAllowsPrevAtIsSticky(t *testing.T) {
+ prev := filepath.Join(t.TempDir(), "carlos.prev")
+ if err := os.WriteFile(prev, []byte("#!/bin/sh\necho carlos v0.38.0\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ran := 0
+ old := func(context.Context, string, ...string) ([]byte, error) {
+ ran++
+ return []byte("carlos v0.38.0\n"), nil
+ }
+ etc := t.TempDir()
+ armGenerations(t, etc, "on")
+ if code := generationsAllowsPrevAt(context.Background(), []string{prev}, prev, etc, envOf(nil), old, t.Logf); code != 1 || ran != 1 {
+ t.Fatalf("switch on: exit %d, ran %d", code, ran)
+ }
+ assertMarked(t, etc)
+ writeHostEnvLines(t, etc) // the switch removed
+ if code := generationsAllowsPrevAt(context.Background(), []string{prev}, prev, etc, envOf(nil), old, t.Logf); code != 1 || ran != 2 {
+ t.Fatalf("switch removed: exit %d, ran %d", code, ran)
+ }
+ never := t.TempDir()
+ writeHostEnvLines(t, never, "CARLOS_HA_GENERATIONS=0")
+ if code := generationsAllowsPrevAt(context.Background(), []string{prev}, prev, never, envOf(nil), old, t.Logf); code != 0 || ran != 2 {
+ t.Fatalf("never on: exit %d, ran %d", code, ran)
+ }
+ if m, _ := generationsFloorMarked(generationsFloorMarkerPath(never)); m {
+ t.Fatal("a sticky record was written on a box that never had the switch on")
+ }
+}
diff --git a/internal/host/genfloor_test.go b/internal/host/genfloor_test.go
new file mode 100644
index 000000000..40f10de77
--- /dev/null
+++ b/internal/host/genfloor_test.go
@@ -0,0 +1,529 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// The storage generations activation floor (genfloor.go): the PROXY
+// protocol guard's tests, on the generations switch and its sticky record.
+
+// generationsFeatureLine is what a build at the floor prints for
+// `version --json`.
+const generationsFeatureLine = `{"version":"v9","features":["ingress-proxy-v2","replica-generations-1"]}` + "\n"
+
+// writeHostEnvLines writes host.env under etcDir with the given lines.
+func writeHostEnvLines(t *testing.T, etcDir string, lines ...string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(etcDir, "carlos"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ body := "CARLOS_REGION=ie\n"
+ for _, l := range lines {
+ body += l + "\n"
+ }
+ if err := os.WriteFile(filepath.Join(etcDir, "carlos", "host.env"), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// armGenerations sets the box's storage-generations switch in host.env.
+func armGenerations(t *testing.T, etcDir, value string) {
+ t.Helper()
+ writeHostEnvLines(t, etcDir, "CARLOS_HA_GENERATIONS="+value)
+}
+
+// assertMarked: the sticky record is there, 0600, with its body.
+func assertMarked(t *testing.T, etcDir string) {
+ t.Helper()
+ path := generationsFloorMarkerPath(etcDir)
+ st, err := os.Lstat(path)
+ if err != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0o600 {
+ t.Fatalf("sticky record %s: %v %v", path, st, err)
+ }
+ if b, _ := os.ReadFile(path); string(b) != "replica-generations-1\n" {
+ t.Fatalf("sticky record body %q", b)
+ }
+}
+
+// assertStageRefused: apply refused the staged candidate with the
+// generations refusal, and the box is as it was.
+func assertStageRefused(t *testing.T, f *applyFixture, req systemRequest, before []byte) {
+ t.Helper()
+ staged := filepath.Join(f.a.stagingDir(), "carlos")
+ want := (&generationsFeatureRefusal{binary: staged}).Error()
+ r := f.result()
+ if r == nil || r.Outcome != systemOutcomeRefused || !r.matches("stable", "v2", req.PromotedAt) || !strings.Contains(r.Reason, want) {
+ t.Fatalf("result = %+v, want refused with %q", r, want)
+ }
+ if after, _ := os.ReadFile(systemBinaryPath(f.a.optDir)); string(after) != string(before) {
+ t.Fatal("the running binary changed")
+ }
+ if _, err := os.Stat(systemPrevPath(f.a.optDir)); !os.IsNotExist(err) {
+ t.Fatalf("carlos.prev written: %v", err)
+ }
+ if j, _ := readSystemJournal(f.a.optDir); j != nil {
+ t.Fatalf("journal written: %+v", j)
+ }
+ if f.called("systemctl") {
+ t.Fatalf("the refusal touched systemd: %v", f.calls)
+ }
+}
+
+func TestGenerationsFeatureRefusalText(t *testing.T) {
+ got := (&generationsFeatureRefusal{binary: "/opt/carlos/carlos.prev"}).Error()
+ want := "this box serves region HA storage generations (CARLOS_HA_GENERATIONS is or was on); /opt/carlos/carlos.prev does not, so it cannot run here. Roll forward, or to a build at or above the first one with replica-generations-1."
+ if got != want {
+ t.Fatalf("refusal %q", got)
+ }
+}
+
+func TestGenerationsGuardArmed(t *testing.T) {
+ env := func(v string) func(string) string {
+ return func(k string) string {
+ if k == "CARLOS_HA_GENERATIONS" {
+ return v
+ }
+ return ""
+ }
+ }
+ file := func(v string, err error) func() (func(string) string, error) {
+ return func() (func(string) string, error) { return env(v), err }
+ }
+ marked := func(m bool, err error) func() (bool, error) { return func() (bool, error) { return m, err } }
+ for _, tc := range []struct {
+ name string
+ getenv func(string) string
+ read func() (func(string) string, error)
+ marked func() (bool, error)
+ want bool
+ recorded bool
+ }{
+ {"nothing", nil, nil, nil, false, false},
+ {"never on", env(""), file("", nil), marked(false, nil), false, false},
+ {"0", env("0"), file("0", nil), marked(false, nil), false, false},
+ {"off", env("off"), file(" off ", nil), marked(false, nil), false, false},
+ {"on in the environment", env("on"), file("", nil), marked(false, nil), true, true},
+ {"fast on disk", env(""), file("fast", nil), marked(false, nil), true, true},
+ // Fail closed: a value the activator reads as off still arms.
+ {"a mistyped value", env("yes"), file("", nil), marked(false, nil), true, true},
+ {"host.env unreadable", env(""), file("", errors.New("permission denied")), marked(false, nil), true, false},
+ // Sticky: the switch was removed, the record stays.
+ {"switch removed, record there", env(""), file("", nil), marked(true, nil), true, false},
+ {"record unreadable", env(""), file("", nil), marked(false, errors.New("permission denied")), true, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ recorded := false
+ record := func() error { recorded = true; return errors.New("read-only") }
+ if got := generationsGuardArmed(tc.getenv, tc.read, tc.marked, record); got != tc.want {
+ t.Fatalf("armed = %v, want %v", got, tc.want)
+ }
+ if recorded != tc.recorded {
+ t.Fatalf("recorded = %v, want %v", recorded, tc.recorded)
+ }
+ })
+ }
+}
+
+func TestRecordGenerationsFloor(t *testing.T) {
+ etc := t.TempDir()
+ // No <etc>/carlos: nothing is created.
+ if err := recordGenerationsFloor(etc); err == nil {
+ t.Fatal("recorded without <etc>/carlos")
+ }
+ if _, err := os.Lstat(filepath.Join(etc, "carlos")); !os.IsNotExist(err) {
+ t.Fatalf("<etc>/carlos created: %v", err)
+ }
+ os.MkdirAll(filepath.Join(etc, "carlos"), 0o755)
+ if err := recordGenerationsFloor(etc); err != nil {
+ t.Fatal(err)
+ }
+ assertMarked(t, etc)
+ // Again: left as it is.
+ if err := recordGenerationsFloor(etc); err != nil {
+ t.Fatal(err)
+ }
+ // A symlink at the path is left alone and counts.
+ other := t.TempDir()
+ os.MkdirAll(filepath.Join(other, "carlos"), 0o755)
+ target := filepath.Join(other, "elsewhere")
+ if err := os.Symlink(target, generationsFloorMarkerPath(other)); err != nil {
+ t.Fatal(err)
+ }
+ if err := recordGenerationsFloor(other); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(target); !os.IsNotExist(err) {
+ t.Fatalf("the symlink was followed: %v", err)
+ }
+ if m, err := generationsFloorMarked(generationsFloorMarkerPath(other)); !m || err != nil {
+ t.Fatalf("marked = %v, %v", m, err)
+ }
+}
+
+// TestNoteGenerationsSwitch: the adopt pass records the sticky record when
+// the switch is on, nothing otherwise, and logs a failure.
+func TestNoteGenerationsSwitch(t *testing.T) {
+ var logged []string
+ logf := func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) }
+ etc := t.TempDir()
+ os.MkdirAll(filepath.Join(etc, "carlos"), 0o755)
+ noteGenerationsSwitch(etc, envOf(map[string]string{"CARLOS_HA_GENERATIONS": "0"}), logf)
+ if m, _ := generationsFloorMarked(generationsFloorMarkerPath(etc)); m || len(logged) != 0 {
+ t.Fatalf("switch off: marked %v, logged %q", m, logged)
+ }
+ noteGenerationsSwitch(etc, envOf(map[string]string{"CARLOS_HA_GENERATIONS": "on"}), logf)
+ assertMarked(t, etc)
+ missing := filepath.Join(t.TempDir(), "absent")
+ noteGenerationsSwitch(missing, envOf(map[string]string{"CARLOS_HA_GENERATIONS": "fast"}), logf)
+ if len(logged) != 1 || !strings.HasPrefix(logged[0], "ALERT: storage generations floor: cannot record "+generationsFloorMarkerPath(missing)+": ") {
+ t.Fatalf("logged %q", logged)
+ }
+}
+
+// TestStageRefusesBinaryWithoutGenerationsFeature: with the switch on,
+// apply (and so a fixed box's rollback to an older release, which arrives
+// as an apply) refuses a candidate that does not report
+// replica-generations-1, including one from the PROXY protocol era that
+// reports only ingress-proxy-v2, and keeps the running binary. Seeing the
+// switch, the guard records the sticky record.
+func TestStageRefusesBinaryWithoutGenerationsFeature(t *testing.T) {
+ for name, answer := range map[string]func(string) (string, bool){
+ "no features list": noFeatures,
+ "PROXY protocol only": func(string) (string, bool) {
+ return `{"version":"v2","features":["ingress-proxy-v2"]}`, true
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f, req := applyHappy(t)
+ armGenerations(t, f.a.etcDir, "on")
+ answerVersionJSON(f, answer)
+ before, _ := os.ReadFile(systemBinaryPath(f.a.optDir))
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ assertStageRefused(t, f, req, before)
+ if !f.called("run carlos version --json") {
+ t.Fatalf("the candidate was not asked: %v", f.calls)
+ }
+ assertMarked(t, f.a.etcDir)
+ })
+ }
+}
+
+// TestStageAllowsBinaryWithGenerationsFeature: a candidate at the floor
+// installs on a box with the switch on.
+func TestStageAllowsBinaryWithGenerationsFeature(t *testing.T) {
+ f, req := applyHappy(t)
+ armGenerations(t, f.a.etcDir, "fast")
+ staged := filepath.Join(f.a.stagingDir(), "carlos")
+ answerVersionJSON(f, func(name string) (string, bool) { return generationsFeatureLine, name == staged })
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || !r.matches("stable", "v2", req.PromotedAt) {
+ t.Fatalf("result = %+v", r)
+ }
+}
+
+// TestStageWithBothGuardsNamesTheMissingFeature: a box armed for PROXY
+// protocol and generations needs both, and the refusal names the one the
+// candidate lacks.
+func TestStageWithBothGuardsNamesTheMissingFeature(t *testing.T) {
+ for _, tc := range []struct {
+ features string
+ want func(string) error
+ }{
+ {`["replica-generations-1"]`, func(b string) error { return &proxyFeatureRefusal{binary: b} }},
+ {`["ingress-proxy-v2"]`, func(b string) error { return &generationsFeatureRefusal{binary: b} }},
+ } {
+ t.Run(tc.features, func(t *testing.T) {
+ f, _ := applyHappy(t)
+ writeHostEnvLines(t, f.a.etcDir, "CARLOS_INGRESS_PROXY_SOURCES=10.0.1.5", "CARLOS_HA_GENERATIONS=on")
+ answerVersionJSON(f, func(string) (string, bool) { return `{"features":` + tc.features + `}`, true })
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ want := tc.want(filepath.Join(f.a.stagingDir(), "carlos")).Error()
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeRefused || !strings.Contains(r.Reason, want) {
+ t.Fatalf("result = %+v, want %q", r, want)
+ }
+ })
+ }
+}
+
+// TestGenerationsFloorIsSticky: once a root pass has seen the switch on,
+// removing it from host.env does not lift the floor; the same candidate
+// is still refused.
+func TestGenerationsFloorIsSticky(t *testing.T) {
+ t.Run("recorded by the adopt pass", func(t *testing.T) {
+ f, req := applyHappy(t)
+ armGenerations(t, f.a.etcDir, "on")
+ noteGenerationsSwitch(f.a.etcDir, envOf(map[string]string{"CARLOS_HA_GENERATIONS": "on"}), t.Logf)
+ writeHostEnvLines(t, f.a.etcDir) // the switch removed
+ answerVersionJSON(f, noFeatures)
+ before, _ := os.ReadFile(systemBinaryPath(f.a.optDir))
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ assertStageRefused(t, f, req, before)
+ })
+ t.Run("recorded by the guard", func(t *testing.T) {
+ f, _ := applyHappy(t)
+ armGenerations(t, f.a.etcDir, "on")
+ if !f.a.generationsArmedHere() {
+ t.Fatal("not armed with the switch on")
+ }
+ armGenerations(t, f.a.etcDir, "0") // the switch turned off
+ if !f.a.generationsArmedHere() {
+ t.Fatal("the switch's removal lifted the floor")
+ }
+ answerVersionJSON(f, noFeatures)
+ if err := f.a.requireFeatures(context.Background(), systemBinaryPath(f.a.optDir)); !errors.As(err, new(*generationsFeatureRefusal)) {
+ t.Fatalf("requireFeatures = %v", err)
+ }
+ })
+}
+
+// TestGenerationsFloorNeverOnUnaffected: a box that never had the switch
+// on (unset, 0 or off) installs as it always has: nothing is asked for
+// --json and nothing is recorded.
+func TestGenerationsFloorNeverOnUnaffected(t *testing.T) {
+ for _, lines := range [][]string{nil, {"CARLOS_HA_GENERATIONS=0"}, {"CARLOS_HA_GENERATIONS=off"}, {"CARLOS_HA_GENERATIONS="}} {
+ t.Run(strings.Join(lines, ","), func(t *testing.T) {
+ f, req := applyHappy(t)
+ writeHostEnvLines(t, f.a.etcDir, lines...)
+ answerVersionJSON(f, noFeatures)
+ if err := f.a.Run(context.Background(), false); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || !r.matches("stable", "v2", req.PromotedAt) {
+ t.Fatalf("result = %+v", r)
+ }
+ if strings.Contains(strings.Join(f.calls, "\n"), "--json") {
+ t.Fatalf("an unarmed box asked for features: %v", f.calls)
+ }
+ if m, _ := generationsFloorMarked(generationsFloorMarkerPath(f.a.etcDir)); m {
+ t.Fatal("a sticky record was written")
+ }
+ })
+ }
+}
+
+// recoveryOnGenerationsBox is recoveryOnArmedBox with the generations
+// switch on instead of PROXY protocol: v2 on disk, carlos.prev v1, the
+// journal open.
+func recoveryOnGenerationsBox(t *testing.T) *applyFixture {
+ t.Helper()
+ f, _ := applyHappy(t)
+ os.WriteFile(systemPrevPath(f.a.optDir), []byte("#!/bin/sh\necho carlos v1\n"), 0o755)
+ os.WriteFile(systemBinaryPath(f.a.optDir), []byte("#!/bin/sh\necho carlos v2\n"), 0o755)
+ writeJSONDurable(filepath.Join(systemRootDir(f.a.optDir), "journal.json"),
+ systemJournal{Phase: systemPhaseInstalled, Target: "v2", PrevBuild: "v1", StartedAt: f.now}, 0o600)
+ f.edgeStartedThisBoot = false
+ armGenerations(t, f.a.etcDir, "on")
+ return f
+}
+
+// TestRecoveryRefusesPrevWithoutGenerationsFeature: `apply --recover` by
+// the current binary refuses to restore a carlos.prev without
+// replica-generations-1, exits non-zero, and keeps the current binary and
+// the journal; with the feature it restores as before.
+func TestRecoveryRefusesPrevWithoutGenerationsFeature(t *testing.T) {
+ f := recoveryOnGenerationsBox(t)
+ answerVersionJSON(f, func(string) (string, bool) { return `{"features":["ingress-proxy-v2"]}`, true })
+ journal, _ := os.ReadFile(filepath.Join(systemRootDir(f.a.optDir), "journal.json"))
+ err := f.a.Run(context.Background(), true)
+ var refusal *generationsFeatureRefusal
+ if !errors.As(err, &refusal) || refusal.binary != systemPrevPath(f.a.optDir) {
+ t.Fatalf("recovery: %v", err)
+ }
+ if bin, _ := os.ReadFile(systemBinaryPath(f.a.optDir)); !strings.Contains(string(bin), "carlos v2") {
+ t.Fatal("the current binary was replaced")
+ }
+ if after, _ := os.ReadFile(filepath.Join(systemRootDir(f.a.optDir), "journal.json")); string(after) != string(journal) {
+ t.Fatal("the journal changed")
+ }
+ if f.called("systemctl") {
+ t.Fatalf("the refusal touched systemd: %v", f.calls)
+ }
+
+ f = recoveryOnGenerationsBox(t)
+ answerVersionJSON(f, func(string) (string, bool) { return generationsFeatureLine, true })
+ if err := f.a.Run(context.Background(), true); err != nil {
+ t.Fatal(err)
+ }
+ if bin, _ := os.ReadFile(systemBinaryPath(f.a.optDir)); !strings.Contains(string(bin), "carlos v1") {
+ t.Fatal("carlos.prev not restored")
+ }
+}
+
+// TestRestoreRefusesACopyUnderGenerations: the restore copy carries
+// carlos.prev's verdict under the generations guard too; a copy that is
+// not that carlos.prev byte for byte is refused before its rename.
+func TestRestoreRefusesACopyUnderGenerations(t *testing.T) {
+ f := recoveryOnGenerationsBox(t)
+ answerVersionJSON(f, func(string) (string, bool) { return generationsFeatureLine, 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 *generationsFeatureRefusal
+ if !errors.As(err, &refusal) || refusal.binary != restore {
+ t.Fatalf("recovery: %v", err)
+ }
+ if bin, _ := os.ReadFile(systemBinaryPath(f.a.optDir)); !strings.Contains(string(bin), "carlos v2") {
+ t.Fatal("the copy was renamed in")
+ }
+}
+
+func TestGenerationsAllowsPrevVerb(t *testing.T) {
+ prev := "/opt/carlos/carlos.prev"
+ for _, tc := range []struct {
+ name string
+ args []string
+ armed bool
+ out string
+ err error
+ want int
+ ran bool
+ }{
+ {"not armed", []string{prev}, false, "carlos v0.38.0\n", nil, 0, false},
+ {"armed, feature", []string{prev}, true, generationsFeatureLine, nil, 0, true},
+ {"armed, PROXY protocol only", []string{prev}, true, proxyFeatureLine, nil, 1, true},
+ {"armed, no features", []string{prev}, true, "carlos v0.38.0\n", nil, 1, true},
+ {"armed, run fails", []string{prev}, true, "", errors.New("exit status 2"), 1, true},
+ {"no path", nil, true, generationsFeatureLine, nil, 2, false},
+ {"another path", []string{"/tmp/carlos"}, false, generationsFeatureLine, nil, 2, false},
+ {"two paths", []string{prev, prev}, false, generationsFeatureLine, nil, 2, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ran := false
+ run := func(_ context.Context, binary string, args ...string) ([]byte, error) {
+ ran = true
+ if binary != prev || strings.Join(args, " ") != "version --json" {
+ t.Fatalf("ran %s %v", binary, args)
+ }
+ return []byte(tc.out), tc.err
+ }
+ var logged []string
+ logf := func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) }
+ sandbox := func(path string) error { return nil }
+ if got := generationsAllowsPrev(context.Background(), tc.args, prev, func() bool { return tc.armed }, sandbox, run, logf); got != tc.want {
+ t.Fatalf("exit %d, want %d", got, tc.want)
+ }
+ if ran != tc.ran {
+ t.Fatalf("ran %v, want %v", ran, tc.ran)
+ }
+ if tc.want == 1 && (len(logged) != 1 || logged[0] != (&generationsFeatureRefusal{binary: prev}).Error()) {
+ t.Fatalf("logged %q", logged)
+ }
+ if tc.want == 2 && (len(logged) != 1 || logged[0] != "usage: carlos system generations-allows-prev "+prev) {
+ t.Fatalf("logged %q", logged)
+ }
+ })
+ }
+}
+
+// generationsRecoveryGate is the recovery unit's generations floor gate.
+const generationsRecoveryGate = " && /opt/carlos/carlos system generations-allows-prev /opt/carlos/carlos.prev"
+
+// TestRecoverUnitGatesPrevOnGenerations: the recovery unit runs carlos.prev
+// only when the current binary's generations-allows-prev passes it,
+// straight after the PROXY protocol gate, and runs the current binary's
+// recovery when it fails.
+func TestRecoverUnitGatesPrevOnGenerations(t *testing.T) {
+ command := recoverUnitCommand(t)
+ proxy := strings.Index(command, proxyRecoveryGate)
+ gate := strings.Index(command, generationsRecoveryGate)
+ then := strings.Index(command, "; then exec /opt/carlos/carlos.prev system apply --recover; fi;")
+ if strings.Count(command, generationsRecoveryGate) != 1 || proxy < 0 || gate != proxy+len(proxyRecoveryGate) || gate+len(generationsRecoveryGate) != then || strings.ContainsAny(command, "%$") {
+ t.Fatalf("the recovery unit does not gate carlos.prev on generations-allows-prev: %s", command)
+ }
+ for _, tc := range []struct {
+ gate string // the stub's answer to generations-allows-prev
+ want string
+ }{
+ {"exit 0", "prev"},
+ {"exit 1", "current"},
+ {"exit 2", "current"},
+ } {
+ t.Run(tc.gate, func(t *testing.T) {
+ root := t.TempDir()
+ current, prev := filepath.Join(root, "current"), filepath.Join(root, "prev")
+ receipt := filepath.Join(root, "receipt")
+ body := "#!/bin/sh\ncase \"$1 $2\" in\n'system generations-allows-prev') " + tc.gate + ";;\n'system apply') echo current > '" + receipt + "';;\n*) exit 0;;\nesac\n"
+ os.WriteFile(current, []byte(body), 0o755)
+ os.WriteFile(prev, []byte("#!/bin/sh\ncase \"$1 $2\" in\n'system apply') echo prev > '"+receipt+"';;\n*) exit 0;;\nesac\n"), 0o755)
+ cmd := strings.ReplaceAll(command, "/opt/carlos/carlos.prev", prev)
+ cmd = strings.ReplaceAll(cmd, "/opt/carlos/carlos", current)
+ for _, p := range []string{"/opt/carlos/system/guard/carlos", "/var/lib/carlos-claims/authority/exec/census.json", "/opt/carlos/system/guard/moves", "/data/.moves/floor.min-release", "/data/.moves/seeds-floor.min-release"} {
+ cmd = strings.ReplaceAll(cmd, p, filepath.Join(root, "absent", filepath.Base(p)))
+ }
+ journal := filepath.Join(root, "journal")
+ os.WriteFile(journal, nil, 0o600)
+ cmd = strings.ReplaceAll(cmd, "/opt/carlos/system/router/journal.json", journal)
+ if out, err := exec.Command("/bin/sh", "-c", cmd).CombinedOutput(); err != nil {
+ t.Fatalf("recovery: %v %s", err, out)
+ }
+ if b, _ := os.ReadFile(receipt); string(b) != tc.want+"\n" {
+ t.Fatalf("recovery ran %q, want %s", b, tc.want)
+ }
+ })
+ }
+}
+
+// TestGuardExecRecoveryPassesOverPrevBelowGenerations: guard-exec's choice
+// of carlos.prev carries the generations guard: an armed box runs the
+// current binary's recovery when carlos.prev lacks the feature.
+func TestGuardExecRecoveryPassesOverPrevBelowGenerations(t *testing.T) {
+ for _, tc := range []struct {
+ out, want string
+ }{
+ {proxyFeatureLine, "current"},
+ {generationsFeatureLine, "prev"},
+ } {
+ opt := t.TempDir()
+ os.MkdirAll(systemRootDir(opt), 0o755)
+ writeJSONDurable(filepath.Join(systemRootDir(opt), "journal.json"), systemJournal{Phase: systemPhaseInstalled, Target: "v2", PrevBuild: "v1"}, 0o600)
+ var ran string
+ b := guardExecRouterBox{
+ opt: opt,
+ rootMoves: func() (rootFloorIdentity, bool, error) { return rootFloorIdentity{}, false, nil },
+ journal: func(opt string) (bool, error) {
+ _, err := os.Stat(filepath.Join(systemRootDir(opt), "journal.json"))
+ return err == nil, nil
+ },
+ withFloor: func(context.Context, string, rootFloorIdentity, bool, func(context.Context, string) error, func(string) error) error {
+ t.Fatal("no moves floor here")
+ return nil
+ },
+ prevAllowed: func(ctx context.Context, prev string) error {
+ return generationsPrevAllowed(ctx, prev, func() bool { return true }, func(context.Context, string, ...string) ([]byte, error) {
+ return []byte(tc.out), nil
+ })
+ },
+ exec: func(path string, args []string) error { ran = path; return nil },
+ logf: t.Logf,
+ }
+ if err := guardExecRouter(context.Background(), "recover", b); err != nil {
+ t.Fatal(err)
+ }
+ want := systemBinaryPath(opt)
+ if tc.want == "prev" {
+ want = systemPrevPath(opt)
+ }
+ if ran != want {
+ t.Fatalf("%s: ran %s, want %s", tc.want, ran, want)
+ }
+ }
+}
diff --git a/internal/host/guardexec.go b/internal/host/guardexec.go
index c15872c91..fc9fb8643 100644
--- a/internal/host/guardexec.go
+++ b/internal/host/guardexec.go
@@ -76,12 +76,16 @@ func RunSystemGuardExec(args []string) {
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) {
+ run := 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
- })
+ }
+ if err := proxyPrevAllowed(ctx, prev, productionProxyArmed, run); err != nil {
+ return err
+ }
+ return generationsPrevAllowed(ctx, prev, productionGenerationsArmed, run)
},
exec: func(path string, args []string) error { return d.Exec(path, platform, args, os.Environ(), "router") },
logf: log.Printf,
@@ -116,8 +120,9 @@ type guardExecRouterBox struct {
// 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 is the activation guards on carlos.prev: PROXY
+ // protocol's (proxyPrevAllowed), then the storage generations floor's
+ // (generationsPrevAllowed): nil, or the first refusal.
prevAllowed func(ctx context.Context, prev string) error
exec func(path string, args []string) error
logf func(string, ...any)
diff --git a/internal/host/proxyfeature.go b/internal/host/proxyfeature.go
index c4976bf64..b83d40df7 100644
--- a/internal/host/proxyfeature.go
+++ b/internal/host/proxyfeature.go
@@ -43,17 +43,25 @@ func (e *proxyFeatureRefusal) Error() string {
// (versionCommand's DefaultOn), which is not JSON, so it has no feature; a
// run that fails has none either.
func binaryHasFeature(ctx context.Context, run func(ctx context.Context, binary string, args ...string) ([]byte, error), binary, feature string) bool {
+ features, ok := binaryFeatures(ctx, run, binary)
+ return ok && slices.Contains(features, feature)
+}
+
+// binaryFeatures is binaryHasFeature's one run: the features binary
+// reports, and false when the run fails or its output is not one JSON
+// object.
+func binaryFeatures(ctx context.Context, run func(ctx context.Context, binary string, args ...string) ([]byte, error), binary string) ([]string, bool) {
out, err := run(ctx, binary, "version", "--json")
if err != nil {
- return false
+ return nil, false
}
var v struct {
Features []string `json:"features"`
}
if err := json.Unmarshal(bytes.TrimSpace(out), &v); err != nil {
- return false
+ return nil, false
}
- return slices.Contains(v.Features, feature)
+ return v.Features, true
}
// proxyKeySet is the guard's own reading of CARLOS_INGRESS_PROXY_SOURCES:
@@ -121,10 +129,34 @@ func (a *systemApplier) proxyArmedHere() bool {
return proxyGuardArmed(a.proxyEnv, read)
}
-// requireFeatures is the activation guard for binary: nil on a box not
-// armed for PROXY protocol, without running anything; otherwise nil only
-// when binary reports ingress-proxy-v2, asked the way the box runs every
-// binary it activates (guardRun, bounded by systemVersionWait). The
+// requiredFeatures is what this box asks of every binary it activates, in
+// order: ingress-proxy-v2 when it is armed for PROXY protocol, then
+// replica-generations-1 when its storage generations floor is armed
+// (genfloor.go). Empty, the guards do not apply.
+func (a *systemApplier) requiredFeatures() []string {
+ var required []string
+ if a.proxyArmedHere() {
+ required = append(required, ingressProxyFeature)
+ }
+ if a.generationsArmedHere() {
+ required = append(required, generationsFeature)
+ }
+ return required
+}
+
+// featureRefusal is the refusal of binary for lacking feature.
+func featureRefusal(feature, binary string) error {
+ if feature == generationsFeature {
+ return &generationsFeatureRefusal{binary: binary}
+ }
+ return &proxyFeatureRefusal{binary: binary}
+}
+
+// requireFeatures is the activation guard for binary: nil on a box where
+// no guard is armed (requiredFeatures), without running anything;
+// otherwise nil only when binary reports every required feature, asked
+// the way the box runs every binary it activates (guardRun, bounded by
+// systemVersionWait), and the refusal for the first it lacks. 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)
@@ -132,16 +164,17 @@ func (a *systemApplier) requireFeatures(ctx context.Context, binary string) erro
}
// featureDigest is requireFeatures that also returns the "sha256:<hex>" of
-// the bytes it found the feature in ("" when the box is not armed). The
+// the bytes it found the features 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() {
+ required := a.requiredFeatures()
+ if len(required) == 0 {
return "", nil
}
if err := a.sandboxAllows(binary); err != nil {
return "", err
}
- refused := &proxyFeatureRefusal{binary: binary}
+ refused := featureRefusal(required[0], binary)
before, err := fileSHA256(binary)
if err != nil {
return "", refused
@@ -150,8 +183,11 @@ func (a *systemApplier) featureDigest(ctx context.Context, binary string) (strin
out, err := a.guardRun(ctx, systemVersionWait, name, args...)
return []byte(out), err
}
- if !binaryHasFeature(ctx, run, binary, ingressProxyFeature) {
- return "", refused
+ features, ok := binaryFeatures(ctx, run, binary)
+ for _, feature := range required {
+ if !ok || !slices.Contains(features, feature) {
+ return "", featureRefusal(feature, binary)
+ }
}
if after, err := fileSHA256(binary); err != nil || after != before {
return "", refused
@@ -172,17 +208,18 @@ func (a *systemApplier) requirePrevFeatures(ctx context.Context) error {
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
+// restoreCopyAllowed is the guards' last word on the restore copy, just
+// before its rename: on a box with either guard armed 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() {
+ required := a.requiredFeatures()
+ if len(required) == 0 {
return nil
}
- refused := &proxyFeatureRefusal{binary: restore}
+ refused := featureRefusal(required[0], restore)
if a.proxyPrevDigest == "" {
return refused
}
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index cf920974b..8974d711f 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -59,6 +59,10 @@ var systemUnitFiles = []string{"carlos-runsc.service", instancectl.UnitPrefixGVi
// failure to report, and probe asks the two QUESTIONS, where non-zero is
// half the answer (see the block below).
func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...string) (string, error), logf func(string, ...any)) {
+ // The storage generations floor is sticky (genfloor.go): an adopt pass
+ // that runs with the switch on (its unit loads host.env) records it,
+ // so the activation guards stay armed once the switch is removed.
+ noteGenerationsSwitch(etcDir, os.Getenv, logf)
a := &systemApplier{etcDir: etcDir, optDir: filepath.Dir(filepath.Dir(filepath.Dir(lockPath))), ops: productionSysOps()}
ensureSystemUnitsWithGuard(etcDir, lockPath, systemctl, probe, logf, a)
}
diff --git a/internal/host/units/carlos-system-recover.service b/internal/host/units/carlos-system-recover.service
index 927a775c2..4df8e5b6e 100644
--- a/internal/host/units/carlos-system-recover.service
+++ b/internal/host/units/carlos-system-recover.service
@@ -30,12 +30,18 @@
# empty, carlos.prev runs only when /opt/carlos/carlos.prev.seeds-allowed
# names that same floor, byte for byte.
#
-# The PROXY protocol gate (edge PPv2 spec §7.3) comes last: on a box whose
+# The PROXY protocol gate (edge PPv2 spec §7.3) comes next: on a box whose
# host.env sets CARLOS_INGRESS_PROXY_SOURCES, carlos.prev runs only when
# the current binary's carlos system proxy-allows-prev finds that it
# reports the ingress-proxy-v2 feature. Otherwise the current binary runs,
# and its own recovery refuses to restore that carlos.prev: the journal
# and the current binary stay, and the unit fails with the reason.
+#
+# The storage generations floor gate comes after it, the same way: on a
+# box whose host.env sets CARLOS_HA_GENERATIONS (anything but empty, 0 or
+# off), or that has ever had it set (/etc/carlos/ha-generations-floor),
+# carlos.prev runs only when the current binary's carlos system
+# generations-allows-prev finds that it reports replica-generations-1.
[Unit]
Description=carlos platform self-update recovery
Before=carlos-edge.service
@@ -48,7 +54,7 @@ Type=oneshot
# runs first.
TimeoutStartSec=13min
EnvironmentFile=-/etc/carlos/host.env
-ExecStart=/bin/sh -c 'if [ -x /opt/carlos/system/guard/carlos ] && { [ -e /var/lib/carlos-claims/authority/exec/census.json ] || [ -L /var/lib/carlos-claims/authority/exec/census.json ] || [ -e /opt/carlos/system/guard/moves ] || [ -L /opt/carlos/system/guard/moves ]; }; then exec /opt/carlos/system/guard/carlos system guard-exec recover; fi; if [ -f /opt/carlos/system/router/journal.json ] && [ -x /opt/carlos/carlos.prev ] && [ ! -L /data/.moves/floor.min-release ] && { [ ! -e /data/.moves/floor.min-release ] || [ -f /data/.moves/floor.min-release ]; } && { ! [ -s /data/.moves/floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/floor.min-release /opt/carlos/carlos.prev.allowed; } && [ ! -L /data/.moves/seeds-floor.min-release ] && { [ ! -e /data/.moves/seeds-floor.min-release ] || [ -f /data/.moves/seeds-floor.min-release ]; } && { ! [ -s /data/.moves/seeds-floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/seeds-floor.min-release /opt/carlos/carlos.prev.seeds-allowed; } && /opt/carlos/carlos system exec-sandbox-allows-prev /opt/carlos/carlos.prev && /opt/carlos/carlos system proxy-allows-prev /opt/carlos/carlos.prev; then exec /opt/carlos/carlos.prev system apply --recover; fi; exec /opt/carlos/carlos system apply --recover'
+ExecStart=/bin/sh -c 'if [ -x /opt/carlos/system/guard/carlos ] && { [ -e /var/lib/carlos-claims/authority/exec/census.json ] || [ -L /var/lib/carlos-claims/authority/exec/census.json ] || [ -e /opt/carlos/system/guard/moves ] || [ -L /opt/carlos/system/guard/moves ]; }; then exec /opt/carlos/system/guard/carlos system guard-exec recover; fi; if [ -f /opt/carlos/system/router/journal.json ] && [ -x /opt/carlos/carlos.prev ] && [ ! -L /data/.moves/floor.min-release ] && { [ ! -e /data/.moves/floor.min-release ] || [ -f /data/.moves/floor.min-release ]; } && { ! [ -s /data/.moves/floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/floor.min-release /opt/carlos/carlos.prev.allowed; } && [ ! -L /data/.moves/seeds-floor.min-release ] && { [ ! -e /data/.moves/seeds-floor.min-release ] || [ -f /data/.moves/seeds-floor.min-release ]; } && { ! [ -s /data/.moves/seeds-floor.min-release ] || /opt/carlos/carlos.prev system floor-allows-prev /data/.moves/seeds-floor.min-release /opt/carlos/carlos.prev.seeds-allowed; } && /opt/carlos/carlos system exec-sandbox-allows-prev /opt/carlos/carlos.prev && /opt/carlos/carlos system proxy-allows-prev /opt/carlos/carlos.prev && /opt/carlos/carlos system generations-allows-prev /opt/carlos/carlos.prev; then exec /opt/carlos/carlos.prev system apply --recover; fi; exec /opt/carlos/carlos system apply --recover'
ProtectHome=yes
PrivateTmp=yes
diff --git a/internal/version/features.go b/internal/version/features.go
index 52c8ac559..0e2576a40 100644
--- a/internal/version/features.go
+++ b/internal/version/features.go
@@ -5,7 +5,15 @@ package version
// for PROXY protocol refuses to activate a build that does not report it.
const FeatureIngressProxyV2 = "ingress-proxy-v2"
+// FeatureReplicaGenerations1 is the feature a build reports once it reads
+// and writes region HA storage generations (the same name as the edges
+// file capability). A box whose storage-generations switch is or has ever
+// been on refuses to activate a build that does not report it: an older
+// build would take a generations lock as an ordinary HA lock and serve
+// stale data.
+const FeatureReplicaGenerations1 = "replica-generations-1"
+
// Features is what `carlos version --json` reports this build can do, for a
// box deciding whether it may activate the build. A feature, once listed,
// stays listed in every later build.
-var Features = []string{FeatureIngressProxyV2}
+var Features = []string{FeatureIngressProxyV2, FeatureReplicaGenerations1}
diff --git a/parity/cli.tsv b/parity/cli.tsv
index b86c1f4b6..3bd2eec04 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -272,6 +272,7 @@ system edge trust-status box-local - - - - -
system exec-sandbox-allows-prev box-local - - - - -
system files box-local - - - - -
system floor-allows-prev box-local - - - - -
+system generations-allows-prev box-local - - - - -
system geoip off operator - - - - -
system geoip publish operator - - - - -
system geoip status operator - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index a8f598a33..a05f8ff0b 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -235,7 +235,7 @@ release-keygen box box-local release-keygen Mints signing keys; the private k
proof box box-local proof keygen ; proof get ; proof put ; proof history Dev proofs a box needs to adopt.
relay-box box box-local relay serve ; relay keygen Runs the relay, or mints a region master key.
mailer-serve box box-local mailer serve Runs the box-local mailer; the unit's entry point.
-system-box box box-local system apply ; system files ; system guard-arm ; system guard-exec ; system floor-allows-prev ; system exec-sandbox-allows-prev ; system runsc-ensure ; system install-channel ; system host-env ; system named-units ; system db-worker ; system journal-migrate ; system group-maintenance ; system edge trust-barrier ; system edge trust-resume ; system edge trust-status ; system proxy-allows-prev ; system box publish-record Root oneshots and units on a box.
+system-box box box-local system apply ; system files ; system guard-arm ; system guard-exec ; system floor-allows-prev ; system exec-sandbox-allows-prev ; system runsc-ensure ; system install-channel ; system host-env ; system named-units ; system db-worker ; system journal-migrate ; system group-maintenance ; system edge trust-barrier ; system edge trust-resume ; system edge trust-status ; system proxy-allows-prev ; system generations-allows-prev ; system box publish-record Root oneshots and units on a box.
status-dry-run box box-local status [--dry-run] A leak check against a fixture fleet, run locally.
devbox-serve box box-local devbox serve The devbox service under systemd.
diff --git a/system.go b/system.go
index 4702c331f..14c20924a 100644
--- a/system.go
+++ b/system.go
@@ -62,6 +62,9 @@ func systemCommand() *clireg.Node {
// The recovery unit's PROXY protocol gate on carlos.prev (edge
// PPv2 spec §7.3); root's, not for operators.
raw("proxy-allows-prev", box, host.RunSystemProxyAllowsPrev),
+ // The recovery unit's storage generations floor gate on
+ // carlos.prev; root's, not for operators.
+ raw("generations-allows-prev", box, host.RunSystemGenerationsAllowsPrev),
raw("group-maintenance", box, func(args []string) {
os.Exit(host.RunGroupMaintenance(args, os.Stdin, os.Stdout, os.Stderr))
}),
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl
index 494f7a9e1..061050f22 100644
--- a/testdata/clireg-golden.jsonl
+++ b/testdata/clireg-golden.jsonl
@@ -882,6 +882,8 @@
{"case":"system files | -h","argv":["system","files","-h"],"exit":1,"stdout":"","stderr":"Files seed failed: hostbox: unresolved lifecycle contract.\n"}
{"case":"system floor-allows-prev | --zz-unknown-flag","argv":["system","floor-allows-prev","--zz-unknown-flag"],"exit":1,"stdout":"","stderr":"moves protocol floor: carlos.prev may not run: floor-allows-prev takes two absolute paths: the floor file and the verdict file\n"}
{"case":"system floor-allows-prev | -h","argv":["system","floor-allows-prev","-h"],"exit":1,"stdout":"","stderr":"moves protocol floor: carlos.prev may not run: floor-allows-prev takes two absolute paths: the floor file and the verdict file\n"}
+{"case":"system generations-allows-prev | --zz-unknown-flag","argv":["system","generations-allows-prev","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"usage: carlos system generations-allows-prev /opt/carlos/carlos.prev\n"}
+{"case":"system generations-allows-prev | -h","argv":["system","generations-allows-prev","-h"],"exit":2,"stdout":"","stderr":"usage: carlos system generations-allows-prev /opt/carlos/carlos.prev\n"}
{"case":"system geoip off | --zz-unknown-flag","argv":["system","geoip","off","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos system geoip off [flags]\nflags:\n --console <string> console origin (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n"}
{"case":"system geoip off | -h","argv":["system","geoip","off","-h"],"exit":0,"stdout":"","stderr":"usage: carlos system geoip off [flags]\nflags:\n --console <string> console origin (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n"}
{"case":"system geoip publish | --zz-unknown-flag","argv":["system","geoip","publish","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\n<file.mmdb>\nflags:\n --console <string> console origin (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --force publish even if the database has under half the current one's nodes\n"}