Skip to content

Self-host: egress fence never publishes ok after lost - #2978

Merged
simple-agent-manager[bot] merged 5 commits into
mainfrom
sam/self-host-security-investigation-rwd9ex
Nov 22, 2026
Merged

simple-agent-manager[bot] merged 5 commits into
mainfrom
sam/self-host-security-investigation-rwd9ex

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Self-hosting only. Hosted SAM is unaffected: every changed file lives under deploy/selfhost/ or scripts/selfhost/.

The L23 egress fence (deploy/selfhost/egress-fence/fence.sh) had two writers of its attestation: the kernel-event reader subprocess (lost()) and the main loop, which publishes ok <ts> through a tmp file and mv. The main loop checked $LOST and then published. If the reader latched between that check and the mv, the attestation read ok after lost until the next pass, 10-100 ms later.

  • fence.sh: lost() and the new publish() hold one flock on the fence's private tmpfs (${STATE}.lock, which no consumer can reach). publish() skips when $LOST exists, so once lost is written, no ok is ever written. The latch never depends on the lock: if the lock file cannot be opened or taken, lost() latches anyway (fail closed), while publish() publishes nothing and the attestation goes stale. The old "converge any stale ok" branch is gone, because with the lock it was dead code.
  • Consumers read the attestation first, then check the latch. $LOST is never cleared while the fence runs, so if it is absent after the read, that ok was not published after a loss. This closes the gap that remains even with the lock: the microseconds inside latch() between writing $LOST and writing lost.
    • deploy/selfhost/celld/start.sh fence_problem(): the latch check moved from before the probes to after the attestation read.
    • scripts/selfhost/verify-fence.ts checkService(): the attestation is read before fence.sh check, and its age is measured at read time.

Why this design and not the alternatives:

  • Re-checking after mv would only shrink the window.
  • Making the main loop the sole writer would delay the latch by up to one recheck interval, and still leaves the check-then-mv gap.
  • A consumer-only fix leaves ok visible in the file.
  • The lock makes the attestation's sequence of values monotonic (ok… then lost, never back). The consumer reorder makes each read sound. Both are a few lines, and busybox flock is already in the pinned Alpine image (checked: /usr/bin/flock -> /bin/busybox).

Was the main CI failure something worse?

No. Main CI run 45041955760, job 137268241147, failed in 104 ms, not at the 3 s deadline. The old test's poll saw the stub's own injected lost, left the loop, and then read the ok that the already-admitted mv published. That is exactly the window described above. I traced every way the fence can be lost:

  • monitor event → latch;
  • monitor or reader death → kill -0 → latch;
  • fingerprint drift → check() → latch;
  • main loop death → no more ok refresh → celld stops at the 2 s max age.

I found no path where $LOST is never written, and none where check() passes after a ruleset change.

Blast radius before this fix

  • celld (start.sh) re-checks every 0.1 s. A stale ok read in the window bought at most one extra check interval of serving, and the kernel table had already changed by then. The probe checks are independent of the attestation and still applied.
  • pnpm selfhost:verify-fence could report "egress fence in effect" once, for a fence that had just latched.
  • The compose healthcheck (fence.sh check) reads $LOST and the fingerprint, not the attestation, so it was never affected.

Validation

  • pnpm lint: eslint and prettier are clean on the changed TS. deploy/selfhost/README.md already failed prettier on main and is unchanged in that respect.
  • pnpm typecheck: tsc -p scripts/selfhost/live/tsconfig.json is clean.
  • pnpm test: the self-host suite tests touched here pass: fence-watchdog 2/2, and verify-fence-cli, fence-verify and fence-runtime 40 passed, 3 skipped.
  • Additional validation: the deterministic tests below; the fence-watchdog file run 200x under full CPU load (result in a comment); and the live fence-netns suite.

Deterministic tests (rule 62: the test owns the ordering). Each was shown red on the old code:

  • scripts/selfhost/fence-watchdog.test.ts: the real reader is driven by a real nft monitor event, released from inside the first mv of an ok publication. A stub flock records lock attempts. The mv stub waits until the reader has either latched (old fence) or reached the lock (fixed fence), so the latch lands between the check and the mv every time. The test asserts that no publication ever happens while $LOST exists and that the attestation stays lost. Results:
    • old fence.sh: red (['ok-while-lost']);
    • lock removed from publish(): red;
    • latch check removed from publish(): red;
    • fix: green.
    • Control: a healthy fence keeps publishing fresh ok, with no latch.
    • Unopenable lock (a directory where the lock file belongs), and flock failing on an open lock: the fence latches lost, publishes nothing, and exits 1. It goes red if publish || { lost; exit 1; } or lost()'s || latch is removed, or if publish swallows a flock failure (exit 0, the Codex finding).
  • scripts/selfhost/verify-fence-cli.test.ts "refuses an ok read just before the fence latched lost": the stub docker latches the fence right after the attestation read. Red on the old order (exit 0), green with the fix.
  • scripts/selfhost/live/fence-netns.live.test.ts "does not start on a fresh ok read after the fence latched lost": the attestation is a FIFO, so start.sh blocks inside its read. The test creates the latch only once the reader has opened the FIFO, then writes a fresh ok. Red on the old start.sh (celld started), green with the fix.
  • Live fence-netns suite, run locally in the privileged lab image (Dockerfile.lab, --privileged --network none, the same command as CI): 68/68 passed, flush-to-stop 72 ms. The Self-host Live CI job runs it again on this PR. The shared box app.vmtest.sam2.party was not used.

Staging Verification (REQUIRED for all code changes — merge-blocking)

N/A for hosted staging. The change touches only the self-host box (deploy/selfhost/, scripts/selfhost/), which hosted staging neither deploys nor runs. The task named the egress-fence live suite as the live gate instead. It runs real nftables and the real fence.sh and start.sh in a privileged network namespace, as the fenced uid. See the Validation section.

  • Infrastructure verification: N/A: no infra changes for hosted SAM (no cloud-init, VM agent, DNS, TLS or scripts/deploy changes).

Staging Verification Evidence

Live fence-netns suite: 68/68 passed in the privileged lab, plus the Self-host Live CI job.

End-to-End Verification (Required for multi-component changes)

Data Flow Trace

  1. The kernel reports a ruleset change, and nft monitor ruleset writes to the FIFO.
  2. The reader subshell in fence.sh calls lost(), takes flock, and runs latch(): it writes $LOST, then lost to the attestation, then the event.
  3. The main loop's publish() takes flock, sees [ -f $LOST ], and publishes nothing.
  4. celld/start.sh fence_problem() reads the attestation, then checks $LOST; the latch is present, so it SIGKILLs celld.
  5. verify-fence.ts checkService() reads the attestation, then fence.sh check fails because of $LOST, so it reports a failure.

Untested Gaps

N/A: every ordering is covered by the deterministic tests above.

Post-Mortem (Required for bug fix PRs)

What broke

The fence attestation could read ok for up to one recheck interval after the fence latched lost, and the watchdog test flaked on main and on PR #2960.

Root cause

L23 (#2917) gave the attestation two writers with no mutual exclusion, and its consumers checked the latch before reading the attestation.

Class of bug

Check-then-act across two processes writing one file (TOCTOU), plus a consumer reading two signals in the unsafe order.

Why it wasn't caught

The original test forced the race but exited its poll on the intermediate state. It accepted eventual convergence instead of asserting that no ok follows lost, and the code comment named the window as acceptable.

Process fix included in this PR

The tests now own the ordering, through stub barriers and a FIFO, rather than relying on timing. No rule change: rule 62 already covers this; the original test predated applying it.

Post-mortem file

tasks/archive/2026-11-22-egress-fence-ok-after-lost.md

Specialist Review Evidence (Required for agent-authored PRs)

  • All local reviewers completed and findings addressed before merge
  • If any reviewer did NOT complete: needs-human-review label added and merge deferred to human (N/A: all completed)
Reviewer Status Outcome
security-auditor ADDRESSED No CRITICAL or HIGH findings. MEDIUM: a failed publish (lock open, ENOSPC) exited under set -e without latching. Fixed in 738b9da: publish || { lost; exit 1; }, plus a new unopenable-lock test that goes red if either fallback is removed. LOW: the single-instance assumption is now documented in the comment and README. LOW, not fixed: shutdown noise in events.jsonl, a zombie kill -0, and real nft monitor formatting (partly covered by the live suite). None of these is a fail-open.
go-specialist (shell/nft concurrency) ADDRESSED PASS. Confirmed flock per open file description, no fd 9 leak into long-lived children, ||-context errexit, and no deadlock. LOW 1 (an inaccurate lock-failure comment) is fixed in 738b9da. LOW 2-4 (an accepted residual if only the reader's flock fails, the test's lock-reached proxy, and fixed absence windows) are not false-failure risks.
task-completion-validator PASS No CRITICAL or HIGH gaps.

CodeRabbit Review Evidence (Required for agent-authored PRs)

  • CodeRabbit requested when the PR was marked ready for review
  • Waited about 15 minutes (or until a skip, rate-limit or quota reply)
  • Either CodeRabbit reviewed and no CodeRabbit feedback is unresolved, or it did not review and the observed outcome is recorded below

CodeRabbit Notes

Requested at 16:49 UTC through the coderabbit-review label. Bot workflow run 45045959116 succeeded. CodeRabbit replied Review skipped (auto reviews disabled) and Review rate limited, so it did not review. Codex reviewed instead: one P2 (a swallowed flock failure in publish), fixed and answered on its thread.

Exceptions (If any)

  • Scope: N/A
  • Rationale: N/A
  • Expiration: N/A

Agent Preflight (Required)

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

External References

Verified busybox flock (fd form flock [-sxun] FD) in the pinned alpine:3.24 image by running it, including a contention check that showed the second holder waits. Used util-linux flock(1) in the lab image.

Codebase Impact Analysis

deploy/selfhost/egress-fence/fence.sh (writer), deploy/selfhost/celld/start.sh and scripts/selfhost/verify-fence.ts (consumers), and the compose healthcheck (unchanged; it reads $LOST and the fingerprint only). Tests: scripts/selfhost/fence-watchdog.test.ts, scripts/selfhost/verify-fence-cli.test.ts, scripts/selfhost/live/fence-netns.live.test.ts.

Documentation & Specs

Updated deploy/selfhost/README.md, "Egress fence and metadata broker". The public docs do not describe the attestation.

Constitution & Risk Check

Principle XI: no new hardcoded tunables. The lock path derives from SAM_EGRESS_FENCE_STATE. Risk: a lock-open failure. The latch does not depend on the lock (fail closed), and publication without the lock is skipped, so celld stops at the max age.

🤖 Generated with Claude Code

The fence's kernel-event reader could latch between the main loop's latch
check and its mv, leaving a fresh ok attestation after lost for one pass.
lost() and publish() now share a lock, and celld/start.sh and verify-fence
read the attestation before checking the latch. Self-host only.

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

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

raphaeltm and others added 2 commits November 22, 2026 16:48
Review follow-up: publish() failing (lock open, ENOSPC) exited under set -e
without latching. Now it latches and exits; covered by an unopenable-lock test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simple-agent-manager
simple-agent-manager Bot marked this pull request as ready for review November 22, 2026 16:49
@simple-agent-manager simple-agent-manager Bot added the coderabbit-review Trigger CodeRabbit review for opt-in PRs label Nov 22, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T17:02:16.520056Z 6e9ba47 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2936593036

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread deploy/selfhost/egress-fence/fence.sh Resolved
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simple-agent-manager

Copy link
Copy Markdown
Contributor Author

Stress result: scripts/selfhost/fence-watchdog.test.ts ran 200 times under full CPU load (8 yes hogs on 8 cores), against the final fence.sh with no edits during the run: pass=200 fail=0. An earlier run is void because I edited files while it ran. During that run, one iteration executed against the old test and fence while the tree was briefly stashed, and it reproduced the original CI failure under load: expected 'ok …' to be 'lost'.

Codex review: flock failing on an open lock returned success from publish(),
so the fence stayed up and healthy while celld's attestation went stale.

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

Copy link
Copy Markdown

@simple-agent-manager
simple-agent-manager Bot merged commit 311f625 into main Nov 22, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant