carlos / platform Public

ppv2: approved operator copy; prereq checks both slots under the guard

Applies the PPv2 operator text review (59 strings, approved by Paul
without edits). Three strings differed from the code: the edge's
no-route refusal now names CARLOS_INGRESS_PROXY_SOURCES, and the prereq
usage paragraph and guard refusal follow the new check.

ppv2-step.py prereq: on a box with the guard installed, check that both
/opt/carlos/carlos and /opt/carlos/carlos.prev report ingress-proxy-v2,
instead of the guard binary itself. An old guard's recovery can only
pick one of those two, and carlos.prev only ever becomes the outgoing
current binary, so once both are vN or later the guard binary stops
mattering. Refusals are per box and slot; an absent guard still passes.
Each slot answers on one line with its output in base64, so nothing a
binary prints can answer for itself or the other slot (Astra P1, fixed).
Runbook prerequisite 6 and the prereq paragraph say the same.

Census: internal/host envelope re-pinned for the refusal text; Astra
approved (#280).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from ppv2-operator-copy into main.
claude agent, operated by paul@keymail.dev 26272c99d8b7b87b0c032c2343e509701c0d94fc parent ded2dab
9 files changed, +183 −39
  • docs/region-ha-runbook.md +2 −2
  • docs/superpowers/notes/census-proposal-ppv2-operator-copy.md +11 −0
  • docs/superpowers/reviews/ASTRA-FINDINGS-ppv2-guard-slots.md +15 −0
  • internal/host/edgetrust.go +2 −2
  • internal/host/edgetrust_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv +3 −0
  • scripts/ppv2-step.py +65 −25
  • scripts/ppv2_step_test.py +83 −9

CI passed — run details

diff --git a/docs/region-ha-runbook.md b/docs/region-ha-runbook.md
index 739ad3973..ed1107d1e 100644
--- a/docs/region-ha-runbook.md
+++ b/docs/region-ha-runbook.md
@@ -366,9 +366,9 @@ In this order:
3. `CARLOS_INGRESS_PROXY_SOURCES` equals the module's output, in the region's host-env parameters (then a group roll, because members write host.env only at launch) and in each fixed box's host.env (drained restart). Every target's journal shows `edge: proxy protocol: armed on :80 and :443, trusting ...` with exactly the module's addresses.
4. The group module is at vN.
5. `CARLOS_HOST_METRICS=cloudwatch` on every target, the module's `proxy_trust_alarm` set, both alarms applied and in OK, and a notification seen arriving.
-6. On a box with the guard armed, the installed guard binary `/opt/carlos/system/guard/carlos` is vN or later. guard-arm copies it once, and application updates do not refresh it. An older one runs `guard-exec recover` with no PPv2 check, so with a journal open it could restore a predecessor below vN. A box without the guard has no such file.
+6. On a box with the guard armed, both `/opt/carlos/carlos` and `/opt/carlos/carlos.prev` report `ingress-proxy-v2` (`<binary> version --json`) before you publish the key. The guard binary `/opt/carlos/system/guard/carlos` is copied once by guard-arm and never refreshed by application updates, and an old one's recovery can fall back to `carlos.prev` without a PROXY protocol check. Once both slots are vN or later, anything it can fall back to carries the check. A box whose `carlos.prev` is older gets one more apply of a release at vN or later, which makes the outgoing vN binary its `carlos.prev`; then check again. A box without the guard has no guard binary and passes.
-`prereq` checks only the automated part: both target groups in S0, every target armed with the NLB's node addresses, the barrier down, the trust alarm OK, and item 6 on every target. For item 6 it runs the installed guard binary's `version --json` over SSM and refuses, naming the boxes, unless the binary is absent or reports `ingress-proxy-v2`. It writes `prereq.json`, including the NLB's public addresses, which the probes must target. Items 1, 2 and 4 and a delivered notification stay manual.
+`prereq` checks only the automated part: both target groups in S0, every target armed with the NLB's node addresses, the barrier down, the trust alarm OK, and item 6 on every target. For item 6 it checks over SSM whether the guard binary exists and, where it does, runs `version --json` on both slots, refusing and naming the box and the slot for each one that does not report `ingress-proxy-v2`. It writes `prereq.json`, including the NLB's public addresses, which the probes must target. Items 1, 2 and 4 and a delivered notification stay manual.
```
python3 scripts/ppv2-step.py prereq --nlb-arn <nlb> --tg-arn-80 <tg80> --tg-arn-443 <tg443> \
diff --git a/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md b/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md
new file mode 100644
index 000000000..9142a7aa1
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-ppv2-operator-copy.md
@@ -0,0 +1,11 @@
+# Census approval: ppv2-operator-copy
+
+Ruling `census-ruling-ppv2-operator-copy`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc` → `19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-ppv2-guard-slots.md b/docs/superpowers/reviews/ASTRA-FINDINGS-ppv2-guard-slots.md
new file mode 100644
index 000000000..9fd9caea4
--- /dev/null
+++ b/docs/superpowers/reviews/ASTRA-FINDINGS-ppv2-guard-slots.md
@@ -0,0 +1,15 @@
+1. **P1 fail-open — binary output can replace its actual exit status.** [scripts/ppv2-step.py:1560](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ppv2-operator-copy/scripts/ppv2-step.py:1560). If current prints the following and exits **3**, while previous reports the feature and exits 0, `guard_refusals` returns `[]`:
+
+ ```text
+ {"features":["ingress-proxy-v2"]}
+ ppv2-step: exit 0
+ ppv2-step: slot diagnostic
+ ```
+
+ The parser accepts the printed exit 0 for current and assigns its actual exit 3 to the ignored `diagnostic` slot. This breaks the requirement that each slot must successfully report the feature. Reproduced through `sh`.
+
+ **Fix:** reject unknown, duplicate, or out-of-order slot markers and require exactly both expected slots with complete exit records. Add this reproducer to `GuardCheckTests`.
+
+The targeted test could not run because the read-only sandbox prevents temporary-file creation. No files changed.
+
+**NOT READY.**
\ No newline at end of file
diff --git a/internal/host/edgetrust.go b/internal/host/edgetrust.go
index 580a1c9d0..b2b38612f 100644
--- a/internal/host/edgetrust.go
+++ b/internal/host/edgetrust.go
@@ -513,11 +513,11 @@ func (cmd edgeTrustCommand) run(ctx context.Context, args []string, out, stderr
case r.NoRoute:
// A socket without the routes: a box not armed (whose socket
// serves other verbs), or an agent older than the routes or not
- // restarted since the key was set. host.env tells which.
+ // restarted since CARLOS_INGRESS_PROXY_SOURCES was set. host.env tells which.
if getenv, err := cmd.hostEnv(); err == nil && !proxySourcesSet(getenv) {
return fail(2, errEdgeNotArmed.Error())
}
- return fail(1, "the agent does not serve the trust routes: an older release, or not restarted since the key was set")
+ return fail(1, "the agent does not serve the trust routes: an older release, or not restarted since CARLOS_INGRESS_PROXY_SOURCES was set")
case r.Error != "":
return fail(1, oneLine(r.Error))
}
diff --git a/internal/host/edgetrust_test.go b/internal/host/edgetrust_test.go
index a9fa77579..fe68f67ca 100644
--- a/internal/host/edgetrust_test.go
+++ b/internal/host/edgetrust_test.go
@@ -502,7 +502,7 @@ func TestEdgeTrustVerbAnswers(t *testing.T) {
{"no socket, host.env unarmed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "", 0, []string{"trust-status"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
{"no socket, host.env armed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "172.31.29.110", 0, []string{"trust-barrier"}, 1, "", "edge: the agent's drain socket is not answering\n"},
{"no route, host.env unarmed", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
- {"no route, host.env armed", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "172.31.29.110", 0, []string{"trust-status"}, 1, "", "edge: the agent does not serve the trust routes: an older release, or not restarted since the key was set\n"},
+ {"no route, host.env armed", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "172.31.29.110", 0, []string{"trust-status"}, 1, "", "edge: the agent does not serve the trust routes: an older release, or not restarted since CARLOS_INGRESS_PROXY_SOURCES was set\n"},
{"agent error", drainCallResult{V: 1, Error: "edge: write trust barrier: disk\nfull"}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: edge: write trust barrier: disk full\n"},
{"child failed", drainCallResult{}, errors.New("the drain call failed"), "", 0, []string{"trust-barrier"}, 1, "", "edge: the drain call failed\n"},
{"no answer", drainCallResult{V: 1}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"},
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ae119c290..fb8a47b1c 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -205,3 +205,4 @@ plan14-root-reads-member-backups-drill-nodb.tsv 07b748a749084fdaf61c5087a6edfca8
plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-member-backups-2b.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-instance-gomemlimit-991.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
+plan14-root-reads-ppv2-operator-copy.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
diff --git a/internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv b/internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv
new file mode 100644
index 000000000..bbabe7886
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-ppv2-operator-copy.tsv
@@ -0,0 +1,3 @@
+# Census overlay ppv2-operator-copy, written by census-propose (#369). census-ruling-ppv2-operator-copy, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-ppv2-operator-copy.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/host 63deead99b50db788dbbb63a21edfc23aa0d76b4dd11d6144fa6bb0ec41f3e91
diff --git a/scripts/ppv2-step.py b/scripts/ppv2-step.py
index 79e7c1478..5173f320e 100755
--- a/scripts/ppv2-step.py
+++ b/scripts/ppv2-step.py
@@ -15,11 +15,12 @@ them changes PPv2 while preservation is off, so no node can pass through S3.
prereq the automated part of the prerequisites (spec 6.1): both target
groups in S0, every target armed with the NLB's node addresses,
- barrier down, the trust alarm OK, and on every target the
- installed guard binary (/opt/carlos/system/guard/carlos) absent
- or reporting ingress-proxy-v2. Writes prereq.json with the NLB's
- public addresses. Versions, the bootstrap object hash and a
- delivered alarm notification are still checked by hand.
+ barrier down, the trust alarm OK, and on every box with the
+ guard installed, both /opt/carlos/carlos and /opt/carlos/carlos.prev
+ reporting ingress-proxy-v2. Writes prereq.json with the NLB's
+ public addresses. Versions, the bootstrap object hash, the group
+ module version and a delivered alarm notification are still
+ checked by hand.
apply makes one step on one target group through a targeted tofu plan,
writes <step>-applied.json, then goes straight into convergence:
it polls target health in BOTH target groups every 10 s, from
@@ -74,6 +75,7 @@ Exit codes: 0 done or passed, 1 refused or failed, 2 invalid arguments,
130 interrupted.
"""
import argparse
+import base64
from collections import namedtuple
from contextlib import contextmanager
from datetime import datetime, timezone
@@ -117,11 +119,23 @@ TRUST_STATUS = '/opt/carlos/carlos system edge trust-status'
LISTENERS = ('80', '443')
TRUST_KEYS = {'armed', 'barrier', 'edge_instance', 'counters', 'proxied_by_node', 'by_listener'}
# The guard binary guard-arm installs; app updates do not refresh it, and an
-# old one's `guard-exec recover` has no PPv2 gate (spec 6.1).
+# old one's `guard-exec recover` can run /opt/carlos/carlos.prev without a
+# PPv2 gate (spec 6.1). carlos.prev only ever stays as it is or becomes the
+# outgoing current binary, and the current binary cannot go below vN on an
+# armed box. So once both slots report the feature, whatever an old guard
+# picks carries the full activation guard, and the guard binary itself stops
+# mattering. On a box with the guard installed, prereq checks both slots.
GUARD_BINARY = '/opt/carlos/system/guard/carlos'
GUARD_ABSENT = 'ppv2-step: guard binary absent'
-GUARD_CHECK = (f'g={GUARD_BINARY}; if [ -e "$g" ] || [ -L "$g" ]; then "$g" version --json; '
+GUARD_SLOTS = ('/opt/carlos/carlos', '/opt/carlos/carlos.prev')
+GUARD_SLOT_MARK = 'ppv2-step: slot'
+# One line per slot: the mark, the slot, its exit code and its output in
+# base64, so nothing a binary prints can pose as another slot's answer.
+GUARD_CHECK = (f'g={GUARD_BINARY}; if [ -e "$g" ] || [ -L "$g" ]; then '
+ f'for b in {" ".join(GUARD_SLOTS)}; do out=$("$b" version --json 2>&1); rc=$?; '
+ f'echo "{GUARD_SLOT_MARK} $b $rc $(printf %s "$out" | base64 -w0)"; done; '
f"else echo '{GUARD_ABSENT}'; fi")
+GUARD_SLOT_RE = re.compile(r'^' + re.escape(GUARD_SLOT_MARK) + r' (\S+) (\d+)(?: ([A-Za-z0-9+/=]*))?$')
FEATURE = 'ingress-proxy-v2'
ARMED_LINE = 'edge: proxy protocol: armed on'
JOURNAL = "journalctl -u carlos-edge.service -o cat --no-pager | grep -F '%s' | tail -n 1" % ARMED_LINE
@@ -1511,14 +1525,12 @@ def cmd_prereq(args, cloud):
reasons.append(f'{iid}: no armed line in the carlos-edge journal')
elif sorted(match.group(1).split(',')) != private:
reasons.append(f"{iid} trusts {match.group(1)}, not the NLB's node addresses {','.join(private)}")
- # The installed guard binary: guard-arm copies it, app updates do not
- # refresh it, and an old one's guard-exec recover has no PPv2 gate.
+ # On a box with the guard installed, both slots an old guard binary
+ # can run must report the feature (GUARD_SLOTS).
guards = {}
for iid, (code, stdout, stderr) in cloud.ssm(targets, GUARD_CHECK).items():
- guards[iid] = one_line(stdout or stderr)[:300]
- reason = guard_refusal(iid, code, stdout, stderr)
- if reason:
- reasons.append(reason)
+ guards[iid] = one_line(stdout or stderr)[:600]
+ reasons.extend(guard_refusals(iid, code, stdout, stderr))
alarms = cloud.aws('cloudwatch', 'describe-alarms', '--alarm-names', args.alarm).get('MetricAlarms') or []
alarm = [a for a in alarms if a.get('AlarmName') == args.alarm]
if not alarm:
@@ -1543,20 +1555,48 @@ def cmd_prereq(args, cloud):
return 1
-def guard_refusal(iid, code, stdout, stderr):
- """Why the installed guard binary on iid would let a pre-vN predecessor
- run (it does not report ingress-proxy-v2), or None (absent, or it does)."""
- text = (stdout or '').strip()
- if code == 0 and text == GUARD_ABSENT:
+def guard_slots(stdout):
+ """GUARD_CHECK's answer on a box with the guard installed: each slot's
+ (output, exit code), or None unless it is exactly one well-formed line
+ per slot in GUARD_SLOTS, in order, and nothing else."""
+ lines = [line for line in (stdout or '').splitlines() if line.strip()]
+ if len(lines) != len(GUARD_SLOTS):
return None
- if code == 0:
- doc = first_json(text, 'features')
- if doc and isinstance(doc.get('features'), list) and FEATURE in doc['features']:
+ slots = {}
+ for line, slot in zip(lines, GUARD_SLOTS):
+ match = GUARD_SLOT_RE.match(line.strip())
+ if not match or match.group(1) != slot:
return None
- said = one_line(text or stderr)[:200] or f'exit {code}'
- return (f'{iid}: the installed guard binary {GUARD_BINARY} does not report {FEATURE} ({said}); '
- 'app updates do not refresh it, so its guard-exec recover has no PPv2 gate. Bring it to vN or later '
- 'on this box before the key is published')
+ try:
+ out = base64.b64decode(match.group(3) or '', validate=True).decode('utf-8', 'replace')
+ except ValueError:
+ return None
+ slots[slot] = (out.strip(), int(match.group(2)))
+ return slots
+
+
+def guard_refusals(iid, code, stdout, stderr):
+ """Why iid's guard could fall back to a binary below vN: one reason per
+ slot in GUARD_SLOTS that does not report ingress-proxy-v2; empty when the
+ guard is absent or both slots report it."""
+ text = (stdout or '').strip()
+ if code == 0 and text == GUARD_ABSENT:
+ return []
+ slots = (guard_slots(stdout) if code == 0 else None) or {}
+ reasons = []
+ for slot in GUARD_SLOTS:
+ out, rc = slots.get(slot, ('', None))
+ if rc == 0:
+ doc = first_json(out, 'features')
+ if doc and isinstance(doc.get('features'), list) and FEATURE in doc['features']:
+ continue
+ said = one_line(out)[:200] or (f'exit {rc}' if rc is not None else
+ one_line(text or stderr)[:200] or f'exit {code}')
+ reasons.append(f'{iid}: this box has the guard installed, and its {slot} does not report {FEATURE} '
+ f"({said}). The guard's recovery can fall back to that binary without a PROXY protocol "
+ 'check. Apply a release at vN or later once more so both /opt/carlos/carlos and '
+ '/opt/carlos/carlos.prev are vN or later, then run prereq again')
+ return reasons
def cmd_sync_tfvars(args, cloud):
diff --git a/scripts/ppv2_step_test.py b/scripts/ppv2_step_test.py
index aaee2062e..56c100761 100644
--- a/scripts/ppv2_step_test.py
+++ b/scripts/ppv2_step_test.py
@@ -8,6 +8,7 @@ Two harnesses, neither reaching AWS or tofu:
Run from the repo root: python3 -m unittest scripts/ppv2_step_test.py
"""
import argparse
+import base64
import contextlib
import copy
import fcntl
@@ -38,6 +39,8 @@ SOURCES = ['172.31.11.189', '172.31.29.110']
PUBLIC = ['54.77.110.223', '54.77.110.224']
INTERFACES = [{'private': SOURCES[0], 'public': PUBLIC[0]}, {'private': SOURCES[1], 'public': PUBLIC[1]}]
ALARM = 'carlos-dev-ie-proxy-trust'
+CURRENT, PREV = '/opt/carlos/carlos', '/opt/carlos/carlos.prev'
+NEW_BINARY = '{"version":"v0.35.0","features":["ingress-proxy-v2"]}'
APPLIED_AT = '2026-11-12T10:00:00.000000Z'
STATES = {'S0': ('true', 'false'), 'S1': ('true', 'true'), 'S2': ('false', 'true'), 'S3': ('false', 'false')}
EXPECT = {'A': 's1', 'B': 's2', 'R': 's1'}
@@ -47,7 +50,7 @@ TFVARS = (b'{ "ppv2_preserve_client_ip": {"80": true, "443": true},\n'
b' "ppv2_proxy_protocol_v2": {"80": false, "443": false} }\n')
FAKE = r'''
-import json, os, sys, time
+import base64, json, os, sys, time
from pathlib import Path
name = Path(sys.argv[0]).name
@@ -100,7 +103,14 @@ def invocation(iid, text):
if 'journalctl' in text:
return [iid, 'Success', 0, world['journal'][iid] + '\n']
if 'system/guard/carlos' in text:
- return [iid, 'Success', 0, world.get('guard', {}).get(iid, 'ppv2-step: guard binary absent') + '\n']
+ slots = world.get('guard', {}).get(iid)
+ if slots is None:
+ return [iid, 'Success', 0, 'ppv2-step: guard binary absent\n']
+ out = ''
+ for slot in ('/opt/carlos/carlos', '/opt/carlos/carlos.prev'):
+ said, rc = slots[slot]
+ out += f'ppv2-step: slot {slot} {rc} {base64.b64encode(said.encode()).decode()}\n'
+ return [iid, 'Success', 0, out]
return [iid, 'Failed', 1, MARK + 'unknown command']
if name == 'aws':
@@ -1827,9 +1837,9 @@ class PrereqTests(Harness):
and 'system/guard/carlos' in json.dumps(c['args'])]
self.assertEqual(1, len(guard_checks))
self.assertEqual(sorted(TARGETS), sorted(guard_checks[0]['instances']))
- # A guard binary that reports the feature passes.
+ # A guard installed with both slots reporting the feature passes.
self.setUp()
- self.world['guard'] = {t: '{"version":"v0.35.0","features":["ingress-proxy-v2"]}' for t in TARGETS}
+ self.world['guard'] = {t: {CURRENT: (NEW_BINARY, 0), PREV: (NEW_BINARY, 0)} for t in TARGETS}
self.run_prereq(expect=0)
cases = {
'TG not in S0': (lambda: self.live({'80': 'S1', '443': 'S0'}), 'S1'),
@@ -1848,11 +1858,19 @@ class PrereqTests(Harness):
"are not the NLB's node addresses"),
'no public address': (lambda: self.world['interfaces'][1].pop('public'), 'no public address'),
'no interfaces': (lambda: self.world.update(nlb_suffix='net/other/1'), 'no network interfaces'),
- # W12: an installed guard binary older than the PPv2 gate.
- 'old guard binary': (lambda: self.world.update(guard={TARGETS[1]: 'carlos v0.34.49'}),
- TARGETS[1] + ': the installed guard binary /opt/carlos/system/guard/carlos does not report'),
- 'guard without the feature': (lambda: self.world.update(
- guard={TARGETS[0]: '{"version":"v0.35.0","features":[]}'}), TARGETS[0] + ': the installed guard binary'),
+ # W12: with the guard installed, an old guard binary can fall
+ # back to carlos.prev, so both slots must report the feature.
+ 'guard, old carlos.prev': (lambda: self.world.update(
+ guard={TARGETS[1]: {CURRENT: (NEW_BINARY, 0), PREV: ('{"version":"v0.34.49","features":[]}', 0)}}),
+ TARGETS[1] + ': this box has the guard installed, and its /opt/carlos/carlos.prev does not report '
+ 'ingress-proxy-v2 ({"version":"v0.34.49","features":[]})'),
+ 'guard, carlos.prev missing': (lambda: self.world.update(
+ guard={TARGETS[0]: {CURRENT: (NEW_BINARY, 0), PREV: ('', 127)}}),
+ TARGETS[0] + ': this box has the guard installed, and its /opt/carlos/carlos.prev does not report '
+ 'ingress-proxy-v2 (exit 127)'),
+ 'guard, current without the feature': (lambda: self.world.update(
+ guard={TARGETS[0]: {CURRENT: ('carlos v0.34.49', 2), PREV: (NEW_BINARY, 0)}}),
+ TARGETS[0] + ': this box has the guard installed, and its /opt/carlos/carlos does not report'),
}
for name, (fault, text) in cases.items():
with self.subTest(case=name):
@@ -1866,5 +1884,61 @@ class PrereqTests(Harness):
self.assertFalse(record['passed'])
+class GuardCheckTests(unittest.TestCase):
+ """GUARD_CHECK run by a real sh against fake binaries, its output read
+ back by guard_refusals: the same text SSM would carry."""
+
+ def run_check(self, binaries, guard=True):
+ m = load_script()
+ with tempfile.TemporaryDirectory() as d:
+ root = Path(d)
+ for slot, body in binaries.items():
+ path = root / slot.lstrip('/')
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text('#!/bin/sh\n' + body + '\n')
+ path.chmod(0o755)
+ if guard:
+ g = root / m.GUARD_BINARY.lstrip('/')
+ g.parent.mkdir(parents=True, exist_ok=True)
+ g.write_text('')
+ script = m.GUARD_CHECK.replace('/opt/carlos/', str(root) + '/opt/carlos/')
+ r = subprocess.run(['sh', '-c', script], capture_output=True, text=True)
+ out = r.stdout.replace(str(root), '')
+ return m.guard_refusals(TARGETS[0], r.returncode, out, r.stderr)
+
+ def test_slots(self):
+ new = "echo '" + NEW_BINARY + "'"
+ old = """echo '{"version":"v0.34.49","features":[]}'"""
+ self.assertEqual([], self.run_check({}, guard=False))
+ self.assertEqual([], self.run_check({CURRENT: new, PREV: new}))
+ reasons = self.run_check({CURRENT: new, PREV: old})
+ self.assertEqual(1, len(reasons))
+ self.assertIn(f'its {PREV} does not report ingress-proxy-v2 ({{"version":"v0.34.49","features":[]}}). '
+ "The guard's recovery can fall back", reasons[0])
+ reasons = self.run_check({CURRENT: new})
+ self.assertEqual(1, len(reasons))
+ self.assertIn(f'its {PREV} does not report', reasons[0])
+ # A binary that prints the feature but fails is not trusted.
+ reasons = self.run_check({CURRENT: new + '; exit 3', PREV: new})
+ self.assertEqual(1, len(reasons))
+ self.assertIn(f'its {CURRENT} does not report', reasons[0])
+ self.assertEqual(2, len(self.run_check({CURRENT: old, PREV: 'exit 1'})))
+ self.assertIn('(exit 1)', self.run_check({CURRENT: new, PREV: 'exit 1'})[0])
+ # Astra P1: a binary that prints a forged exit line and slot marker
+ # must not pass with its real exit code moved elsewhere.
+ forged = "printf '%s\\n' '" + NEW_BINARY + "' 'ppv2-step: exit 0' 'ppv2-step: slot diagnostic'; exit 3"
+ reasons = self.run_check({CURRENT: forged, PREV: new})
+ self.assertEqual(1, len(reasons))
+ self.assertIn(f'its {CURRENT} does not report', reasons[0])
+ # Nor can one slot's output answer for the other slot.
+ fake_prev = 'ppv2-step: slot /opt/carlos/carlos.prev 0 ' + base64.b64encode(NEW_BINARY.encode()).decode()
+ reasons = self.run_check({CURRENT: new + "; echo '" + fake_prev + "'", PREV: old})
+ self.assertEqual(1, len(reasons))
+ self.assertIn(f'its {PREV} does not report', reasons[0])
+ # A malformed answer refuses both slots.
+ m = load_script()
+ self.assertEqual(2, len(m.guard_refusals(TARGETS[0], 0, 'garbage\n', '')))
+
+
if __name__ == '__main__':
unittest.main()