boxself: monitor files follow no symlink, read capped (#898)
The agent's self.json and verify-assign.json and the drill's local verify.json go through boxself.ReadFile and WriteFile. On Linux (safefile) no path component is followed, a read opens only a regular single-link file under a cap (64 KiB self, 1 MiB assignment and verify.json), and a write stages under a random name in a fresh 0700 directory, O_EXCL and O_NOFOLLOW, chmod 0644, fsync, renameat, never over a non-regular target. Other systems refuse (ErrUnsupported). Replaces the fixed .tmp/O_TRUNC writer and the uncapped os.ReadFile, the ls284 fault family, so a root-run agent or drill is safe without skipping on root. The claim census lists verify.json and drops the .tmp names.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/boxself/boxself.go+55 −55internal/boxself/boxself_test.go+8 −10internal/boxself/io_linux.go+84 −0internal/boxself/io_linux_test.go+297 −0internal/boxself/io_other.go+13 −0internal/dbverify/dbverify.go+5 −0internal/host/boxself_census_linux_test.go+5 −7internal/host/claimcensus.go+9 −4internal/metrics/verify.go+4 −2internal/metrics/verify_linux_test.go+81 −0internal/ops/localverify_linux_test.go+45 −0internal/ops/ops.go+6 −30
Intent
<task-notification> <task-id>a6db8b3211f158c85</task-id> <tool-use-id>toolu_01PJPi6arabCvrQBDekHp758</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a6db8b3211f158c85.output</output-file> <status>completed</status> <summary>Agent "Implement slice 1 Task 5 (CLI)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE. `carlos instances backups` is built, tested and committed on member-backups-1. Not pushed. **Commit:** a106e8af on top of d070fb13. **Tests:** the root/parity run you specified passes (`TestInstancesBackups|TestApprovedMemberBackupsCopy|TestCLIProjection|TestParityCLIPaths`, 7 new tests, failing first), as do the console's backups page tests; build, vet and gofmt are clean. **Copy:** the root CLI doesn't import internal/console, so I made a new leaf package, `internal/backupswords`. It holds the 23 strings the page and the CLI both show, the console's `backupsCopy` now reads them from there, and the copy record points at the new file. "Backups for {host}" lives in `instances_backups.go` and is no longer pending. **Concerns:** - Only the strings are shared. The rules that turn the door's answer into chips, reason line and `db pull` commands are a copy of the page's code, so a change to the page has to be repeated in the CLI by hand. - `docs/site/cli.md` gets a heading and one example command, no sentence, because no description is approved yet. The `--instance` flag help text is also new and unreviewed. - `printBackups` takes an extra `now` argument so tests can fix the time. - The root binary changed, including the new package, so Task 6's census needs to cover it. I didn't touch census testdata. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-1/.superpowers/sdd/2026-11-11-member-backups-slice1/task-5-report.md</result> <usage><subagent_tokens>135043</subagent_tokens><tool_uses>56</tool_uses><duration_ms>601023</duration_ms></usage> </task-notification>
<task-notification> <task-id>a19e9c74fb235bc01</task-id> <tool-use-id>toolu_016wK9sbjqKR6CfN69i5roTq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a19e9c74fb235bc01.output</output-file> <status>completed</status> <summary>Agent "Implement slice 2a Task 9 (census)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS. Both census tests now pass. The root-read proposal is committed but not approved; the reviewer still has to rule on #280. Commits on member-backups-2a (not pushed): - 0e60df82 adds `memberBackups2aWriteCensusInventory`, layered on the linked deployments slice 1 inventory. It re-pins `dbverify.Publish`, `dbverify.RemoveHost` and `moves.OfflineManifest`, with no class or kind changes. - c113836e adds the claims file `docs/superpowers/notes/census-claims-member-backups-2a.tsv`, the overlay, the chain line and the proposal `docs/superpowers/notes/census-proposal-member-backups-2a.md` (18 units, 14 envelopes). Tests: `TestPlan14RootReadCensus` and `TestPlan9B8RecordWriteCensus` pass, the wider `-run 'Census|Plan14|Plan9B8'` set in internal/provision passes, and `go vet ./internal/provision` is clean. Concern: the reviewer will very likely reject this. It is the same problem Astra rejected in census ruling ls284: an agent running as root must not follow paths the carlos user can write. Three new agent paths don't check for root: - `boxself.writeAtomic` truncates, writes and sets mode 0644 on the fixed `<data>/monitor/self.json.tmp` and `verify-assign.json.tmp`. A root agent would follow a symlink planted there, which is worse than the ls284 case. - `metrics.ReadVerify` reads `verify.json` every alert tick with no size limit. I'd fix this before the reviewer sees the card: skip those writes and the read when running as root, add a guard test, then rerun census-propose with the same NAME. The catch is that on a root-run box the drill would then refuse to run, because there would be no fresh `self.json`. That trade-off is yours to accept. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-2a/.superpowers/sdd/2026-11-11-member-backups-slice2a/task-9-report.md</result> <usage><subagent_tokens>148741</subagent_tokens><tool_uses>58</tool_uses><duration_ms>885404</duration_ms></usage> </task-notification>
<task-notification> <task-id>a6db8b3211f158c85</task-id> <tool-use-id>toolu_01EtPzDvSxJTNcFUmJ8kSebF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/a6db8b3211f158c85.output</output-file> <status>completed</status> <summary>Agent "Implement slice 1 Task 5 (CLI)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE. All three review findings are fixed and committed on member-backups-1. Not pushed. **Commit:** dabd213c, on top of a106e8af. **Fixes:** 1. **`--instance` help:** it now uses `carlos db pull`'s text, byte for byte. Both commands read it from one constant in `db.go`, so there's no new copy. 2. **No dash in the CLI:** "Restore test" prints just "not shown yet", and an unknown history start prints the "Go back as far as" label alone. The page keeps its "—". 3. **Shared display rules:** the decisions (chips, reason line, tiles, the two `db pull` commands, the date and `--at` helpers) now live in one function, `backupswords.Show`. The console page and the CLI both call it and only lay out the result. The console's class, reason and files values now come from the same package. **Tests:** - Root, parity and `backupswords`: 13 tests pass, including a new table test over every class and reason and a new test that the `--instance` help matches `db pull`'s. - Console backups, including the page tests: 18 pass. - Build, vet and gofmt are clean. - Every new or changed test failed first. **Concerns:** - The root binary and internal/console both changed again; census testdata is left for Task 6. - I didn't run the `db pull`/`db query` tests after moving the `--instance` text into a constant. The text is unchanged, and the build and the new test cover it. Report (fix section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-1/.superpowers/sdd/2026-11-11-member-backups-slice1/task-5-report.md</result> <usage><subagent_tokens>163354</subagent_tokens><tool_uses>20</tool_uses><duration_ms>317237</duration_ms></usage> </task-notification>
diff --git a/internal/boxself/boxself.go b/internal/boxself/boxself.go| index f51ae52ef..004f8d9df 100644 |
| --- a/internal/boxself/boxself.go |
| +++ b/internal/boxself/boxself.go |
| @@ -6,9 +6,17 @@ |
| // restore drill (carlos ops hibernate-verify) reads both; it cannot work |
| // either out for itself. |
| // |
| -// Both files are written whole (a temp file renamed into place), mode |
| -// 0644, so the drill, which runs as the same user, reads one or the other |
| -// version and never half of one. |
| +// Both files, and the drill's local copy of its record that the agent's |
| +// alerts read (dbverify.LocalPath), go through ReadFile and WriteFile: |
| +// on Linux no symlink is followed in any component of the path, only a |
| +// regular file with one link is read, a read is capped, and a write |
| +// stages under a random name in a fresh private directory beside the |
| +// target, syncs it, sets mode 0644 and renames it into place, never over |
| +// anything but a regular file. The drill, which runs as the same user, |
| +// reads one version or the other and never half of one. The agent and the |
| +// drill run as user carlos in their units, but nothing here relies on it: |
| +// a process running as root follows no path the carlos user can plant. |
| +// Elsewhere every read and write is refused (ErrUnsupported). |
| package boxself |
| import ( |
| @@ -16,7 +24,6 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| - "io" |
| "os" |
| "path/filepath" |
| "slices" |
| @@ -29,10 +36,23 @@ const ( |
| dirName = "monitor" |
| selfName = "self.json" |
| assignName = "verify-assign.json" |
| - // maxRead bounds a read: the assignment names every HA host once. |
| - maxRead = 16 << 20 |
| + // maxSelf bounds self.json, a few dozen bytes. maxAssign bounds the |
| + // assignment, which names every HA host once (about 60 bytes each); |
| + // WriteAssignment refuses one over it, so the agent says so rather |
| + // than the drill finding a file it will not read. |
| + maxSelf = 64 << 10 |
| + maxAssign = 1 << 20 |
| ) |
| +// ErrUnsafe refuses a monitor file that is not a regular file with one |
| +// link reached without following a symlink, a write over anything but a |
| +// regular file, and a read over its cap. |
| +var ErrUnsafe = errors.New("boxself: not a regular file reached without a symlink, or over its size") |
| + |
| +// ErrUnsupported is every read and write on a system other than Linux: |
| +// the agent and the drill run only there. |
| +var ErrUnsupported = errors.New("boxself: the monitor files are read and written only on Linux") |
| + |
| // Self is this box as the agent names it. |
| type Self struct { |
| // Ref is the box's reference: the label its metrics publish under, |
| @@ -127,7 +147,7 @@ func writeSelf(dataDir string, s Self) error { |
| if err != nil { |
| return err |
| } |
| - return writeAtomic(SelfPath(dataDir), body) |
| + return WriteFile(SelfPath(dataDir), body, maxSelf) |
| } |
| // Read is the self Write last recorded. An error wrapping os.ErrNotExist |
| @@ -135,7 +155,7 @@ func writeSelf(dataDir string, s Self) error { |
| // is not one (wrong version, a reference ValidRef refuses, not JSON). |
| func Read(dataDir string) (Self, error) { |
| var d selfDoc |
| - if err := readStrict(SelfPath(dataDir), &d); err != nil { |
| + if err := readStrict(SelfPath(dataDir), maxSelf, &d); err != nil { |
| return Self{}, err |
| } |
| if d.V != 1 { |
| @@ -181,7 +201,7 @@ func WriteAssignment(dataDir string, a Assignment) error { |
| if err != nil { |
| return err |
| } |
| - return writeAtomic(AssignmentPath(dataDir), body) |
| + return WriteFile(AssignmentPath(dataDir), body, maxAssign) |
| } |
| // ReadAssignment is the assignment WriteAssignment last recorded, with |
| @@ -189,7 +209,7 @@ func WriteAssignment(dataDir string, a Assignment) error { |
| // box whose agent has not computed one yet. |
| func ReadAssignment(dataDir string) (Assignment, error) { |
| var d assignDoc |
| - if err := readStrict(AssignmentPath(dataDir), &d); err != nil { |
| + if err := readStrict(AssignmentPath(dataDir), maxAssign, &d); err != nil { |
| return Assignment{}, err |
| } |
| if d.V != 1 { |
| @@ -225,24 +245,37 @@ func checkAssignment(a Assignment) error { |
| return nil |
| } |
| -// remove is os.Remove; a test makes it fail. |
| -var remove = os.Remove |
| +// remove and write are removeFile and writeFile; a test makes them fail. |
| +var ( |
| + remove = removeFile |
| + write = writeFile |
| +) |
| + |
| +// ReadFile is the body of the monitor file at path, at most max bytes. |
| +// A missing file (or directory) is an error wrapping os.ErrNotExist; a |
| +// symlink anywhere in the path, a file that is not regular or has more |
| +// than one link, and one over max are ErrUnsafe. |
| +func ReadFile(path string, max int) ([]byte, error) { return readFile(path, max) } |
| + |
| +// WriteFile replaces the monitor file at path with body, creating its |
| +// directory (0755) if needed: staged under a random name, synced, mode |
| +// 0644 whatever the umask, and renamed into place. It refuses a body over |
| +// max, and (ErrUnsafe) a path through a symlink or one that holds anything |
| +// but a regular file. |
| +func WriteFile(path string, body []byte, max int) error { |
| + if len(body) > max { |
| + return fmt.Errorf("%w: %s would be %d bytes, over %d", ErrUnsafe, path, len(body), max) |
| + } |
| + return write(path, body) |
| +} |
| // readStrict decodes the one JSON value at path into v, refusing unknown |
| // fields, a wrong type and anything after the value. |
| -func readStrict(path string, v any) error { |
| - f, err := os.Open(path) |
| - if err != nil { |
| - return err |
| - } |
| - defer f.Close() |
| - body, err := io.ReadAll(io.LimitReader(f, maxRead+1)) |
| +func readStrict(path string, max int, v any) error { |
| + body, err := ReadFile(path, max) |
| if err != nil { |
| return err |
| } |
| - if len(body) > maxRead { |
| - return fmt.Errorf("boxself: %s is over %d bytes", path, maxRead) |
| - } |
| dec := json.NewDecoder(bytes.NewReader(body)) |
| dec.DisallowUnknownFields() |
| if err := dec.Decode(v); err != nil { |
| @@ -253,36 +286,3 @@ func readStrict(path string, v any) error { |
| } |
| return nil |
| } |
| - |
| -// writeAtomic puts body at path through path+".tmp", synced and renamed, |
| -// mode 0644 whatever the umask, creating the directory (0755) if needed. |
| -// The scratch name is fixed so a crash leaves one known file, which the |
| -// next write replaces. |
| -func writeAtomic(path string, body []byte) error { |
| - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| - return err |
| - } |
| - tmp := path + ".tmp" |
| - f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) |
| - if err != nil { |
| - return err |
| - } |
| - _, err = f.Write(body) |
| - if err == nil { |
| - err = f.Chmod(0o644) |
| - } |
| - if err == nil { |
| - err = f.Sync() |
| - } |
| - if cerr := f.Close(); err == nil { |
| - err = cerr |
| - } |
| - if err == nil { |
| - err = os.Rename(tmp, path) |
| - } |
| - if err != nil { |
| - os.Remove(tmp) |
| - return err |
| - } |
| - return nil |
| -} |
diff --git a/internal/boxself/boxself_test.go b/internal/boxself/boxself_test.go| index b10944343..c49cf9e6f 100644 |
| --- a/internal/boxself/boxself_test.go |
| +++ b/internal/boxself/boxself_test.go |
| @@ -161,11 +161,11 @@ func TestBoxSelfFailedWriteWithdrawsTheOldSelf(t *testing.T) { |
| for name, fail := range map[string]func(dir string) Self{ |
| // The new reference is refused before anything is written. |
| "refused ref": func(string) Self { return Self{Ref: "", At: selfAt} }, |
| - // The scratch file cannot be created: a directory holds its name. |
| - "scratch blocked": func(dir string) Self { |
| - if err := os.MkdirAll(filepath.Join(SelfPath(dir)+".tmp", "x"), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| + // The write itself fails (a full disk, say). |
| + "write fails": func(string) Self { |
| + was := write |
| + write = func(string, []byte) error { return errors.New("no space left on device") } |
| + t.Cleanup(func() { write = was }) |
| return Self{Ref: "jolly-otter", At: selfAt} |
| }, |
| } { |
| @@ -270,12 +270,10 @@ func TestBoxSelfStaleWhenWriteAndRemovalFail(t *testing.T) { |
| if err := Write(dir, old); err != nil { |
| t.Fatal(err) |
| } |
| - was := remove |
| + was, wasWrite := remove, write |
| remove = func(string) error { return errors.New("read-only file system") } |
| - t.Cleanup(func() { remove = was }) |
| - if err := os.MkdirAll(filepath.Join(SelfPath(dir)+".tmp", "x"), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| + write = func(string, []byte) error { return errors.New("read-only file system") } |
| + t.Cleanup(func() { remove, write = was, wasWrite }) |
| check(t, dir, Write(dir, Self{Ref: "jolly-otter", At: now})) |
| }) |
| } |
diff --git a/internal/boxself/io_linux.go b/internal/boxself/io_linux.go| new file mode 100644 |
| index 000000000..144ea4bac |
| --- /dev/null |
| +++ b/internal/boxself/io_linux.go |
| @@ -0,0 +1,84 @@ |
| +//go:build linux |
| + |
| +package boxself |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + |
| + "github.com/carlosframework/platform/internal/safefile" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// readFile opens path through safefile, which walks every directory from |
| +// / with O_NOFOLLOW and opens the last component only after an |
| +// O_PATH|O_NOFOLLOW handle shows a regular file with one link (so a |
| +// symlink, a FIFO, a socket, a device or a directory is never opened for |
| +// reading), then reads at most max bytes. |
| +func readFile(path string, max int) ([]byte, error) { |
| + f, err := safefile.OpenFile(path, os.O_RDONLY, 0) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, err |
| + } |
| + return nil, fmt.Errorf("%w: %s: %v", ErrUnsafe, path, err) |
| + } |
| + defer f.Close() |
| + body, err := io.ReadAll(io.LimitReader(f, int64(max)+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(body) > max { |
| + return nil, fmt.Errorf("%w: %s is over %d bytes", ErrUnsafe, path, max) |
| + } |
| + return body, nil |
| +} |
| + |
| +// writeFile creates the directory without following a symlink, opens it |
| +// the same way, refuses a target that exists and is not a regular file |
| +// (fstatat with AT_SYMLINK_NOFOLLOW: a symlink there is refused, not |
| +// followed), and hands the bytes to safefile.WriteAt: a fresh 0700 |
| +// staging directory under a random name in that directory, the file |
| +// created in it with O_CREAT|O_EXCL|O_NOFOLLOW, written, chmod 0644, |
| +// fsynced, renamed onto the target relative to the open directory, and |
| +// the directory fsynced. A rename replaces a name and never follows it, |
| +// so a symlink planted after the check is replaced, not written through. |
| +func writeFile(path string, body []byte) error { |
| + dir, name := filepath.Dir(path), filepath.Base(path) |
| + if err := safefile.MkdirAll(dir, 0o755); err != nil { |
| + return unsafeOr(path, err) |
| + } |
| + d, err := safefile.OpenDir(dir) |
| + if err != nil { |
| + return unsafeOr(path, err) |
| + } |
| + defer d.Close() |
| + var st unix.Stat_t |
| + switch err := unix.Fstatat(int(d.Fd()), name, &st, unix.AT_SYMLINK_NOFOLLOW); { |
| + case err == unix.ENOENT: |
| + case err != nil: |
| + return &os.PathError{Op: "stat", Path: path, Err: err} |
| + case st.Mode&unix.S_IFMT != unix.S_IFREG: |
| + return fmt.Errorf("%w: %s is not a regular file, so it is not replaced", ErrUnsafe, path) |
| + } |
| + return safefile.WriteAt(int(d.Fd()), name, body, 0o644) |
| +} |
| + |
| +// removeFile unlinks path's last component relative to its directory, |
| +// opened without following a symlink. A symlink there is removed, never |
| +// followed; a directory there is refused. |
| +func removeFile(path string) error { |
| + return safefile.Remove(path) |
| +} |
| + |
| +// unsafeOr marks a symlinked or non-directory component as ErrUnsafe and |
| +// passes any other error through. |
| +func unsafeOr(path string, err error) error { |
| + if errors.Is(err, unix.ELOOP) || errors.Is(err, unix.ENOTDIR) { |
| + return fmt.Errorf("%w: %s: %v", ErrUnsafe, path, err) |
| + } |
| + return err |
| +} |
diff --git a/internal/boxself/io_linux_test.go b/internal/boxself/io_linux_test.go| new file mode 100644 |
| index 000000000..d9cf6d8d3 |
| --- /dev/null |
| +++ b/internal/boxself/io_linux_test.go |
| @@ -0,0 +1,297 @@ |
| +//go:build linux |
| + |
| +package boxself |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The monitor files' I/O follows no symlink and touches nothing but a |
| +// regular file, so a process running as root (or as carlos) cannot be |
| +// pointed at another file by whoever can write <data>/monitor. |
| + |
| +const victimBody = "root-owned secret\n" |
| + |
| +// victim is a file outside the data dir that a planted link points at. |
| +func victim(t *testing.T) string { |
| + t.Helper() |
| + p := filepath.Join(t.TempDir(), "victim") |
| + if err := os.WriteFile(p, []byte(victimBody), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| +} |
| + |
| +func untouched(t *testing.T, p string) { |
| + t.Helper() |
| + body, err := os.ReadFile(p) |
| + if err != nil || string(body) != victimBody { |
| + t.Fatalf("the link target was touched: %q, %v", body, err) |
| + } |
| + fi, err := os.Stat(p) |
| + if err != nil || fi.Mode().Perm() != 0o600 { |
| + t.Fatalf("the link target's mode changed: %v, %v", fi.Mode(), err) |
| + } |
| +} |
| + |
| +// monitorWriters are the three files written through WriteFile. |
| +func monitorWriters(dir string) map[string]struct { |
| + path string |
| + write func() error |
| +} { |
| + at := time.Now() |
| + return map[string]struct { |
| + path string |
| + write func() error |
| + }{ |
| + "self.json": {SelfPath(dir), func() error { return Write(dir, Self{Ref: "jolly-otter", At: at}) }}, |
| + "verify-assign.json": {AssignmentPath(dir), func() error { |
| + return WriteAssignment(dir, Assignment{At: at, Hosts: map[string]string{"shop.example.com": "jolly-otter"}}) |
| + }}, |
| + "verify.json": {filepath.Join(dir, "monitor", "verify.json"), func() error { |
| + return WriteFile(filepath.Join(dir, "monitor", "verify.json"), []byte(`{"v":2}`), 1<<20) |
| + }}, |
| + } |
| +} |
| + |
| +// TestMonitorWriteRefusesSymlinkTarget: a symlink planted at the target |
| +// is not written through; the write is refused and the target untouched. |
| +func TestMonitorWriteRefusesSymlinkTarget(t *testing.T) { |
| + for name := range monitorWriters("") { |
| + t.Run(name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + w := monitorWriters(dir)[name] |
| + v := victim(t) |
| + if err := os.MkdirAll(filepath.Dir(w.path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(v, w.path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.write(); err == nil { |
| + t.Fatal("a write through a symlinked target succeeded") |
| + } |
| + untouched(t, v) |
| + }) |
| + } |
| +} |
| + |
| +// TestMonitorWriteIgnoresOldScratchLink: the scratch name is random in a |
| +// fresh private directory, so a symlink at the old fixed scratch name |
| +// (<file>.tmp) is never opened: the write lands and the target is |
| +// untouched. |
| +func TestMonitorWriteIgnoresOldScratchLink(t *testing.T) { |
| + for name := range monitorWriters("") { |
| + t.Run(name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + w := monitorWriters(dir)[name] |
| + v := victim(t) |
| + if err := os.MkdirAll(filepath.Dir(w.path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(v, w.path+".tmp"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.write(); err != nil { |
| + t.Fatal(err) |
| + } |
| + untouched(t, v) |
| + if fi, err := os.Lstat(w.path); err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("target after the write: %v, %v; want a 0644 regular file", fi, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestMonitorWriteRefusesSymlinkedDir: a symlink at the monitor directory |
| +// (or above it) is not followed; nothing is created where it points. |
| +func TestMonitorWriteRefusesSymlinkedDir(t *testing.T) { |
| + for name := range monitorWriters("") { |
| + t.Run(name, func(t *testing.T) { |
| + dir, elsewhere := t.TempDir(), t.TempDir() |
| + if err := os.Symlink(elsewhere, filepath.Join(dir, "monitor")); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := monitorWriters(dir)[name].write() |
| + if !errors.Is(err, ErrUnsafe) { |
| + t.Fatalf("write through a symlinked monitor dir: %v, want ErrUnsafe", err) |
| + } |
| + if entries, _ := os.ReadDir(elsewhere); len(entries) != 0 { |
| + t.Fatalf("the write created %d entries where the link points", len(entries)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestMonitorWriteRefusesNonRegularTarget: a directory or a FIFO at the |
| +// target is refused, not replaced. |
| +func TestMonitorWriteRefusesNonRegularTarget(t *testing.T) { |
| + for _, kind := range []string{"dir", "fifo"} { |
| + for name := range monitorWriters("") { |
| + t.Run(kind+"/"+name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + w := monitorWriters(dir)[name] |
| + plantNonRegular(t, kind, w.path) |
| + if err := w.write(); err == nil { |
| + t.Fatal("a write over a non-regular file succeeded") |
| + } |
| + // Never replaced by a record. A refused self write then |
| + // withdraws what is at the name, so a FIFO there is |
| + // unlinked (a directory is not); nothing is followed. |
| + fi, err := os.Lstat(w.path) |
| + if err == nil && fi.Mode().IsRegular() || err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the %s at the target was replaced: %v, %v", kind, fi, err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// TestMonitorWriteModeIgnoresUmask: the written file is 0644 whatever the |
| +// umask, so the drill and the agent can read each other's files. |
| +func TestMonitorWriteModeIgnoresUmask(t *testing.T) { |
| + old := syscall.Umask(0o077) |
| + defer syscall.Umask(old) |
| + dir := t.TempDir() |
| + if err := Write(dir, Self{Ref: "jolly-otter", At: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if fi, err := os.Stat(SelfPath(dir)); err != nil || fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("self.json mode: %v, %v; want 0644", fi, err) |
| + } |
| +} |
| + |
| +// TestMonitorReadRefusesUnsafe: a read follows no symlink and reads only |
| +// a regular file with one link, within its cap. |
| +func TestMonitorReadRefusesUnsafe(t *testing.T) { |
| + good := `{"v":1,"ref":"jolly-otter","group":false,"at":"2026-11-11T03:00:00Z"}` |
| + for _, tc := range []struct { |
| + name string |
| + plant func(t *testing.T, path string) |
| + }{ |
| + {"symlink to a good record", func(t *testing.T, path string) { |
| + src := filepath.Join(t.TempDir(), "self.json") |
| + if err := os.WriteFile(src, []byte(good), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(src, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"hard link", func(t *testing.T, path string) { |
| + if err := os.WriteFile(path, []byte(good), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Link(path, path+".second"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"fifo", func(t *testing.T, path string) { plantNonRegular(t, "fifo", path) }}, |
| + {"dir", func(t *testing.T, path string) { plantNonRegular(t, "dir", path) }}, |
| + {"over the cap", func(t *testing.T, path string) { |
| + big := good[:len(good)-1] + `,"pad":"` + strings.Repeat("x", maxSelf) + `"}` |
| + if err := os.WriteFile(path, []byte(big), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(dir, "monitor"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + tc.plant(t, SelfPath(dir)) |
| + done := make(chan error, 1) |
| + go func() { _, err := Read(dir); done <- err }() |
| + select { |
| + case err := <-done: |
| + if !errors.Is(err, ErrUnsafe) { |
| + t.Fatalf("Read = %v, want ErrUnsafe", err) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("Read blocked (opened a FIFO?)") |
| + } |
| + }) |
| + } |
| + // A symlinked monitor directory is refused too. |
| + dir, elsewhere := t.TempDir(), t.TempDir() |
| + if err := os.WriteFile(filepath.Join(elsewhere, "self.json"), []byte(good), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(elsewhere, filepath.Join(dir, "monitor")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := Read(dir); err == nil || errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("Read through a symlinked monitor dir = %v, want a refusal", err) |
| + } |
| +} |
| + |
| +// TestMonitorAssignmentCap: an assignment over its cap is refused on |
| +// write, and one planted over it is refused on read. |
| +func TestMonitorAssignmentCap(t *testing.T) { |
| + dir := t.TempDir() |
| + hosts := map[string]string{} |
| + // Each entry is about 41 bytes: "shop-0000001.example.com":"jolly-otter", |
| + for i := 0; i < maxAssign/40+100; i++ { |
| + hosts[fmt.Sprintf("shop-%07d.example.com", i)] = "jolly-otter" |
| + } |
| + if err := WriteAssignment(dir, Assignment{At: time.Now(), Hosts: hosts}); !errors.Is(err, ErrUnsafe) { |
| + t.Fatalf("oversized WriteAssignment = %v, want ErrUnsafe", err) |
| + } |
| + if err := os.MkdirAll(filepath.Join(dir, "monitor"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := append([]byte(`{"v":1,"at":"2026-11-11T03:00:00Z","hosts":{},"unknown":[],"pad":"`), bytes.Repeat([]byte("x"), maxAssign)...) |
| + if err := os.WriteFile(AssignmentPath(dir), append(body, `"}`...), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := ReadAssignment(dir); !errors.Is(err, ErrUnsafe) { |
| + t.Fatalf("oversized ReadAssignment = %v, want ErrUnsafe", err) |
| + } |
| +} |
| + |
| +// TestFailedWriteRemovesPlantedLinkNotTarget: a refused self write |
| +// withdraws what is at self.json; for a planted symlink that is the link, |
| +// never the file it points at. |
| +func TestFailedWriteRemovesPlantedLinkNotTarget(t *testing.T) { |
| + dir := t.TempDir() |
| + v := victim(t) |
| + if err := os.MkdirAll(filepath.Join(dir, "monitor"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(v, SelfPath(dir)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := Write(dir, Self{Ref: "jolly-otter", At: time.Now()}); err == nil { |
| + t.Fatal("write through a symlinked self.json succeeded") |
| + } |
| + untouched(t, v) |
| + if _, err := os.Lstat(SelfPath(dir)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the planted link is still there: %v", err) |
| + } |
| +} |
| + |
| +func plantNonRegular(t *testing.T, kind, path string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + var err error |
| + switch kind { |
| + case "dir": |
| + err = os.Mkdir(path, 0o755) |
| + case "fifo": |
| + err = syscall.Mkfifo(path, 0o644) |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/boxself/io_other.go b/internal/boxself/io_other.go| new file mode 100644 |
| index 000000000..7eb5572a5 |
| --- /dev/null |
| +++ b/internal/boxself/io_other.go |
| @@ -0,0 +1,13 @@ |
| +//go:build !linux |
| + |
| +package boxself |
| + |
| +// The agent and the drill run only on Linux; anywhere else every monitor |
| +// file read and write is refused rather than done without the Linux |
| +// no-follow guarantees. |
| + |
| +func readFile(string, int) ([]byte, error) { return nil, ErrUnsupported } |
| + |
| +func writeFile(string, []byte) error { return ErrUnsupported } |
| + |
| +func removeFile(string) error { return ErrUnsupported } |
diff --git a/internal/dbverify/dbverify.go b/internal/dbverify/dbverify.go| index e7574c60d..7ff0d9917 100644 |
| --- a/internal/dbverify/dbverify.go |
| +++ b/internal/dbverify/dbverify.go |
| @@ -54,6 +54,11 @@ func LocalPath(dataDir string) string { |
| return filepath.Join(filepath.Dir(boxself.SelfPath(dataDir)), "verify.json") |
| } |
| +// LocalMax caps the local copy: the drill refuses to write one over it and |
| +// the agent refuses to read one (both through boxself's no-follow I/O). A |
| +// verdict is a few hundred bytes, so it holds a few thousand hosts. |
| +const LocalMax = 1 << 20 |
| + |
| // The three results. |
| const ( |
| ResultPassed = "passed" |
diff --git a/internal/host/boxself_census_linux_test.go b/internal/host/boxself_census_linux_test.go| index c4ac30ad8..58a922143 100644 |
| --- a/internal/host/boxself_census_linux_test.go |
| +++ b/internal/host/boxself_census_linux_test.go |
| @@ -4,19 +4,19 @@ package host |
| import ( |
| "errors" |
| - "os" |
| "path/filepath" |
| "slices" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| "github.com/carlosframework/platform/internal/hostbox" |
| ) |
| // TestBoxSelfFilesInClaimCensus: the drill records the agent writes on |
| -// every box, and the scratch a crashed write leaves, are classified box |
| -// files, so a claim census over the data dir does not refuse them. |
| +// every box, and the drill's local copy of its own record, are classified |
| +// box files, so a claim census over the data dir does not refuse them. |
| func TestBoxSelfFilesInClaimCensus(t *testing.T) { |
| data, opt, units := t.TempDir(), t.TempDir(), t.TempDir() |
| if err := boxself.Write(data, boxself.Self{Ref: "g-0123456789abcdef0123", Group: true, At: time.Now()}); err != nil { |
| @@ -25,10 +25,8 @@ func TestBoxSelfFilesInClaimCensus(t *testing.T) { |
| if err := boxself.WriteAssignment(data, boxself.Assignment{At: time.Now(), Hosts: map[string]string{"shop.example.com": "g-0123456789abcdef0123"}}); err != nil { |
| t.Fatal(err) |
| } |
| - for _, p := range []string{boxself.SelfPath(data) + ".tmp", boxself.AssignmentPath(data) + ".tmp"} { |
| - if err := os.WriteFile(p, []byte("{"), 0o644); err != nil { |
| - t.Fatal(err) |
| - } |
| + if err := boxself.WriteFile(dbverify.LocalPath(data), []byte(`{"v":2}`), dbverify.LocalMax); err != nil { |
| + t.Fatal(err) |
| } |
| roots := map[string]string{"data": data, "opt": opt, "units": units} |
| shared := map[string][]string{"data": claimDataCensus(data)} |
diff --git a/internal/host/claimcensus.go b/internal/host/claimcensus.go| index c5b4eb465..bf0fefcf5 100644 |
| --- a/internal/host/claimcensus.go |
| +++ b/internal/host/claimcensus.go |
| @@ -9,6 +9,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -114,10 +115,14 @@ func claimBoxDataCensus(dataDir string) []string { |
| // geoipmirror.go's "current") and the metrics loop's alert state. |
| filepath.Join(dataDir, "carlos", "geoip", "current"), |
| filepath.Join(dataDir, "monitor", "alerts.json"), |
| - // The agent's records for the nightly restore drill (boxself), |
| - // and the scratch a crashed write of either leaves. |
| - boxself.SelfPath(dataDir), boxself.SelfPath(dataDir) + ".tmp", |
| - boxself.AssignmentPath(dataDir), boxself.AssignmentPath(dataDir) + ".tmp", |
| + // The agent's records for the nightly restore drill (boxself) and |
| + // the drill's local copy of its record (dbverify.LocalPath). All |
| + // three are written through boxself.WriteFile, whose staging |
| + // directory is removed after the rename; a crash between the two |
| + // leaves a .carlos-write-* directory holding the staged file, |
| + // which this census does not classify and so refuses (fails |
| + // closed); an operator removes it. |
| + boxself.SelfPath(dataDir), boxself.AssignmentPath(dataDir), dbverify.LocalPath(dataDir), |
| } { |
| files = append(files, hostbox.CensusFile(rel(path))) |
| } |
diff --git a/internal/metrics/verify.go b/internal/metrics/verify.go| index ac75079f6..b3c931e86 100644 |
| --- a/internal/metrics/verify.go |
| +++ b/internal/metrics/verify.go |
| @@ -5,11 +5,11 @@ import ( |
| "errors" |
| "fmt" |
| "io/fs" |
| - "os" |
| "sort" |
| "time" |
| "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/boxself" |
| "github.com/carlosframework/platform/internal/dbverify" |
| ) |
| @@ -56,7 +56,9 @@ type VerifyReading struct { |
| // not parse, or is a record version this does not know, is an error and no |
| // reading, so the rules hold. |
| func ReadVerify(path string, now time.Time) (*VerifyReading, error) { |
| - body, err := os.ReadFile(path) |
| + // No symlink followed, a regular file only, at most LocalMax bytes: |
| + // the agent reads what the drill wrote and nothing it was pointed at. |
| + body, err := boxself.ReadFile(path, dbverify.LocalMax) |
| if errors.Is(err, fs.ErrNotExist) { |
| return nil, nil |
| } |
diff --git a/internal/metrics/verify_linux_test.go b/internal/metrics/verify_linux_test.go| new file mode 100644 |
| index 000000000..642224ed3 |
| --- /dev/null |
| +++ b/internal/metrics/verify_linux_test.go |
| @@ -0,0 +1,81 @@ |
| +//go:build linux |
| + |
| +package metrics |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxself" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| +) |
| + |
| +// TestReadVerifyRefusesUnsafe: the agent reads the drill's local copy |
| +// only as a regular file with one link, reached without a symlink, and at |
| +// most dbverify.LocalMax bytes. Anything else is no reading and an error, |
| +// never another file's contents. |
| +func TestReadVerifyRefusesUnsafe(t *testing.T) { |
| + good := `{"v":2,"box":"jolly-otter","checked_at":"2026-11-11T03:00:00Z","hosts":{}}` |
| + for _, tc := range []struct { |
| + name string |
| + plant func(t *testing.T, path string) |
| + }{ |
| + {"symlink to a good record", func(t *testing.T, path string) { |
| + src := filepath.Join(t.TempDir(), "verify.json") |
| + if err := os.WriteFile(src, []byte(good), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(src, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"over the cap", func(t *testing.T, path string) { |
| + big := good[:len(good)-1] + `,"pad":"` + strings.Repeat("x", dbverify.LocalMax) + `"}` |
| + if err := os.WriteFile(path, []byte(big), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"fifo", func(t *testing.T, path string) { |
| + if err := syscall.Mkfifo(path, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"dir", func(t *testing.T, path string) { |
| + if err := os.Mkdir(path, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "verify.json") |
| + tc.plant(t, path) |
| + type result struct { |
| + v *VerifyReading |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { v, err := ReadVerify(path, time.Now()); done <- result{v, err} }() |
| + select { |
| + case r := <-done: |
| + if r.v != nil || !errors.Is(r.err, boxself.ErrUnsafe) { |
| + t.Fatalf("ReadVerify = %+v, %v; want no reading and ErrUnsafe", r.v, r.err) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("ReadVerify blocked (opened a FIFO?)") |
| + } |
| + }) |
| + } |
| + // A good record still reads. |
| + path := filepath.Join(t.TempDir(), "verify.json") |
| + if err := os.WriteFile(path, []byte(good), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, err := ReadVerify(path, time.Now()); v == nil || err != nil { |
| + t.Fatalf("a good record: %+v, %v", v, err) |
| + } |
| +} |
diff --git a/internal/ops/localverify_linux_test.go b/internal/ops/localverify_linux_test.go| new file mode 100644 |
| index 000000000..dcdfd53d8 |
| --- /dev/null |
| +++ b/internal/ops/localverify_linux_test.go |
| @@ -0,0 +1,45 @@ |
| +//go:build linux |
| + |
| +package ops |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/dbverify" |
| +) |
| + |
| +// TestWriteLocalVerifyFollowsNoLink: the drill's local copy is written |
| +// through boxself.WriteFile, so a symlink planted at verify.json (or at a |
| +// guessable scratch name beside it) is never written through; the file it |
| +// points at is untouched. |
| +func TestWriteLocalVerifyFollowsNoLink(t *testing.T) { |
| + rec := &dbverify.Record{V: 2, Box: "jolly-otter", CheckedAt: time.Now().UTC(), Hosts: map[string]dbverify.Verdict{}} |
| + for _, at := range []string{"verify.json", "verify.json.tmp"} { |
| + t.Run(at, func(t *testing.T) { |
| + data := t.TempDir() |
| + victim := filepath.Join(t.TempDir(), "victim") |
| + if err := os.WriteFile(victim, []byte("keep"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.MkdirAll(filepath.Join(data, "monitor"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(victim, filepath.Join(data, "monitor", at)); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := writeLocalVerify(data, rec) |
| + if at == "verify.json" && err == nil { |
| + t.Fatal("a write through a symlinked verify.json succeeded") |
| + } |
| + if at != "verify.json" && err != nil { |
| + t.Fatalf("a link beside the target blocked the write: %v", err) |
| + } |
| + if body, err := os.ReadFile(victim); err != nil || string(body) != "keep" { |
| + t.Fatalf("the link target was touched: %q, %v", body, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index 793f8983b..d18870a14 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -18,7 +18,6 @@ import ( |
| "os" |
| "os/exec" |
| "os/signal" |
| - "path/filepath" |
| "strings" |
| "syscall" |
| "time" |
| @@ -548,40 +547,17 @@ func localVerifyPath(dataDir string) string { |
| return dbverify.LocalPath(dataDir) |
| } |
| -// writeLocalVerify writes rec to the local alert copy whole (a temp file |
| -// synced and renamed into place), mode 0644, so the agent reads one version |
| -// or the other and never half of one. |
| +// writeLocalVerify writes rec to the local alert copy whole through |
| +// boxself.WriteFile (no symlink followed, a random staging name, synced, |
| +// mode 0644, renamed into place, never over anything but a regular file), |
| +// so the agent reads one version or the other and never half of one. A |
| +// record over dbverify.LocalMax is refused. |
| func writeLocalVerify(dataDir string, rec *dbverify.Record) error { |
| body, err := json.Marshal(rec) |
| if err != nil { |
| return err |
| } |
| - path := localVerifyPath(dataDir) |
| - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| - return err |
| - } |
| - f, err := os.CreateTemp(filepath.Dir(path), ".verify-*.tmp") |
| - if err != nil { |
| - return err |
| - } |
| - tmp := f.Name() |
| - _, err = f.Write(body) |
| - if err == nil { |
| - err = f.Chmod(0o644) |
| - } |
| - if err == nil { |
| - err = f.Sync() |
| - } |
| - if cerr := f.Close(); err == nil { |
| - err = cerr |
| - } |
| - if err == nil { |
| - err = os.Rename(tmp, path) |
| - } |
| - if err != nil { |
| - os.Remove(tmp) |
| - } |
| - return err |
| + return boxself.WriteFile(localVerifyPath(dataDir), body, dbverify.LocalMax) |
| } |
| // openDeployStore resolves the deployment bucket the same way the agent's |