gvisor demos: establish guest and host hardening contract (measured)
Pin the twelve host properties after arm64 root-runner 20261108T230205-7f89b9 passed run, probe, compiler-shaped build and trampoline checks. Prove read-only source and guest 32 MiB file limits. Embed byte-identical measured templates, retain the explicit TERM/SIGCONT stop recipe, and document append output with per-run probe nonces. Carry the saved nonce implementation and refreshed cumulative census proposal; independent review remains pending.
Co-Authored-By: Astra (gpt-6-astra) via codex
15 files changed,
+984
−70
docs/superpowers/notes/census-proposal-gvisor-demos.md+5 −2docs/superpowers/plans/2026-11-08-gvisor-demos.md+17 −6internal/execsandbox/hardening.go+32 −0internal/execsandbox/hardening_test.go+31 −0internal/host/gvisor_fixture_rootrunner_linux_test.go+587 −37internal/host/gvisor_hardening_rootrunner_linux_test.go+147 −16internal/host/host_test.go+3 −0internal/host/units/carlos-demo-build-gvisor@.service+43 −0internal/host/units/carlos-instance-gvisor-probe.service+42 −0internal/host/units/carlos-instance-gvisor@.service+38 −0internal/instancectl/names.go+1 −0internal/instanceexec/sandbox_linux.go+3 −1internal/instanceexec/sandbox_linux_test.go+21 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv+13 −7
CI failed — run details
Intent
diff --git a/docs/superpowers/notes/census-proposal-gvisor-demos.md b/docs/superpowers/notes/census-proposal-gvisor-demos.md| index 2063a3d5d..d54caa194 100644 |
| --- a/docs/superpowers/notes/census-proposal-gvisor-demos.md |
| +++ b/docs/superpowers/notes/census-proposal-gvisor-demos.md |
| @@ -1,6 +1,6 @@ |
| # Census approval: gvisor-demos |
| -Ruling `census-ruling-gvisor-demos`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-gvisor-demos`. The independent reviewer approves or rejects every change below, 7 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| @@ -41,8 +41,11 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/execsandbox/runsc.lock.json:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/host/execsandbox.go:sandboxExecGate`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen |
| - new `internal/host/execsandbox.go:sandboxRouteGate`: reads +registry:Runtime, +whole:Route ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/host/units/carlos-demo-build-gvisor@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| +- new `internal/host/units/carlos-instance-gvisor-probe.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| +- new `internal/host/units/carlos-instance-gvisor@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/instanceexec/sandbox_linux.go:gvisorProbeChecks`: reads +data-literal, +file:ReadFile; written legacy, accepted-legacy, frozen |
| -Seal: `b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c` → `fe0ca981cae7d649de4d5b30aec791b44914ed5770eb374dc91e7b7242406744`. |
| +Seal: `b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c` → `8c254ae5f1dc65f4a15b894f366c74dda7a147956d198e0281c76957f5970565`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-11-08-gvisor-demos.md b/docs/superpowers/plans/2026-11-08-gvisor-demos.md| index 4fde335c8..c353ab019 100644 |
| --- a/docs/superpowers/plans/2026-11-08-gvisor-demos.md |
| +++ b/docs/superpowers/plans/2026-11-08-gvisor-demos.md |
| @@ -181,6 +181,8 @@ Slice=carlos-instances-%i.slice |
| ExecStart= |
| Restart=no |
| KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| TimeoutStopSec=20 |
| SuccessExitStatus=129 130 141 143 |
| StandardOutput=file:/run/carlos/logs/%I.run.sock |
| @@ -209,9 +211,11 @@ Slice=carlos-instances.slice |
| ExecStart= |
| Restart=no |
| KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| RuntimeMaxSec=30 |
| TimeoutStopSec=20 |
| -StandardOutput=truncate:/run/carlos-control/gvisor-probe.out |
| +StandardOutput=append:/run/carlos-control/gvisor-probe.out |
| StandardError=journal |
| RuntimeDirectory=carlos-runsc |
| RuntimeDirectoryMode=0700 |
| @@ -253,7 +257,6 @@ MemorySwapMax=0 |
| TasksMax=192 |
| CPUQuota=50% |
| CPUWeight=10 |
| -LimitFSIZE=33554432 |
| UMask=0077 |
| StandardInput=null |
| StandardOutput=null |
| @@ -264,7 +267,7 @@ RuntimeDirectoryPreserve=yes |
| ReadWritePaths=/run/carlos-runsc |
| ``` |
| -Build's per-job drop-in adds its `work/out`, `work/tmp`, `work/home`, and mounted `work/cache` to ReadWritePaths, and carries the same lines as the native drop-in (unit.go:189): the `BindsTo=`/`After=` lines for the work and cache mounts (so the overlay cannot be unmounted under a running build), `StandardOutput=truncate:<work>/diagnostics` and `StandardError=inherit`. Systemd opens diagnostics before the namespace, and the worker parses that file; the template's `StandardOutput=null`/`StandardError=null` are only the defaults the drop-in overrides. `assertUnit` checks these lines. No `/work` host bind is needed: OCI mounts individual directories. |
| +Build's per-job drop-in adds its `work/out`, `work/tmp`, `work/home`, and mounted `work/cache` to ReadWritePaths, and carries the native drop-in's (unit.go:189) `BindsTo=`/`After=` lines for the work and cache mounts, so the overlay cannot be unmounted under a running build. It sets `StandardOutput=append:<work>/diagnostics` and `StandardError=inherit`. Systemd opens diagnostics before the namespace, and the worker parses that file; the template's `StandardOutput=null`/`StandardError=null` are only the defaults the drop-in overrides. `assertUnit` checks these lines. No `/work` host bind is needed: OCI mounts individual directories. |
| `carlos-runsc.service` (no extra measured block): |
| @@ -301,13 +304,21 @@ Command drop-in for a run uses `pinPath=RunscPath(pin)`, `iid=provision.Instance |
| ExecStartPre= |
| ExecStartPre=-<pinPath> --root=/run/carlos-runsc delete -force <id> |
| ExecStart= |
| -ExecStart=<pinPath> --root=/run/carlos-runsc --ignore-cgroups --network=none --host-uds=create run --bundle <bundle> <id> |
| +ExecStart=<pinPath> --root=/run/carlos-runsc --ignore-cgroups --network=none --host-uds=create --overlay2=none run --bundle <bundle> <id> |
| +ExecStop= |
| +ExecStop=-<pinPath> --root=/run/carlos-runsc kill <id> TERM |
| ExecStopPost= |
| ExecStopPost=/opt/carlos/carlos instance-exit --sandbox=gvisor run %I |
| ExecStopPost=-<pinPath> --root=/run/carlos-runsc delete -force <id> |
| ``` |
| -Angle-bracket words here are renderer substitutions, never shell expansion. The minus on delete tolerates an already-absent runtime; acceptance checks must still prove state cleanup, and failures cannot make a live ID reusable. Probe uses id `probe`, same command shape, and no instance-exit hook. Build uses id `build-<hex-job>_<attempt>`, same run/delete shape and no instance-exit hook. Assert the locked runtime's systrap default in Task 2, matching the spec's exact argv; do not introduce a configurable platform. |
| +Angle-bracket words here are renderer substitutions, never shell expansion. The minus on delete tolerates an already-absent runtime; acceptance checks must still prove state cleanup, and failures cannot make a live ID reusable. Probe uses id `probe`, same command shape, and no instance-exit hook. Build uses id `build-<hex-job>_<attempt>`, the same run/delete shape, no ExecStop and no instance-exit hook; it retains KillMode=control-group. Assert the locked runtime's systrap default in Task 2, matching the spec's exact argv; do not introduce a configurable platform. |
| + |
| +The run/probe kill command tolerates already-removed runtime state. Do not add `runsc wait`: the attached run owns waiting and state cleanup. `KillSignal=SIGCONT` lets it finish after the guest receives TERM; `KillMode=mixed` and the stop timeout retain the final cgroup kill. |
| + |
| +Before each probe or build start, root removes the exact output file without following symlinks. Both use append output so stop/delete commands cannot truncate the result. Root supplies a fresh probe challenge through the OCI environment variable `CARLOS_GVISOR_PROBE_NONCE`; the report carries it in `ProbeReport.Nonce` (`nonce` in JSON), and the consumer must reject missing or mismatched nonces and malformed JSON. This check does not replace the full readiness proof. |
| + |
| +The build template has no host LimitFSIZE because runsc uses a memory file larger than 32 MiB. Its guest OCI process keeps RLIMIT_FSIZE soft/hard 33554432. Task 2 measured successful runtime startup and a guest write beyond that limit returning EFBIG in run `20261108T230205-7f89b9`. |
| - [ ] **Step 5: Wire installation and awareness tests.** Bootstrap/apply create rootfs 0755 and `/opt/carlos/runsc` root-owned 0755; controller never creates rootfs. Add templates to bootstrap and missing-unit repair, keeping them unarmed until an explicit start. `TestRunscGarbageCollection` removes an old pin only after complete loaded-unit/job/installed-command inventory proves no ExecStart names it; enumeration failure retains it. Never prune a pin still referenced by a prepared drop-in or active sandbox. `TestExecSandboxProtocolReleaseBuild` is split. The ordinary half runs `go build -ldflags "-s -w"` (the Makefile's LDFLAGS; not `make build`, which writes `./carlos` and needs git) for linux/arm64 and linux/amd64 into `t.TempDir()`, requires protocol 1 from ScanProtocol on each, and skips only the builds under `testing.Short()`; the source scan above and duplicate/chunk-boundary/oversize cases still run in short mode. Use `-short` during targeted iteration, and record both architecture builds once as Task 3 evidence. `TestExecSandboxProtocolPreviousRelease` reads the unaware binary path from `CARLOS_EXEC_SANDBOX_PREVIOUS_RELEASE` and skips when unset. At implementation time, resolve and record the exact tag of the release immediately before this one (do not guess it), fetch its linux binary once, verify it against that release's signed SHA256SUMS, run the half against it (protocol 0) and record tag, hash and run as Task 3 evidence. Spec §7 needs both halves. Ordinary tests separately cover ReadProtocol's owner/link/symlink refusals; Task 9 exercises successful ReadProtocol on root-owned installed bytes. Non-root local builds are not passed off as root-owned files. Remove only generated outputs. |
| - [ ] **Step 6: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: install pinned runtime and guard recovery`. |
| @@ -413,7 +424,7 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| - [ ] **Step 1: Write `TestGVisorBuildBundle`, `TestGVisorBuildOwnership`, `TestGVisorBuildBudget`, `TestGVisorBuildRecoveryBothFamilies`, `TestGVisorBuildWindow`.** Require only intended guest mounts; directories out/tmp/home 65534:65534 0700; source/toolchain/backing dirs/lower files remain root-owned. Snapshot lower-layer file inode/bytes and upper-layer contents around ownership changes: no cache-file copy-up. For slots 1–4 assert parent MemoryMax=slots*1107296256, TasksMax=slots*192, CPUQuota=slots*50, swap=0. Assert signed deadline, transport, worker and unit all retain 180 seconds. Recovery stops both named families before any mount/bundle removal and retains work on failed proof. |
| - [ ] **Step 2: Run** `go test ./internal/demobuild ./internal/instancectl ./internal/host -run 'TestGVisorBuild|TestDemoBuild' -count=1`; expect failure, then implement family-aware prepareUnit/runUnit/assertUnit/cleanUnit/recover. Write bundle after source extraction and overlay mount. Change ownership on only out/tmp/home and mounted cache **directories** (directory mode 0700 owned by build uid), never recursively chown files or cache backing trees. Individual guest mounts prevent traversal to backing directories. |
| - [ ] **Step 3: Set guest process and mounts.** Argv is `/opt/carlos/demo-toolchain/bin/go build -mod=readonly -trimpath -buildvcs=false -o /work/out/app .`; cwd `/work/src`; environment exactly BuildEnvironment() plus GOMEMLIMIT=966367638. No inherited host env, loader variables or additional Go flags. OCI RLIMIT_FSIZE soft/hard=33554432, umask=0077. Toolchain including module cache and source are ro; `/work/out`, `/work/tmp`, `/work/home`, mounted `/work/cache` rw; guest proc/dev/tmp as Task 4, no host work root or backing dirs. Root-owned source archive parsing remains today's validated extraction, not a new launch-command source. |
| -- [ ] **Step 4: Verify unit/readback and recovery.** Build assertUnit consumes measured hardening and exact Task 3 command recipe; check Type=exec, RemainAfterExit, no DynamicUser, deadlines, limits, slice, byte-identical bundle, the `BindsTo`/`After` work and cache mount lines, and `StandardOutput=truncate:<work>/diagnostics` with `StandardError=inherit`. `TestGVisorBuildBundle` or a runner case asserts a compile error reaches the diagnostics file, with runsc's own stderr lines bounded and not mistaken for compiler output. Recover enumerates both families for each validated job attempt regardless of current mode, proves both stopped/empty and runtime delete complete, then unmounts overlay/work and removes bundle. Initialization failure keeps the worker closed while cleanup can retry. Build readiness probe uses the selected family and the real warm toolchain cache; never retry a failed gVisor compilation natively. |
| +- [ ] **Step 4: Verify unit/readback and recovery.** Build assertUnit consumes measured hardening and exact Task 3 command recipe; check Type=exec, RemainAfterExit, no DynamicUser, deadlines, limits, slice, byte-identical bundle, the `BindsTo`/`After` work and cache mount lines, and `StandardOutput=append:<work>/diagnostics` with `StandardError=inherit`. `TestGVisorBuildBundle` or a runner case asserts a compile error reaches the diagnostics file, with runsc's own stderr lines bounded and not mistaken for compiler output. Recover enumerates both families for each validated job attempt regardless of current mode, proves both stopped/empty and runtime delete complete, then unmounts overlay/work and removes bundle. Initialization failure keeps the worker closed while cleanup can retry. Build readiness probe uses the selected family and the real warm toolchain cache; never retry a failed gVisor compilation natively. |
| - [ ] **Step 5: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: build offline demos in pinned sandboxes`. |
| ### Task 8: Report actual sandbox identity and logical size |
diff --git a/internal/execsandbox/hardening.go b/internal/execsandbox/hardening.go| new file mode 100644 |
| index 000000000..b482a7a05 |
| --- /dev/null |
| +++ b/internal/execsandbox/hardening.go |
| @@ -0,0 +1,32 @@ |
| +package execsandbox |
| + |
| +import "strings" |
| + |
| +// Measured with run, probe and compiler-shaped guests in root-runner |
| +// 20261108T230205-7f89b9. These constrain the host runtime; guest caps stay zero. |
| +const gvisorHardeningLines = `ProtectSystem=strict |
| +ProtectHome=yes |
| +PrivateTmp=yes |
| +ProtectKernelTunables=yes |
| +ProtectKernelModules=yes |
| +ProtectKernelLogs=yes |
| +ProtectClock=yes |
| +ProtectHostname=yes |
| +ProtectControlGroups=yes |
| +LockPersonality=yes |
| +RestrictRealtime=yes |
| +SystemCallArchitectures=native |
| +` |
| + |
| +// GVisorHardening returns a fresh copy of the measured host-unit properties. |
| +func GVisorHardening() map[string]string { |
| + properties := make(map[string]string) |
| + for _, line := range strings.Split(strings.TrimSuffix(gvisorHardeningLines, "\n"), "\n") { |
| + name, value, _ := strings.Cut(line, "=") |
| + properties[name] = value |
| + } |
| + return properties |
| +} |
| + |
| +// GVisorHardeningLines returns the same properties in pinned template order. |
| +func GVisorHardeningLines() string { return gvisorHardeningLines } |
diff --git a/internal/execsandbox/hardening_test.go b/internal/execsandbox/hardening_test.go| new file mode 100644 |
| index 000000000..95a9a4dde |
| --- /dev/null |
| +++ b/internal/execsandbox/hardening_test.go |
| @@ -0,0 +1,31 @@ |
| +package execsandbox |
| + |
| +import ( |
| + "reflect" |
| + "testing" |
| +) |
| + |
| +func TestGVisorHardening(t *testing.T) { |
| + want := map[string]string{ |
| + "ProtectSystem": "strict", "ProtectHome": "yes", "PrivateTmp": "yes", |
| + "ProtectKernelTunables": "yes", "ProtectKernelModules": "yes", "ProtectKernelLogs": "yes", |
| + "ProtectClock": "yes", "ProtectHostname": "yes", "ProtectControlGroups": "yes", |
| + "LockPersonality": "yes", "RestrictRealtime": "yes", "SystemCallArchitectures": "native", |
| + } |
| + got := GVisorHardening() |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("hardening=%v, want %v", got, want) |
| + } |
| + got["ProtectSystem"] = "no" |
| + delete(got, "ProtectHome") |
| + got["Unmeasured"] = "yes" |
| + if !reflect.DeepEqual(GVisorHardening(), want) { |
| + t.Fatal("caller mutation changed the pinned contract") |
| + } |
| + const lines = "ProtectSystem=strict\nProtectHome=yes\nPrivateTmp=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectClock=yes\nProtectHostname=yes\nProtectControlGroups=yes\nLockPersonality=yes\nRestrictRealtime=yes\nSystemCallArchitectures=native\n" |
| + for range 3 { |
| + if got := GVisorHardeningLines(); got != lines { |
| + t.Fatalf("hardening lines=%q, want %q", got, lines) |
| + } |
| + } |
| +} |
diff --git a/internal/host/gvisor_fixture_rootrunner_linux_test.go b/internal/host/gvisor_fixture_rootrunner_linux_test.go| index 2c65cf808..583021f45 100644 |
| --- a/internal/host/gvisor_fixture_rootrunner_linux_test.go |
| +++ b/internal/host/gvisor_fixture_rootrunner_linux_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "archive/tar" |
| "bytes" |
| "context" |
| + "crypto/rand" |
| "crypto/sha256" |
| "crypto/sha512" |
| "encoding/hex" |
| @@ -45,6 +46,23 @@ func init() { |
| return |
| } |
| switch os.Args[1] { |
| + case "gvisor-test-exit-env": |
| + if len(os.Args) != 3 { |
| + os.Exit(75) |
| + } |
| + rec := instancectl.ExitRecord{Invocation: os.Getenv("INVOCATION_ID"), Result: os.Getenv("SERVICE_RESULT"), Code: os.Getenv("EXIT_CODE"), Status: os.Getenv("EXIT_STATUS")} |
| + file, err := os.OpenFile("/run/carlos-runsc/"+os.Args[2]+".exit-env.json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, err) |
| + os.Exit(75) |
| + } |
| + err = json.NewEncoder(file).Encode(rec) |
| + closeErr := file.Close() |
| + if err != nil || closeErr != nil { |
| + fmt.Fprintln(os.Stderr, err, closeErr) |
| + os.Exit(75) |
| + } |
| + os.Exit(0) |
| case "instance-exec": |
| instanceexec.RunExec(os.Args[2:]) |
| os.Exit(0) |
| @@ -76,6 +94,8 @@ type gvisorGuestEvidence struct { |
| Status string |
| MemoryLimit string |
| Limits unix.Rlimit |
| + FileSizeLimit unix.Rlimit |
| + FileSizeError string |
| Permitted, LeafRefused, ParentRefused, EscapeRefused bool |
| } |
| @@ -144,7 +164,7 @@ func gvisorGuestApp() error { |
| } |
| select { |
| case <-sigs: |
| - return nil |
| + return os.WriteFile("/data/instances/"+gvisorFixtureHost+"/graceful", []byte("SIGTERM"), 0600) |
| case <-time.After(15 * time.Second): |
| return errors.New("guest stop timeout") |
| } |
| @@ -160,9 +180,12 @@ func gvisorCompilerApp() error { |
| if string(b) != "fixture source" { |
| return errors.New("unexpected source") |
| } |
| - if err := os.WriteFile("/work/src/forbidden", nil, 0600); !errors.Is(err, syscall.EROFS) { |
| + if err := os.WriteFile("/work/src/write-canary", []byte("changed"), 0666); !errors.Is(err, syscall.EROFS) { |
| return fmt.Errorf("source write: %v", err) |
| } |
| + if b, err := os.ReadFile("/work/src/write-canary"); err != nil || string(b) != "unchanged source canary" { |
| + return fmt.Errorf("source canary changed: %q %v", b, err) |
| + } |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| if err := exec.CommandContext(ctx, "/opt/carlos/app", "gvisor-test-child").Run(); err != nil { |
| @@ -179,6 +202,29 @@ func gvisorCompilerApp() error { |
| if err != nil { |
| return err |
| } |
| + if err := unix.Getrlimit(unix.RLIMIT_FSIZE, &e.FileSizeLimit); err != nil { |
| + return err |
| + } |
| + if e.FileSizeLimit.Cur != 33554432 || e.FileSizeLimit.Max != 33554432 { |
| + return fmt.Errorf("guest file-size limit: %+v", e.FileSizeLimit) |
| + } |
| + // Ignore only the accompanying signal so the witness can record EFBIG. |
| + signal.Ignore(syscall.SIGXFSZ) |
| + defer signal.Reset(syscall.SIGXFSZ) |
| + boundary, err := os.OpenFile("/work/out/file-size-boundary", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| + if err != nil { |
| + return err |
| + } |
| + defer boundary.Close() |
| + defer os.Remove("/work/out/file-size-boundary") |
| + if n, err := boundary.WriteAt([]byte{1}, 33554431); n != 1 || err != nil { |
| + return fmt.Errorf("write at file-size limit: n=%d err=%v", n, err) |
| + } |
| + if n, err := boundary.WriteAt([]byte{1}, 33554432); n != 0 || !errors.Is(err, syscall.EFBIG) { |
| + return fmt.Errorf("write beyond file-size limit: n=%d err=%v", n, err) |
| + } |
| + e.FileSizeError = "EFBIG" |
| + fmt.Fprintln(os.Stderr, "guest file-size boundary: 33554432 bytes allowed; extension refused with EFBIG") |
| raw, err := json.Marshal(e) |
| if err != nil { |
| return err |
| @@ -188,12 +234,13 @@ func gvisorCompilerApp() error { |
| } |
| type gvisorFixture struct { |
| - t *testing.T |
| - uid, gid int |
| - runtime string |
| - rootStat unix.Stat_t |
| - nofile unix.Rlimit |
| - serial int |
| + t *testing.T |
| + uid, gid int |
| + runtime string |
| + skeletons map[string]string |
| + nofile unix.Rlimit |
| + serial int |
| + probeNonce string |
| } |
| func gvisorCommand(timeout time.Duration, name string, args ...string) (string, error) { |
| @@ -207,6 +254,7 @@ func gvisorCommand(timeout time.Duration, name string, args ...string) (string, |
| func newGVisorFixture(t *testing.T) *gvisorFixture { |
| t.Helper() |
| + checkGVisorMeasuredTemplates(t) |
| if os.Geteuid() != 0 { |
| t.Fatal("root is required") |
| } |
| @@ -216,7 +264,7 @@ func newGVisorFixture(t *testing.T) *gvisorFixture { |
| if _, err := os.Stat("/sys/fs/cgroup/cgroup.controllers"); err != nil { |
| t.Fatalf("cgroup v2 required: %v", err) |
| } |
| - f := &gvisorFixture{t: t} |
| + f := &gvisorFixture{t: t, skeletons: map[string]string{}} |
| slice, err := gvisorCommand(5*time.Second, "systemctl", "show", "carlos-gvisor-fixture.slice", "--property=ActiveState", "--property=ControlGroup", "--property=FragmentPath") |
| sliceProperties := gvisorProperties(slice) |
| if err != nil || sliceProperties["ActiveState"] != "inactive" || sliceProperties["ControlGroup"] != "" || sliceProperties["FragmentPath"] != "" { |
| @@ -348,7 +396,23 @@ func newGVisorFixture(t *testing.T) *gvisorFixture { |
| if err := os.WriteFile("/var/lib/carlos/work/src/input", []byte("fixture source"), 0444); err != nil { |
| t.Fatal(err) |
| } |
| - if err := unix.Stat(gvisorFixtureRootfs, &f.rootStat); err != nil { |
| + // DAC permits this fixture-only write; only the read-only source mount |
| + // should refuse it. The production source permissions are not changed. |
| + canary := "/var/lib/carlos/work/src/write-canary" |
| + if err := os.WriteFile(canary, []byte("unchanged source canary"), 0666); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(canary, 0666); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + b, err := os.ReadFile(canary) |
| + var st unix.Stat_t |
| + if err != nil || string(b) != "unchanged source canary" || unix.Lstat(canary, &st) != nil || st.Uid != 0 || st.Gid != 0 || st.Mode != unix.S_IFREG|0666 || st.Nlink != 1 { |
| + t.Errorf("source canary contents/metadata changed: %q %+v %v", b, st, err) |
| + } |
| + }) |
| + if err := os.Chmod(gvisorFixtureRootfs, 0700); err != nil { |
| t.Fatal(err) |
| } |
| t.Cleanup(f.assertRootfs) |
| @@ -398,18 +462,46 @@ func (f *gvisorFixture) writeJSON(path string, v any, mode os.FileMode) { |
| func (f *gvisorFixture) assertRootfs() { |
| f.t.Helper() |
| - entries, err := os.ReadDir(gvisorFixtureRootfs) |
| - if err != nil || len(entries) != 0 { |
| - f.t.Errorf("rootfs changed: %v %v", entries, err) |
| - } |
| - var st unix.Stat_t |
| - if err := unix.Stat(gvisorFixtureRootfs, &st); err != nil { |
| - f.t.Error(err) |
| - return |
| + for path, before := range f.skeletons { |
| + after, err := gvisorSkeletonDigest(path) |
| + f.t.Logf("skeleton %s before=%s after=%s", filepath.Base(path), before, after) |
| + if err != nil || before != after { |
| + f.t.Errorf("rootfs skeleton changed: %s: %v", path, err) |
| + } |
| } |
| - if st.Uid != 0 || st.Gid != 0 || st.Mode&0777 != 0755 || st.Ino != f.rootStat.Ino || st.Dev != f.rootStat.Dev || st.Mtim != f.rootStat.Mtim || st.Ctim != f.rootStat.Ctim { |
| - f.t.Errorf("rootfs identity changed: before=%+v after=%+v", f.rootStat, st) |
| +} |
| + |
| +func gvisorSkeletonDigest(root string) (string, error) { |
| + hash := sha256.New() |
| + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + var st unix.Stat_t |
| + if err := unix.Lstat(path, &st); err != nil { |
| + return err |
| + } |
| + if st.Uid != 0 || st.Gid != 0 { |
| + return fmt.Errorf("skeleton owner: %s", path) |
| + } |
| + if entry.IsDir() { |
| + if st.Mode != unix.S_IFDIR|0755 { |
| + return fmt.Errorf("skeleton directory mode: %s", path) |
| + } |
| + } else if st.Mode != unix.S_IFREG|0444 || st.Size != 0 || st.Nlink != 1 { |
| + return fmt.Errorf("skeleton file metadata: %s", path) |
| + } |
| + rel, err := filepath.Rel(root, path) |
| + if err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(hash, "%s\t%o\t%d:%d\t%d\n", rel, st.Mode, st.Uid, st.Gid, st.Size) |
| + return nil |
| + }) |
| + if err != nil { |
| + return "", err |
| } |
| + return hex.EncodeToString(hash.Sum(nil)), nil |
| } |
| func (f *gvisorFixture) fetchRunsc() string { |
| @@ -548,12 +640,44 @@ func (f *gvisorFixture) bundle(kind, id string) string { |
| iid = "_probe" |
| cwd = "/data/instances/_probe" |
| args = []string{"/opt/carlos/carlos", "instance-probe", "--sandbox=gvisor"} |
| + var nonce [32]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.probeNonce = hex.EncodeToString(nonce[:]) |
| + env = append(env, "CARLOS_GVISOR_PROBE_NONCE="+f.probeNonce) |
| } |
| if kind == "build" { |
| args = []string{"/opt/carlos/app", "gvisor-test-compiler"} |
| cwd = "/work/src" |
| env = []string{"GOMEMLIMIT=966367638"} |
| } |
| + mounts, rootfs := f.mountsAndSkeleton(kind, iid, id) |
| + caps := map[string]any{} |
| + for _, k := range []string{"bounding", "effective", "inheritable", "permitted", "ambient"} { |
| + caps[k] = []string{} |
| + } |
| + ns := []map[string]string{} |
| + for _, typ := range []string{"pid", "ipc", "uts", "mount", "network"} { |
| + ns = append(ns, map[string]string{"type": typ}) |
| + } |
| + rlimits := []map[string]any{{"type": "RLIMIT_NOFILE", "soft": f.nofile.Cur, "hard": f.nofile.Max}} |
| + user := map[string]any{"uid": f.uid, "gid": f.gid, "additionalGids": []int{}} |
| + if kind == "build" { |
| + user["umask"] = 63 |
| + rlimits = append(rlimits, map[string]any{"type": "RLIMIT_FSIZE", "soft": 33554432, "hard": 33554432}) |
| + } |
| + config := map[string]any{"ociVersion": "1.0.2", "root": map[string]any{"path": rootfs, "readonly": true}, "process": map[string]any{"terminal": false, "user": user, "args": args, "env": env, "cwd": cwd, "capabilities": caps, "noNewPrivileges": true, "rlimits": rlimits}, "mounts": mounts, "linux": map[string]any{"namespaces": ns}} |
| + path := execsandbox.BundleDir(id) |
| + if err := os.Mkdir(path, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.writeJSON(filepath.Join(path, "config.json"), config, 0600) |
| + return path |
| +} |
| + |
| +func (f *gvisorFixture) mountsAndSkeleton(kind, iid, id string) ([]map[string]any, string) { |
| + f.t.Helper() |
| mount := func(dst, typ, src string, opts ...string) map[string]any { |
| return map[string]any{"destination": dst, "type": typ, "source": src, "options": opts} |
| } |
| @@ -580,25 +704,451 @@ func (f *gvisorFixture) bundle(kind, id string) string { |
| mounts = append(mounts, mount(root+iid, "bind", root+iid, "bind", "rw", "nosuid", "nodev")) |
| } |
| } |
| - caps := map[string]any{} |
| - for _, k := range []string{"bounding", "effective", "inheritable", "permitted", "ambient"} { |
| - caps[k] = []string{} |
| + |
| + root := filepath.Join(gvisorFixtureRootfs, id) |
| + if err := os.Mkdir(root, 0755); err != nil { |
| + f.t.Fatal(err) |
| } |
| - ns := []map[string]string{} |
| - for _, typ := range []string{"pid", "ipc", "uts", "mount", "network"} { |
| - ns = append(ns, map[string]string{"type": typ}) |
| + for _, mount := range mounts { |
| + target := mount["destination"].(string) |
| + path := filepath.Join(root, target) |
| + file := target == "/opt/carlos/carlos" || target == "/opt/carlos/app" |
| + if file { |
| + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + h, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0444) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := h.Close(); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + } else if err := os.MkdirAll(path, 0755); err != nil { |
| + f.t.Fatal(err) |
| + } |
| } |
| - rlimits := []map[string]any{{"type": "RLIMIT_NOFILE", "soft": f.nofile.Cur, "hard": f.nofile.Max}} |
| - user := map[string]any{"uid": f.uid, "gid": f.gid, "additionalGids": []int{}} |
| - if kind == "build" { |
| - user["umask"] = 63 |
| - rlimits = append(rlimits, map[string]any{"type": "RLIMIT_FSIZE", "soft": 33554432, "hard": 33554432}) |
| + digest, err := gvisorSkeletonDigest(root) |
| + if err != nil { |
| + f.t.Fatal(err) |
| } |
| - config := map[string]any{"ociVersion": "1.0.2", "root": map[string]any{"path": gvisorFixtureRootfs, "readonly": true}, "process": map[string]any{"terminal": false, "user": user, "args": args, "env": env, "cwd": cwd, "capabilities": caps, "noNewPrivileges": true, "rlimits": rlimits}, "mounts": mounts, "linux": map[string]any{"namespaces": ns}} |
| - path := execsandbox.BundleDir(id) |
| - if err := os.Mkdir(path, 0700); err != nil { |
| - t.Fatal(err) |
| + f.skeletons[root] = digest |
| + return mounts, root |
| +} |
| + |
| +// The controller authorized this diagnostic matrix in task-2-resume2.md. |
| +// Runtime flags and candidate omissions here are test-only experiments. |
| +type gvisorBisectVariant struct { |
| + name, hardening, overlay string |
| +} |
| + |
| +type gvisorBisectResult struct { |
| + variant gvisorBisectVariant |
| + passed bool |
| + elapsed time.Duration |
| + failure string |
| + diagnostics []string |
| +} |
| + |
| +func TestRootGVisorHardeningBisect(t *testing.T) { |
| + f := newGVisorFixture(t) |
| + variants := []gvisorBisectVariant{{name: "all", hardening: gvisorCandidateHardening}} |
| + var results []gvisorBisectResult |
| + defer func() { |
| + // Deduplicate full debug lines so the result row fit the runner's stdout cap. |
| + messages := []string{} |
| + index := map[string]int{} |
| + t.Log("BISECT_TABLE_BEGIN\nvariant | overlay | result | elapsed_ms | evidence") |
| + for _, r := range results { |
| + refs := []string{} |
| + evidence := append([]string(nil), r.diagnostics...) |
| + if r.failure != "" { |
| + evidence = append(evidence, "witness: "+r.failure) |
| + } |
| + for _, message := range evidence { |
| + id, ok := index[message] |
| + if !ok { |
| + id = len(messages) + 1 |
| + messages = append(messages, message) |
| + index[message] = id |
| + } |
| + refs = append(refs, fmt.Sprintf("E%02d", id)) |
| + } |
| + verdict := "FAIL" |
| + if r.passed { |
| + verdict = "PASS" |
| + } |
| + t.Logf("BISECT_ROW %s | %s | %s | %d | %s", r.variant.name, r.variant.overlay, verdict, r.elapsed.Milliseconds(), strings.Join(refs, ",")) |
| + } |
| + for i, message := range messages { |
| + t.Logf("BISECT_EVIDENCE E%02d %s", i+1, message) |
| + } |
| + t.Log("BISECT_TABLE_END") |
| + }() |
| + deadline := time.Now().Add(20 * time.Minute) |
| + anyPass := false |
| + for _, variant := range variants { |
| + for _, overlay := range []string{"none"} { |
| + if time.Now().After(deadline) { |
| + t.Fatal("bounded bisection deadline exceeded") |
| + } |
| + variant.overlay = overlay |
| + result, err := f.bisectVariant(variant, len(results)+1) |
| + results = append(results, result) |
| + if err != nil { |
| + t.Fatalf("bisection infrastructure/cleanup: %v", err) |
| + } |
| + if result.passed { |
| + anyPass = true |
| + } |
| + } |
| } |
| - f.writeJSON(filepath.Join(path, "config.json"), config, 0600) |
| - return path |
| + if !anyPass { |
| + t.Fatal("no configuration passed; stop BLOCKED") |
| + } |
| +} |
| + |
| +func (f *gvisorFixture) bisectVariant(v gvisorBisectVariant, number int) (result gvisorBisectResult, infrastructureErr error) { |
| + result.variant = v |
| + started := time.Now() |
| + defer func() { |
| + result.elapsed = time.Since(started) |
| + if infrastructureErr != nil { |
| + result.passed = false |
| + result.failure += "; cleanup: " + infrastructureErr.Error() |
| + } |
| + }() |
| + id := fmt.Sprintf("bisect-run-%02d", number) |
| + unit := "carlos-gvisor-" + id + ".service" |
| + path := "/run/systemd/system/" + unit |
| + bundle := f.bundle("run", id) |
| + logDir := "/run/carlos-runsc/bisect-logs/" + id |
| + if err := os.MkdirAll(filepath.Dir(logDir), 0700); err != nil { |
| + return result, err |
| + } |
| + if err := os.Mkdir(logDir, 0700); err != nil { |
| + return result, err |
| + } |
| + load, err := gvisorCommand(5*time.Second, "systemctl", "show", unit, "--property=LoadState", "--value") |
| + if err != nil || strings.TrimSpace(load) != "not-found" { |
| + return result, fmt.Errorf("refuse preexisting unit %s: %s %v", unit, load, err) |
| + } |
| + var lines []string |
| + for _, line := range strings.Split(gvisorRunSkeleton, "\n") { |
| + if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| + continue |
| + } |
| + if strings.HasPrefix(line, "Slice=") { |
| + line = "Slice=carlos-gvisor-fixture.slice" |
| + } |
| + if strings.HasPrefix(line, "StandardOutput=") { |
| + line = "StandardOutput=journal" |
| + } |
| + line = strings.ReplaceAll(line, "%I", gvisorFixtureHost) |
| + line = strings.ReplaceAll(line, "%i", gvisorFixtureHost) |
| + lines = append(lines, line) |
| + } |
| + debugFlags := " --debug --debug-log=" + logDir + "/ --debug-log-format=text" |
| + debugFlags += " --overlay2=" + v.overlay |
| + body := strings.Join(lines, "\n") + "\n" + v.hardening + |
| + "ExecStartPre=-" + f.runtime + " --root=/run/carlos-runsc delete -force " + id + "\n" + |
| + "ExecStart=" + f.runtime + " --root=/run/carlos-runsc --ignore-cgroups --network=none --host-uds=create" + debugFlags + " run --bundle " + bundle + " " + id + "\n" + |
| + "ExecStop=-" + f.runtime + " --root=/run/carlos-runsc kill " + id + " TERM\n" + |
| + "ExecStopPost=/opt/carlos/carlos gvisor-test-exit-env " + id + "\n" + |
| + "ExecStopPost=/opt/carlos/carlos instance-exit --sandbox=gvisor run " + gvisorFixtureHost + "\n" + |
| + "ExecStopPost=-" + f.runtime + " --root=/run/carlos-runsc delete -force " + id + "\n" |
| + file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| + if err != nil { |
| + return result, err |
| + } |
| + _, err = file.WriteString(body) |
| + closeErr := file.Close() |
| + var invocation, cgroup string |
| + defer func() { |
| + // Stop-post owns runtime deletion, even on a failed startup. No variant |
| + // begins until this unit, its cgroup and its runtime ID are proved gone. |
| + out, err := gvisorCommand(30*time.Second, "systemctl", "stop", unit) |
| + if err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, fmt.Errorf("stop %s: %s %w", unit, out, err)) |
| + return |
| + } |
| + props, err := gvisorCommand(5*time.Second, "systemctl", "show", unit, "--property=ActiveState", "--property=Result", "--property=ExecMainStatus") |
| + values := gvisorProperties(props) |
| + if err != nil || (values["ActiveState"] != "inactive" && values["ActiveState"] != "failed") { |
| + infrastructureErr = errors.Join(infrastructureErr, fmt.Errorf("unsettled unit: %s %v", props, err)) |
| + return |
| + } |
| + if cgroup != "" { |
| + err := filepath.WalkDir(filepath.Join("/sys/fs/cgroup", cgroup), func(p string, d os.DirEntry, err error) error { |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if d.Name() == "cgroup.procs" { |
| + b, err := os.ReadFile(p) |
| + if err != nil { |
| + return err |
| + } |
| + if len(strings.TrimSpace(string(b))) != 0 { |
| + return fmt.Errorf("populated cgroup %s", p) |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + return |
| + } |
| + } |
| + runtimeList, err := gvisorCommand(5*time.Second, f.runtime, "--root=/run/carlos-runsc", "list", "--format=json") |
| + var states []struct { |
| + ID string `json:"id"` |
| + } |
| + if err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, fmt.Errorf("runtime list: %s %w", runtimeList, err)) |
| + return |
| + } |
| + if err := json.Unmarshal([]byte(runtimeList), &states); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + return |
| + } |
| + for _, s := range states { |
| + if s.ID == id { |
| + infrastructureErr = errors.Join(infrastructureErr, fmt.Errorf("runtime %s survived stop-post", id)) |
| + return |
| + } |
| + } |
| + if result.passed { |
| + if values["Result"] != "success" || values["ActiveState"] != "inactive" { |
| + result.passed = false |
| + result.failure = "unclean graceful stop: " + strings.TrimSpace(props) |
| + } |
| + recordPath := "/run/carlos/instances/" + gvisorFixtureHost + "/" + instancectl.ExitRecordName(instancectl.RoleRun, invocation) |
| + raw, err := os.ReadFile(recordPath) |
| + var rec instancectl.ExitRecord |
| + var st unix.Stat_t |
| + expected, expectedErr := gvisorExitEnvironment(id) |
| + graceful, gracefulErr := os.ReadFile("/data/instances/" + gvisorFixtureHost + "/graceful") |
| + if err != nil || json.Unmarshal(raw, &rec) != nil || expectedErr != nil || !gvisorSameExit(rec, expected) || rec.Invocation != invocation || rec.Result != "success" || unix.Stat(recordPath, &st) != nil || st.Uid != uint32(f.uid) || st.Gid != uint32(f.gid) || st.Mode&0777 != 0600 || gracefulErr != nil || string(graceful) != "SIGTERM" { |
| + result.passed = false |
| + result.failure = fmt.Sprintf("exit record contract: %s %v", raw, err) |
| + } |
| + } |
| + root := filepath.Join(gvisorFixtureRootfs, id) |
| + before := f.skeletons[root] |
| + after, err := gvisorSkeletonDigest(root) |
| + f.t.Logf("BISECT_SKELETON %s/%s before=%s after=%s", v.name, v.overlay, before, after) |
| + if err != nil || before != after { |
| + result.passed = false |
| + result.failure += fmt.Sprintf("; rootfs skeleton changed: %v", err) |
| + } |
| + result.diagnostics = f.bisectDebugErrors(logDir) |
| + if !result.passed && len(result.diagnostics) == 0 { |
| + journal, _ := gvisorCommand(5*time.Second, "journalctl", "-u", unit, "--no-pager", "-o", "cat", "-n", "12") |
| + for _, line := range strings.Split(journal, "\n") { |
| + if strings.Contains(line, "instance-exec:") || strings.Contains(line, "running container:") { |
| + result.diagnostics = append(result.diagnostics, "journal: "+line) |
| + break |
| + } |
| + } |
| + } |
| + if err := os.Remove(path); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + if out, err := gvisorCommand(5*time.Second, "systemctl", "daemon-reload"); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, fmt.Errorf("reload: %s %w", out, err)) |
| + } |
| + gvisorCommand(5*time.Second, "systemctl", "reset-failed", unit) |
| + for _, p := range []string{bundle, logDir, root, "/run/carlos-runsc/" + id + ".exit-env.json", "/data/instances/" + gvisorFixtureHost, "/run/carlos/instances/" + gvisorFixtureHost} { |
| + if err := os.RemoveAll(p); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + } |
| + // Only fixture data is reset after the unit, cgroup and runtime ID are gone. |
| + delete(f.skeletons, root) |
| + for _, p := range []string{"/data/instances/" + gvisorFixtureHost, "/run/carlos/instances/" + gvisorFixtureHost} { |
| + if err := os.Mkdir(p, 0755); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + if p != gvisorFixtureRootfs { |
| + if err := os.Chown(p, f.uid, f.gid); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + if err := os.Chmod(p, 0700); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + } |
| + } |
| + launch := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: gvisorFixtureHost, Argv: []string{instanceexec.LiveDir + "/" + gvisorFixtureHost, "gvisor-test-app"}, Env: []string{"GOMEMLIMIT=1", "GOMEMLIMIT=off"}} |
| + raw, err := json.Marshal(launch) |
| + if err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + return |
| + } |
| + lp := "/data/instances/" + gvisorFixtureHost + "/launch.run.json" |
| + if err := os.WriteFile(lp, raw, 0600); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + if err := os.Chown(lp, f.uid, f.gid); err != nil { |
| + infrastructureErr = errors.Join(infrastructureErr, err) |
| + } |
| + }() |
| + if err != nil || closeErr != nil { |
| + return result, errors.Join(err, closeErr) |
| + } |
| + if out, err := gvisorCommand(5*time.Second, "systemctl", "daemon-reload"); err != nil { |
| + return result, fmt.Errorf("reload: %s %w", out, err) |
| + } |
| + if out, err := gvisorCommand(20*time.Second, "systemctl", "start", unit); err != nil { |
| + result.failure = "start: " + strings.TrimSpace(out) |
| + return result, nil |
| + } |
| + props, err := gvisorCommand(5*time.Second, "systemctl", "show", unit, "--property=InvocationID", "--property=ControlGroup") |
| + if err != nil { |
| + return result, err |
| + } |
| + values := gvisorProperties(props) |
| + invocation = values["InvocationID"] |
| + cgroup = values["ControlGroup"] |
| + if v.hardening != "" { |
| + args := []string{"show", unit} |
| + for name := range gvisorProperties(v.hardening) { |
| + args = append(args, "--property="+name) |
| + } |
| + effective, err := gvisorCommand(5*time.Second, "systemctl", args...) |
| + if err != nil { |
| + return result, err |
| + } |
| + for name, want := range gvisorProperties(v.hardening) { |
| + if gvisorProperties(effective)[name] != want { |
| + result.failure = "effective property mismatch: " + name |
| + return result, nil |
| + } |
| + } |
| + } |
| + deadline := time.Now().Add(10 * time.Second) |
| + for time.Now().Before(deadline) { |
| + conn, err := net.DialTimeout("unix", "/run/carlos/instances/"+gvisorFixtureHost+"/app.sock", 200*time.Millisecond) |
| + if err == nil { |
| + conn.SetDeadline(time.Now().Add(3 * time.Second)) |
| + var e gvisorGuestEvidence |
| + err = json.NewDecoder(conn).Decode(&e) |
| + conn.Close() |
| + if err != nil { |
| + result.failure = "guest evidence: " + err.Error() |
| + return result, nil |
| + } |
| + if e.UID != f.uid || e.GID != f.gid || e.PPID != 1 || e.PID == 1 || e.MemoryLimit != "241591905" || (e.Limits.Max != f.nofile.Max || e.Limits.Cur < f.nofile.Cur) || !e.Permitted || !e.LeafRefused || !e.ParentRefused || !e.EscapeRefused { |
| + result.failure = fmt.Sprintf("guest contract uid=%d gid=%d pid=%d ppid=%d memory=%s limits=%+v opens=%v/%v/%v/%v", e.UID, e.GID, e.PID, e.PPID, e.MemoryLimit, e.Limits, e.Permitted, e.LeafRefused, e.ParentRefused, e.EscapeRefused) |
| + return result, nil |
| + } |
| + status := map[string]string{} |
| + for _, line := range strings.Split(e.Status, "\n") { |
| + k, v, _ := strings.Cut(line, ":") |
| + status[k] = strings.TrimSpace(v) |
| + } |
| + for _, key := range []string{"CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"} { |
| + if status[key] != "0000000000000000" { |
| + result.failure = "guest " + key + "=" + status[key] |
| + return result, nil |
| + } |
| + } |
| + if status["NoNewPrivs"] != "1" { |
| + result.failure = "guest NoNewPrivs=" + status["NoNewPrivs"] |
| + return result, nil |
| + } |
| + f.t.Logf("BISECT_NOFILE %s/%s native=%d/%d guest=%d/%d", v.name, v.overlay, f.nofile.Cur, f.nofile.Max, e.Limits.Cur, e.Limits.Max) |
| + result.passed = true |
| + return result, nil |
| + } |
| + state, err := gvisorCommand(2*time.Second, "systemctl", "show", unit, "--property=ActiveState", "--value") |
| + if err != nil { |
| + return result, err |
| + } |
| + if strings.TrimSpace(state) != "active" && strings.TrimSpace(state) != "activating" { |
| + result.failure = "runtime exited before guest socket" |
| + return result, nil |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + result.failure = "guest socket timeout" |
| + return result, nil |
| +} |
| + |
| +func (f *gvisorFixture) bisectDebugErrors(dir string) []string { |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + return []string{"debug-log read: " + err.Error()} |
| + } |
| + var errorsFound []string |
| + for _, entry := range entries { |
| + if !entry.Type().IsRegular() { |
| + continue |
| + } |
| + h, err := os.Open(filepath.Join(dir, entry.Name())) |
| + if err != nil { |
| + errorsFound = append(errorsFound, "debug-log open: "+err.Error()) |
| + continue |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(h, 4<<20)) |
| + h.Close() |
| + if err != nil { |
| + errorsFound = append(errorsFound, "debug-log read: "+err.Error()) |
| + continue |
| + } |
| + first := "" |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + // Go's text logger starts fatal/error records with F/E plus MMDD. |
| + strong := len(line) > 5 && (line[0] == 'F' || line[0] == 'E') && line[1] >= '0' && line[1] <= '9' |
| + lower := strings.ToLower(line) |
| + if strong || strings.Contains(lower, "panic:") || strings.Contains(lower, "fatal error:") { |
| + first = line |
| + break |
| + } |
| + } |
| + if first == "" { |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + lower := strings.ToLower(line) |
| + if strings.Contains(lower, "failed") || strings.Contains(lower, "error:") { |
| + first = line |
| + break |
| + } |
| + } |
| + } |
| + if first != "" { |
| + // Keep the component and source location, remove only variable logger |
| + // timestamp/thread prefixes so repeated evidence shares one table key. |
| + if split := strings.Index(first, "] "); split >= 0 { |
| + prefix := strings.Fields(first[:split]) |
| + if len(prefix) > 0 { |
| + first = prefix[len(prefix)-1] + "] " + first[split+2:] |
| + } |
| + } |
| + component := "runsc" |
| + for _, name := range []string{"gofer", "boot", "sentry"} { |
| + if strings.Contains(entry.Name(), name) { |
| + component = name |
| + break |
| + } |
| + } |
| + errorsFound = append(errorsFound, component+": "+first) |
| + } |
| + } |
| + return errorsFound |
| +} |
| + |
| +func gvisorExitEnvironment(id string) (instancectl.ExitRecord, error) { |
| + var rec instancectl.ExitRecord |
| + raw, err := os.ReadFile("/run/carlos-runsc/" + id + ".exit-env.json") |
| + if err != nil { |
| + return rec, err |
| + } |
| + err = json.Unmarshal(raw, &rec) |
| + return rec, err |
| +} |
| + |
| +func gvisorSameExit(got, want instancectl.ExitRecord) bool { |
| + return got.Invocation == want.Invocation && got.Result == want.Result && got.Code == want.Code && got.Status == want.Status |
| } |
diff --git a/internal/host/gvisor_hardening_rootrunner_linux_test.go b/internal/host/gvisor_hardening_rootrunner_linux_test.go| index aeca1b18a..f587cfde8 100644 |
| --- a/internal/host/gvisor_hardening_rootrunner_linux_test.go |
| +++ b/internal/host/gvisor_hardening_rootrunner_linux_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "net" |
| "os" |
| "path/filepath" |
| @@ -14,12 +15,13 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "golang.org/x/sys/unix" |
| ) |
| -// Measurement candidates only. Promote to execsandbox's pinned contract and |
| -// embedded templates only after the real trampoline passes on the root runner. |
| +// Preserve the exact measurement input. The template comparison below requires |
| +// the shipped units and pinned properties to match these tested bytes. |
| const gvisorCandidateHardening = `ProtectSystem=strict |
| ProtectHome=yes |
| PrivateTmp=yes |
| @@ -52,6 +54,27 @@ func TestRootGVisorHardening(t *testing.T) { |
| } |
| } |
| +func TestGVisorMeasuredTemplates(t *testing.T) { |
| + checkGVisorMeasuredTemplates(t) |
| +} |
| + |
| +func checkGVisorMeasuredTemplates(t *testing.T) { |
| + t.Helper() |
| + if execsandbox.GVisorHardeningLines() != gvisorCandidateHardening { |
| + t.Fatal("pinned hardening differs from measured candidates") |
| + } |
| + for name, skeleton := range map[string]string{ |
| + "carlos-instance-gvisor@.service": gvisorRunSkeleton, |
| + "carlos-instance-gvisor-probe.service": gvisorProbeSkeleton, |
| + "carlos-demo-build-gvisor@.service": gvisorBuildSkeleton, |
| + } { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + if err != nil || string(raw) != skeleton+execsandbox.GVisorHardeningLines() { |
| + t.Errorf("%s differs from the measured skeleton and hardening: %v", name, err) |
| + } |
| + } |
| +} |
| + |
| func TestRootGVisorTrampoline(t *testing.T) { |
| f := newGVisorFixture(t) |
| unit := f.start("run") |
| @@ -95,15 +118,35 @@ func (f *gvisorFixture) start(kind string) string { |
| } |
| lines = append(lines, line) |
| } |
| - // The fixture substitutes only deployment dependencies, slice and log sink. |
| - // All candidate hardening, limits and the runsc recipe stay as specified. |
| - body := strings.Join(lines, "\n") + "\n" + gvisorCandidateHardening + "\nExecStartPre=-" + f.runtime + " --root=/run/carlos-runsc delete -force " + id + "\nExecStart=" + f.runtime + " --root=/run/carlos-runsc --ignore-cgroups --network=none --host-uds=create run --bundle " + bundle + " " + id + "\n" |
| + // Test-only substitutions cover deployment dependencies, slice, log sink, |
| + // and the independent exit-environment witness. R-T2b selects overlay none. |
| + debugFlags := "" |
| + if kind == "build" { |
| + logDir := "/run/carlos-runsc/build-logs-" + id |
| + if err := os.Mkdir(logDir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + debugFlags = " --debug --debug-log=" + logDir + "/ --debug-log-format=text" |
| + } |
| + body := strings.Join(lines, "\n") + "\n" + gvisorCandidateHardening + "\nExecStartPre=-" + f.runtime + " --root=/run/carlos-runsc delete -force " + id + "\nExecStart=" + f.runtime + " --root=/run/carlos-runsc --ignore-cgroups --network=none --host-uds=create --overlay2=none" + debugFlags + " run --bundle " + bundle + " " + id + "\n" |
| + if kind != "build" { |
| + body += "ExecStop=-" + f.runtime + " --root=/run/carlos-runsc kill " + id + " TERM\n" |
| + } |
| if kind == "run" { |
| + body += "ExecStopPost=/opt/carlos/carlos gvisor-test-exit-env " + id + "\n" |
| body += "ExecStopPost=/opt/carlos/carlos instance-exit --sandbox=gvisor run " + gvisorFixtureHost + "\n" |
| } |
| body += "ExecStopPost=-" + f.runtime + " --root=/run/carlos-runsc delete -force " + id + "\n" |
| if kind == "build" { |
| - body += "ReadWritePaths=/var/lib/carlos/work/out /var/lib/carlos/work/tmp /var/lib/carlos/work/home /var/lib/carlos/work/cache\nStandardOutput=truncate:/var/lib/carlos/work/diagnostics\nStandardError=inherit\n" |
| + body += "ReadWritePaths=/var/lib/carlos/work/out /var/lib/carlos/work/tmp /var/lib/carlos/work/home /var/lib/carlos/work/cache\nStandardOutput=append:/var/lib/carlos/work/diagnostics\nStandardError=inherit\n" |
| + } |
| + // Ancestors belong exclusively to this root fixture. Unlink never follows |
| + // the leaf, so stale output cannot survive into this invocation. |
| + output := map[string]string{"probe": "/run/carlos-control/gvisor-probe.out", "build": "/var/lib/carlos/work/diagnostics"}[kind] |
| + if output != "" { |
| + if err := unix.Unlink(output); err != nil && !errors.Is(err, unix.ENOENT) { |
| + t.Fatal(err) |
| + } |
| } |
| h, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| if err != nil { |
| @@ -143,7 +186,7 @@ func (f *gvisorFixture) checkHardening(unit string) { |
| t := f.t |
| t.Helper() |
| args := []string{"show", unit, "--property=LimitNOFILE", "--property=LimitNOFILESoft"} |
| - for name := range gvisorProperties(gvisorCandidateHardening) { |
| + for name := range execsandbox.GVisorHardening() { |
| args = append(args, "--property="+name) |
| } |
| out, err := gvisorCommand(5*time.Second, "systemctl", args...) |
| @@ -152,11 +195,13 @@ func (f *gvisorFixture) checkHardening(unit string) { |
| } |
| t.Logf("effective %s:\n%s", unit, out) |
| props := gvisorProperties(out) |
| - for name, want := range gvisorProperties(gvisorCandidateHardening) { |
| + for name, want := range execsandbox.GVisorHardening() { |
| got := props[name] |
| // systemctl exposes these bool settings as yes/no; there is no generic |
| // truthiness conversion that could hide a weaker setting. |
| - if got != want { |
| + // Explicit systemctl readback normalization measured on this runner. |
| + wire := map[string]string{"yes": "yes", "strict": "strict", "native": "native"}[want] |
| + if wire == "" || got != wire { |
| t.Errorf("%s=%q, candidate=%q", name, got, want) |
| } |
| } |
| @@ -167,6 +212,44 @@ func (f *gvisorFixture) checkHardening(unit string) { |
| func (f *gvisorFixture) diagnostics(unit string) { |
| f.t.Helper() |
| + if strings.Contains(unit, "fixture-build-") { |
| + id := strings.TrimSuffix(strings.TrimPrefix(unit, "carlos-gvisor-"), ".service") |
| + logDir := "/run/carlos-runsc/build-logs-" + id |
| + for _, message := range f.bisectDebugErrors(logDir) { |
| + f.t.Logf("build runsc debug error: %s", message) |
| + } |
| + entries, err := os.ReadDir(logDir) |
| + if err != nil { |
| + f.t.Logf("build runsc debug directory: %v", err) |
| + } |
| + for i, entry := range entries { |
| + if i >= 8 { |
| + break |
| + } |
| + if !entry.Type().IsRegular() { |
| + continue |
| + } |
| + h, err := os.Open(filepath.Join(logDir, entry.Name())) |
| + if err != nil { |
| + f.t.Logf("build runsc debug open: %v", err) |
| + continue |
| + } |
| + if st, err := h.Stat(); err == nil && st.Size() > 16<<10 { |
| + h.Seek(-16<<10, io.SeekEnd) |
| + } |
| + b, readErr := io.ReadAll(io.LimitReader(h, 16<<10)) |
| + h.Close() |
| + f.t.Logf("build runsc debug %s (last 16 KiB):\n%s\nread error: %v", entry.Name(), b, readErr) |
| + } |
| + h, err := os.Open("/var/lib/carlos/work/diagnostics") |
| + if err != nil { |
| + f.t.Logf("build diagnostics: %v", err) |
| + } else { |
| + b, readErr := io.ReadAll(io.LimitReader(h, 64<<10)) |
| + h.Close() |
| + f.t.Logf("build diagnostics (first 64 KiB):\n%s\nread error: %v", b, readErr) |
| + } |
| + } |
| out, _ := gvisorCommand(5*time.Second, "systemctl", "show", unit, "--property=ActiveState", "--property=SubState", "--property=Result", "--property=ExecMainStatus", "--property=InvocationID") |
| f.t.Log(out) |
| out, _ = gvisorCommand(5*time.Second, "journalctl", "-u", unit, "--no-pager", "-n", "35") |
| @@ -215,8 +298,8 @@ func (f *gvisorFixture) exercise(kind, unit string) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - var report instancectl.ProbeReport |
| - if err := json.Unmarshal(raw, &report); err != nil { |
| + report, err := gvisorProbeReport(raw, f.probeNonce) |
| + if err != nil { |
| t.Fatalf("probe output %q: %v", raw, err) |
| } |
| found := map[string]bool{} |
| @@ -249,6 +332,9 @@ func (f *gvisorFixture) exercise(kind, unit string) { |
| t.Fatal(err) |
| } |
| f.checkGuest(e, false, "966367638") |
| + if e.FileSizeLimit.Cur != 33554432 || e.FileSizeLimit.Max != 33554432 || e.FileSizeError != "EFBIG" { |
| + t.Fatalf("guest file-size boundary: limit=%+v error=%q", e.FileSizeLimit, e.FileSizeError) |
| + } |
| diagnostics, err := os.ReadFile("/var/lib/carlos/work/diagnostics") |
| if err != nil || !strings.Contains(string(diagnostics), "compiler-shaped diagnostics") { |
| t.Fatalf("compiler diagnostics: %q %v", diagnostics, err) |
| @@ -282,7 +368,7 @@ func (f *gvisorFixture) checkGuest(e gvisorGuestEvidence, child bool, limit stri |
| if props["NoNewPrivs"] != "1" { |
| t.Errorf("guest NoNewPrivs=%q", props["NoNewPrivs"]) |
| } |
| - if e.Limits != f.nofile { |
| + if e.Limits.Max != f.nofile.Max || e.Limits.Cur < f.nofile.Cur { |
| t.Errorf("guest NOFILE=%+v native=%+v", e.Limits, f.nofile) |
| } |
| if !e.Permitted || !e.LeafRefused || !e.ParentRefused || !e.EscapeRefused { |
| @@ -290,6 +376,35 @@ func (f *gvisorFixture) checkGuest(e gvisorGuestEvidence, child bool, limit stri |
| } |
| } |
| +func gvisorProbeReport(raw []byte, nonce string) (instancectl.ProbeReport, error) { |
| + var report instancectl.ProbeReport |
| + if err := json.Unmarshal(raw, &report); err != nil { |
| + return report, err |
| + } |
| + if nonce == "" || report.Nonce != nonce { |
| + return report, errors.New("probe nonce mismatch") |
| + } |
| + return report, nil |
| +} |
| + |
| +func TestGVisorProbeReportNonce(t *testing.T) { |
| + for _, tc := range []struct { |
| + raw, nonce string |
| + ok bool |
| + }{ |
| + {`{"nonce":"fresh","ready":false}`, "fresh", true}, |
| + {`{"nonce":"stale"}`, "fresh", false}, |
| + {`{}`, "fresh", false}, |
| + {`{}`, "", false}, |
| + {`{"nonce":"fresh"} {"nonce":"fresh"}`, "fresh", false}, |
| + {`{"nonce":`, "fresh", false}, |
| + } { |
| + if _, err := gvisorProbeReport([]byte(tc.raw), tc.nonce); (err == nil) != tc.ok { |
| + t.Errorf("report=%q nonce=%q: %v", tc.raw, tc.nonce, err) |
| + } |
| + } |
| +} |
| + |
| func (f *gvisorFixture) waitFinished(unit string, remain bool) { |
| t := f.t |
| t.Helper() |
| @@ -327,7 +442,10 @@ func (f *gvisorFixture) stop(unit string) { |
| if out, err := gvisorCommand(30*time.Second, "systemctl", "stop", unit); err != nil { |
| t.Fatalf("stop: %s %v", out, err) |
| } |
| - f.waitFinished(unit, false) |
| + after, err := gvisorCommand(5*time.Second, "systemctl", "show", unit, "--property=ActiveState", "--property=Result") |
| + if err != nil || gvisorProperties(after)["ActiveState"] != "inactive" || gvisorProperties(after)["Result"] != "success" { |
| + t.Fatalf("stop result: %s %v", after, err) |
| + } |
| if cg := p["ControlGroup"]; cg != "" { |
| err := filepath.WalkDir(filepath.Join("/sys/fs/cgroup", cg), func(path string, d os.DirEntry, err error) error { |
| if errors.Is(err, os.ErrNotExist) { |
| @@ -361,7 +479,12 @@ func (f *gvisorFixture) stop(unit string) { |
| if err := json.Unmarshal(raw, &rec); err != nil { |
| t.Fatal(err) |
| } |
| - if rec.Invocation != p["InvocationID"] || rec.Result != "success" || rec.Status != "0" { |
| + id := strings.TrimSuffix(strings.TrimPrefix(unit, "carlos-gvisor-"), ".service") |
| + expected, err := gvisorExitEnvironment(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Invocation != p["InvocationID"] || rec.Result != "success" || !gvisorSameExit(rec, expected) { |
| t.Fatalf("exit hook record: %s", raw) |
| } |
| var st unix.Stat_t |
| @@ -371,6 +494,11 @@ func (f *gvisorFixture) stop(unit string) { |
| if st.Uid != uint32(f.uid) || st.Gid != uint32(f.gid) || st.Mode&0777 != 0600 { |
| t.Fatalf("exit owner/mode: %+v", st) |
| } |
| + graceful, err := os.ReadFile("/data/instances/" + gvisorFixtureHost + "/graceful") |
| + if err != nil || string(graceful) != "SIGTERM" { |
| + t.Fatalf("guest SIGTERM receipt: %q %v", graceful, err) |
| + } |
| + t.Logf("exit record matched hook environment: code=%s status=%s", rec.Code, rec.Status) |
| var keys map[string]any |
| json.Unmarshal(raw, &keys) |
| if _, ok := keys["kind"]; ok { |
| @@ -392,6 +520,8 @@ Slice=carlos-instances-%i.slice |
| ExecStart= |
| Restart=no |
| KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| TimeoutStopSec=20 |
| SuccessExitStatus=129 130 141 143 |
| StandardOutput=file:/run/carlos/logs/%I.run.sock |
| @@ -417,9 +547,11 @@ Slice=carlos-instances.slice |
| ExecStart= |
| Restart=no |
| KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| RuntimeMaxSec=30 |
| TimeoutStopSec=20 |
| -StandardOutput=truncate:/run/carlos-control/gvisor-probe.out |
| +StandardOutput=append:/run/carlos-control/gvisor-probe.out |
| StandardError=journal |
| RuntimeDirectory=carlos-runsc |
| RuntimeDirectoryMode=0700 |
| @@ -458,7 +590,6 @@ MemorySwapMax=0 |
| TasksMax=192 |
| CPUQuota=50% |
| CPUWeight=10 |
| -LimitFSIZE=33554432 |
| UMask=0077 |
| StandardInput=null |
| StandardOutput=null |
diff --git a/internal/host/host_test.go b/internal/host/host_test.go| index 733ad7c54..dfa263c87 100644 |
| --- a/internal/host/host_test.go |
| +++ b/internal/host/host_test.go |
| @@ -40,6 +40,7 @@ var expectedUnits = []string{ |
| "carlos-config-sync.service", |
| "carlos-dbread.socket", |
| "carlos-dbread@.service", |
| + "carlos-demo-build-gvisor@.service", |
| "carlos-demo-build@.service", |
| "carlos-demo-builds.slice", |
| "carlos-demo-snapshot@.service", |
| @@ -50,6 +51,8 @@ var expectedUnits = []string{ |
| "carlos-instance-control.service", |
| "carlos-instance-control.socket", |
| "carlos-instance-gen@.service", |
| + "carlos-instance-gvisor-probe.service", |
| + "carlos-instance-gvisor@.service", |
| "carlos-instance-probe.service", |
| "carlos-instance-rootfs-cmd@.service", |
| "carlos-instance-rootfs-gen@.service", |
diff --git a/internal/host/units/carlos-demo-build-gvisor@.service b/internal/host/units/carlos-demo-build-gvisor@.service| new file mode 100644 |
| index 000000000..94f013e96 |
| --- /dev/null |
| +++ b/internal/host/units/carlos-demo-build-gvisor@.service |
| @@ -0,0 +1,43 @@ |
| +[Unit] |
| +Description=carlos gVisor offline demo build |
| +BindsTo=carlos-instance-control.service |
| +After=carlos-instance-control.service |
| +[Service] |
| +Type=exec |
| +RemainAfterExit=yes |
| +User=root |
| +Group=root |
| +Slice=carlos-demo-builds.slice |
| +ExecStart= |
| +Restart=no |
| +KillMode=control-group |
| +RuntimeMaxSec=180 |
| +TimeoutStopSec=5 |
| +SendSIGKILL=yes |
| +OOMPolicy=kill |
| +MemoryMax=1107296256 |
| +MemoryHigh=996566625 |
| +MemorySwapMax=0 |
| +TasksMax=192 |
| +CPUQuota=50% |
| +CPUWeight=10 |
| +UMask=0077 |
| +StandardInput=null |
| +StandardOutput=null |
| +StandardError=null |
| +RuntimeDirectory=carlos-runsc |
| +RuntimeDirectoryMode=0700 |
| +RuntimeDirectoryPreserve=yes |
| +ReadWritePaths=/run/carlos-runsc |
| +ProtectSystem=strict |
| +ProtectHome=yes |
| +PrivateTmp=yes |
| +ProtectKernelTunables=yes |
| +ProtectKernelModules=yes |
| +ProtectKernelLogs=yes |
| +ProtectClock=yes |
| +ProtectHostname=yes |
| +ProtectControlGroups=yes |
| +LockPersonality=yes |
| +RestrictRealtime=yes |
| +SystemCallArchitectures=native |
diff --git a/internal/host/units/carlos-instance-gvisor-probe.service b/internal/host/units/carlos-instance-gvisor-probe.service| new file mode 100644 |
| index 000000000..a92b484c7 |
| --- /dev/null |
| +++ b/internal/host/units/carlos-instance-gvisor-probe.service |
| @@ -0,0 +1,42 @@ |
| +[Unit] |
| +Description=carlos gVisor instance probe |
| +Requires=data-instances.mount run-carlos-instances.mount |
| +After=data-instances.mount run-carlos-instances.mount |
| +[Service] |
| +Type=exec |
| +User=root |
| +Group=root |
| +Slice=carlos-instances.slice |
| +ExecStart= |
| +Restart=no |
| +KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| +RuntimeMaxSec=30 |
| +TimeoutStopSec=20 |
| +StandardOutput=append:/run/carlos-control/gvisor-probe.out |
| +StandardError=journal |
| +RuntimeDirectory=carlos-runsc |
| +RuntimeDirectoryMode=0700 |
| +RuntimeDirectoryPreserve=yes |
| +ReadWritePaths=/run/carlos-runsc /data/instances/_probe /run/carlos/instances/_probe |
| +MemoryMax=301989888 |
| +MemoryHigh=271790892 |
| +MemorySwapMax=301989888 |
| +TasksMax=320 |
| +CPUQuota=50% |
| +CPUWeight=50 |
| +IOWeight=50 |
| +OOMPolicy=kill |
| +ProtectSystem=strict |
| +ProtectHome=yes |
| +PrivateTmp=yes |
| +ProtectKernelTunables=yes |
| +ProtectKernelModules=yes |
| +ProtectKernelLogs=yes |
| +ProtectClock=yes |
| +ProtectHostname=yes |
| +ProtectControlGroups=yes |
| +LockPersonality=yes |
| +RestrictRealtime=yes |
| +SystemCallArchitectures=native |
diff --git a/internal/host/units/carlos-instance-gvisor@.service b/internal/host/units/carlos-instance-gvisor@.service| new file mode 100644 |
| index 000000000..9a760bf57 |
| --- /dev/null |
| +++ b/internal/host/units/carlos-instance-gvisor@.service |
| @@ -0,0 +1,38 @@ |
| +[Unit] |
| +Description=carlos gVisor demo instance %I |
| +BindsTo=carlos-edge.service |
| +Requires=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount |
| +After=carlos-edge.service data-instances.mount run-carlos-instances.mount run-carlos-logs.mount |
| +[Service] |
| +Type=exec |
| +User=root |
| +Group=root |
| +Slice=carlos-instances-%i.slice |
| +ExecStart= |
| +Restart=no |
| +KillMode=mixed |
| +# Let attached runsc wait for the guest after ExecStop sends TERM to guest init. |
| +KillSignal=SIGCONT |
| +TimeoutStopSec=20 |
| +SuccessExitStatus=129 130 141 143 |
| +StandardOutput=file:/run/carlos/logs/%I.run.sock |
| +StandardError=inherit |
| +RuntimeDirectory=carlos-runsc |
| +RuntimeDirectoryMode=0700 |
| +RuntimeDirectoryPreserve=yes |
| +ReadWritePaths=/run/carlos-runsc /data/instances/%I /run/carlos/instances/%I |
| +TasksMax=320 |
| +OOMScoreAdjust=500 |
| +OOMPolicy=kill |
| +ProtectSystem=strict |
| +ProtectHome=yes |
| +PrivateTmp=yes |
| +ProtectKernelTunables=yes |
| +ProtectKernelModules=yes |
| +ProtectKernelLogs=yes |
| +ProtectClock=yes |
| +ProtectHostname=yes |
| +ProtectControlGroups=yes |
| +LockPersonality=yes |
| +RestrictRealtime=yes |
| +SystemCallArchitectures=native |
diff --git a/internal/instancectl/names.go b/internal/instancectl/names.go| index 9c0403bb2..39d77a4d2 100644 |
| --- a/internal/instancectl/names.go |
| +++ b/internal/instancectl/names.go |
| @@ -645,6 +645,7 @@ type VerdictLine struct { |
| type ProbeReport struct { |
| Ready bool `json:"ready"` |
| Lines []VerdictLine `json:"lines"` |
| + Nonce string `json:"nonce,omitempty"` |
| } |
| // BuildHeader carries the control service's version.Build on every /ready |
diff --git a/internal/instanceexec/sandbox_linux.go b/internal/instanceexec/sandbox_linux.go| index 5e30f81e0..9cbc055d4 100644 |
| --- a/internal/instanceexec/sandbox_linux.go |
| +++ b/internal/instanceexec/sandbox_linux.go |
| @@ -63,5 +63,7 @@ func gvisorProbeChecks() instancectl.ProbeReport { |
| // Task 6 supplies the root challenges and full network/runtime proof. |
| // This early measurement must not advertise readiness to production. |
| v.add("gvisor-readiness", "fail", "gVisor readiness proof is incomplete") |
| - return v.report() |
| + report := v.report() |
| + report.Nonce = os.Getenv("CARLOS_GVISOR_PROBE_NONCE") |
| + return report |
| } |
diff --git a/internal/instanceexec/sandbox_linux_test.go b/internal/instanceexec/sandbox_linux_test.go| index 839535a44..590047878 100644 |
| --- a/internal/instanceexec/sandbox_linux_test.go |
| +++ b/internal/instanceexec/sandbox_linux_test.go |
| @@ -19,6 +19,27 @@ import ( |
| "golang.org/x/sys/unix" |
| ) |
| +func TestGVisorProbeNonce(t *testing.T) { |
| + for _, nonce := range []string{"", "root-challenge-one", "root-challenge-two"} { |
| + t.Setenv("CARLOS_GVISOR_PROBE_NONCE", nonce) |
| + raw, err := json.Marshal(gvisorProbeChecks()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var report map[string]any |
| + if err := json.Unmarshal(raw, &report); err != nil { |
| + t.Fatal(err) |
| + } |
| + if nonce == "" { |
| + if _, ok := report["nonce"]; ok { |
| + t.Fatal("empty nonce changed legacy report shape") |
| + } |
| + } else if report["nonce"] != nonce { |
| + t.Fatalf("nonce=%v, want %q", report["nonce"], nonce) |
| + } |
| + } |
| +} |
| + |
| func TestGVisorLaunchValidation(t *testing.T) { |
| const host = "gvisor.example.com" |
| for _, flags := range [][]string{ |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index a8ce2bca2..114ce60c8 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -128,4 +128,4 @@ plan14-root-reads-fix-activator-backoff-flake.tsv feba66806ddfcbdfaf369d72413bb1 |
| plan14-root-reads-region-ha-dr5.tsv f19eb78c1da1475cbf8e11a3d6c394d828aa1c8f88ae24469fe8d473581b934b |
| plan14-root-reads-instance-syscall-filter.tsv b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c |
| plan14-root-reads-instance-restore-658-cli.tsv b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c |
| -plan14-root-reads-gvisor-demos.tsv fe0ca981cae7d649de4d5b30aec791b44914ed5770eb374dc91e7b7242406744 |
| +plan14-root-reads-gvisor-demos.tsv 8c254ae5f1dc65f4a15b894f366c74dda7a147956d198e0281c76957f5970565 |
diff --git a/internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv b/internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv| index 0444dc92d..7d8de0576 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-gvisor-demos.tsv |
| @@ -1,6 +1,6 @@ |
| # Census overlay gvisor-demos, written by census-propose (#369). census-ruling-gvisor-demos, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-gvisor-demos.md. |
| # 12 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -# 4 new dispositions: 0 reads re-frozen at their disposition with the claim, 4 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +# 7 new dispositions: 0 reads re-frozen at their disposition with the claim, 7 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy 53142bae4c3f2ad8444ecd148a1e5389cf059e60e80b0366056a6f7dce33997b internal/host/bootstrap.go bootstrapWithGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move bootstrapWith body here, retaining host.env, embedded unit reads and tmpfiles execution. Group live caller holds root mutation guard; skip automatic update/recovery units, preserve Restart=no/nftables drop-in and masks, and write separate root-owned /run/carlos-group-maintenance tmpfiles rule outside service ownership walk. No agent receipt read.;rev3=census-ruling-gvisor-demos;basis=Use the distinct claim/demo rendering marker, with historic state-directory recognition, for the 6b-N2 keep-installed decision; ordinary units are repaired on malformed host.env. Existing reads unchanged. file:Command@11946,file:ReadFile@564,file:ReadFile@7000 3cb60d7cb52e0e04a5ed690938acd5376f38e8275bf92624610f05bd3f6b41ab |
| @legacy 30cbb184502cda61320987fa438776a839eee01c610185e050779ae82eeed822 internal/host/systemapply.go systemApplier.installUnits legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-agent-start-demo-1;basis=Renders the staged build slice against live root host configuration; preserves it when settings cannot be parsed.;rev3=census-ruling-region-ha-p3b;basis=Require group apply/rollback permit, preserve root Restart=no/nftables drop-in and masks, and skip automatic update/recovery units. Existing staged unit and host.env reads remain; new indirect marker/permit reads are protected and agent receipts are excluded.;rev3=census-ruling-gvisor-demos;basis=Use claim/demo rendering evidence instead of the now-common EnvironmentFile line to preserve installed control on settings errors. Ordinary control stays flag-off and does not gain automatic restarts. Existing reads unchanged. file:ReadDir@1409,file:ReadFile@2000,file:ReadFile@5035,file:ReadFile@960,file:Stat@2658,file:Stat@3951 957f210b9c50169a414cc99ddf5ddae35a804e7c2ff734fe755e85bf3388087a |
| @legacy 16c52a77d87551d9536e381991f55ea95e527b1d647d5d58ff2f1797c0e1b971 internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Use claim/demo rendering evidence for repair/restart selection and 6b-N2 preservation. Ordinary environment loading does not classify a box as claims-enabled. Existing reads unchanged. file:OpenFile@293,file:ReadFile@4702,file:ReadFile@4835,file:ReadFile@6239,file:Stat@4611 123236f110db2d69dc2f425944485e52ba12fede7be07d07f7db0d08987f4f61 |
| @@ -11,7 +11,10 @@ |
| @legacy 39b3f98c010e512816b6964fd4de98193a850564e68021119a888e6a97f7befa internal/execsandbox/runsc.lock.json external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Extend the embedded release-20261102.0 pin to exactly the five R-T2 executable members on each Linux platform. Archive SHA512 was verified before extracting the named regular members; freeze each SHA256. Top-level SHA256 still equals runsc. No external runtime read. file:external@0 3a24ba581a95bc8fd8283984b5501f0002daff003e2d8fe90571e150ba15b617 |
| @legacy ee7a88073c08baf804220709c6e2d7778d7d277054f413be0443d2ac431643ef internal/host/execsandbox.go sandboxExecGate legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Read the existing registry route through injected lookup only for gVisor; require the same route admission before BeforeExec. No new path; lookup is the existing registry handle. whole:Route@493,whole:Route@587 e66292565a6718b38622cfbd0747888356fb66fca161d782399067a0db23a1f5 |
| @legacy 8d2537e489c6d9c5782c1548a3cdabe421f20a9d4eae4b71d008d089c071a43c internal/host/execsandbox.go sandboxRouteGate legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Read existing route layout, demo marker and runtime to refuse unsupported or direct gVisor launches before the next config gate. No new path; layout inputs are the backend's existing ones. registry:Runtime@700,whole:Route@432,whole:Route@802 6d3b45864d6e551a523e37dbec39f6d7befd414d02ce6751531ac312c7ec1d67 |
| -@legacy 3c1078f0c5d2242857e988d8047b8036e7c09c603443508ddb2520232da88e4a internal/instanceexec/sandbox_linux.go gvisorProbeChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Preliminary guest-only probe reads the fixed /proc/self/status to check empty capability sets and NoNewPrivs, and SelfCheck opens the fixed own /data/instances/_probe directory with unchanged safe-open flags. Runs as the guest carlos identity; reports readiness incomplete until the later root challenges exist. No tenant-selected host path or root authority is added. data-literal@696,file:ReadFile@202 825a550d5d62da0d0b322c480fa2a4a1027de35f04ac274b5f5c7eb1bbc072a2 |
| +@legacy 7ce6741a7508b1a64de66d58ea342ff1ac4f4093c73a94e8e211949a574fca23 internal/host/units/carlos-demo-build-gvisor@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor build skeleton with empty ExecStart, all twelve measured properties, control-group termination and fixed physical budgets. Host LimitFSIZE is omitted by ruling; guest OCI limit remains 33554432 and passed EFBIG measurement. Root prepares validated per-job writable paths, append diagnostics and runtime commands later; template output defaults remain null. file:external@0 8b6f939424c554aaf1e5ed38111ebd0bf67fdcbaaa5bc6415df55affb64ba17a |
| +@legacy 1cb2a2b1f667f42c1b24eb4997c20b5ecc00a9571d92060dedfada948e8a0f5d internal/host/units/carlos-instance-gvisor-probe.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor probe skeleton with empty ExecStart, all twelve measured properties, fixed probe data/run paths, append output and mixed kill with SIGCONT. Root command preparation must reset output and bind a fresh nonce before start; full readiness consumer remains a later task. file:external@0 b05d264190ef2172e87e5b2667164f2051e83016695595e32ccbcdce9186eb6b |
| +@legacy 4de04c1583d5fa335adadb7227f9ce1ec35e28280744d6571ebe92c72b4442f2 internal/host/units/carlos-instance-gvisor@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor run skeleton with empty ExecStart and all twelve measured host properties. Defines per-instance data/run writable paths and socket output, root runtime directory, mixed kill with SIGCONT, and the existing bounded stop. A root-prepared validated command drop-in is required before it can start; no command or pin placeholder is installed here. file:external@0 914a3c0486d83b6b87ce14c473aab9005ff7bc004cb984040a81ddc60087a5c1 |
| +@legacy 6c407dd1a2b848bef09894cb174b933331bbc0b2c8147e7e533b41c9f6bb7464 internal/instanceexec/sandbox_linux.go gvisorProbeChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Preliminary guest-only probe reads the fixed /proc/self/status to check empty capability sets and NoNewPrivs, and SelfCheck opens the fixed own /data/instances/_probe directory with unchanged safe-open flags. Runs as the guest carlos identity; reports readiness incomplete until the later root challenges exist. No tenant-selected host path or root authority is added. Echo CARLOS_GVISOR_PROBE_NONCE from the initial guest environment in the additive omitempty report field; root supplies the challenge in the OCI environment. No new filesystem read or readiness grant. data-literal@696,file:ReadFile@202 b201174cac395aea50cbe7c306859c47a120d1a954d988a43e9746a1386f658a |
| internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. file:Exec@19431,file:Open@1837,file:Statfs@50774,registry:App@12933,registry:Host@46810,whole:Route@12925,whole:Route@45968,whole:Route@46933,whole:Route@46995 c618605dd17ada0fb0b53b3c4d2176fd737c4f44b38a25298fbc1c48bae9fa0e |
| internal/host/bootstrap.go bootstrapWithGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move bootstrapWith body here, retaining host.env, embedded unit reads and tmpfiles execution. Group live caller holds root mutation guard; skip automatic update/recovery units, preserve Restart=no/nftables drop-in and masks, and write separate root-owned /run/carlos-group-maintenance tmpfiles rule outside service ownership walk. No agent receipt read.;rev3=census-ruling-gvisor-demos;basis=Use the distinct claim/demo rendering marker, with historic state-directory recognition, for the 6b-N2 keep-installed decision; ordinary units are repaired on malformed host.env. Existing reads unchanged. file:Command@11946,file:ReadFile@564,file:ReadFile@7000 3cb60d7cb52e0e04a5ed690938acd5376f38e8275bf92624610f05bd3f6b41ab |
| internal/host/claimstop_run.go RunInstanceControl authority C,D,G rev3=PROPOSED-p3;run=24;identity=root claim/adopt/update controller uid 0;basis=production root startup builds authenticated execution and launch handlers then uses activateClaimRoot for recovery, the registered census launch verifier and lifecycle start;rev3=census-ruling-rootfs-apps-2;basis=the claims-off path serves through instancectl.RunWithRegistryView with HostRuntime: instanceRegistryHostRuntime beside the same instanceRegistryHostApp(nil); the new read is instanceRegistryHostRuntime's own (a decision row in rootfs-apps-2-new); no read added in this body;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 4 and 6: the claims-off branch hands RunWithRegistryView the pre-claim egress asserter (newEgressAsserter over registryEgressSource and registryEgressHosts, which read the agent-written registry read-only, beside the instanceRegistryHostApp read it already had); the claims branch builds its runtime resources in instanceControlClaimResources, adding the claims asserter (claimsEgressSource writes no allow; the registry is read only to name slices), and serves through runClaimControl, which passes RunWithClaim the same handler, held-release route and host lookup plus that asserter. No read site in the unit, none added.;rev3=census-ruling-agent-start-demo-1;basis=Wires demo registry views and existing root release/adoption guard into instance control.;rev3=census-ruling-region-ha-p3b;basis=Add root hairpin identity verification, dormant install and reset CLI entries with bounded contexts. Indirect inputs are root-owned marker/identity/ingress/state and kernel/systemd process evidence; no request-controlled addresses or executable path. Existing control-service path remains.;rev3=census-ruling-gvisor-demos;basis=Resolve sandbox once through shared Configure; select claim protocol independently of sandbox refusal and retain claim stop/recovery, activation and host-fence pass. Relax demo-plus-claims fatal only for ErrClaims. Keep egress asserter and install its restart-only refusal before claim recovery. No new root read. 8defd30b08522508edaf87978bf7e7a70ff48fc0aef71a63a702231f387f0efb |
| @@ -27,9 +30,12 @@ internal/instancectl/server.go type Server legacy accepted-legacy accepted-legac |
| internal/execsandbox/runsc.lock.json external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Extend the embedded release-20261102.0 pin to exactly the five R-T2 executable members on each Linux platform. Archive SHA512 was verified before extracting the named regular members; freeze each SHA256. Top-level SHA256 still equals runsc. No external runtime read. file:external@0 3a24ba581a95bc8fd8283984b5501f0002daff003e2d8fe90571e150ba15b617 |
| internal/host/execsandbox.go sandboxExecGate legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Read the existing registry route through injected lookup only for gVisor; require the same route admission before BeforeExec. No new path; lookup is the existing registry handle. whole:Route@493,whole:Route@587 e66292565a6718b38622cfbd0747888356fb66fca161d782399067a0db23a1f5 |
| internal/host/execsandbox.go sandboxRouteGate legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Read existing route layout, demo marker and runtime to refuse unsupported or direct gVisor launches before the next config gate. No new path; layout inputs are the backend's existing ones. registry:Runtime@700,whole:Route@432,whole:Route@802 6d3b45864d6e551a523e37dbec39f6d7befd414d02ce6751531ac312c7ec1d67 |
| -internal/instanceexec/sandbox_linux.go gvisorProbeChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Preliminary guest-only probe reads the fixed /proc/self/status to check empty capability sets and NoNewPrivs, and SelfCheck opens the fixed own /data/instances/_probe directory with unchanged safe-open flags. Runs as the guest carlos identity; reports readiness incomplete until the later root challenges exist. No tenant-selected host path or root authority is added. data-literal@696,file:ReadFile@202 825a550d5d62da0d0b322c480fa2a4a1027de35f04ac274b5f5c7eb1bbc072a2 |
| -@coverage internal/execsandbox c3a67170cb13dda0369dd20029d2bc0be845843d2d84843dae270fe828013c01 |
| +internal/host/units/carlos-demo-build-gvisor@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor build skeleton with empty ExecStart, all twelve measured properties, control-group termination and fixed physical budgets. Host LimitFSIZE is omitted by ruling; guest OCI limit remains 33554432 and passed EFBIG measurement. Root prepares validated per-job writable paths, append diagnostics and runtime commands later; template output defaults remain null. file:external@0 8b6f939424c554aaf1e5ed38111ebd0bf67fdcbaaa5bc6415df55affb64ba17a |
| +internal/host/units/carlos-instance-gvisor-probe.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor probe skeleton with empty ExecStart, all twelve measured properties, fixed probe data/run paths, append output and mixed kill with SIGCONT. Root command preparation must reset output and bind a fresh nonce before start; full readiness consumer remains a later task. file:external@0 b05d264190ef2172e87e5b2667164f2051e83016695595e32ccbcdce9186eb6b |
| +internal/host/units/carlos-instance-gvisor@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Add the unarmed root gVisor run skeleton with empty ExecStart and all twelve measured host properties. Defines per-instance data/run writable paths and socket output, root runtime directory, mixed kill with SIGCONT, and the existing bounded stop. A root-prepared validated command drop-in is required before it can start; no command or pin placeholder is installed here. file:external@0 914a3c0486d83b6b87ce14c473aab9005ff7bc004cb984040a81ddc60087a5c1 |
| +internal/instanceexec/sandbox_linux.go gvisorProbeChecks legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Preliminary guest-only probe reads the fixed /proc/self/status to check empty capability sets and NoNewPrivs, and SelfCheck opens the fixed own /data/instances/_probe directory with unchanged safe-open flags. Runs as the guest carlos identity; reports readiness incomplete until the later root challenges exist. No tenant-selected host path or root authority is added. Echo CARLOS_GVISOR_PROBE_NONCE from the initial guest environment in the additive omitempty report field; root supplies the challenge in the OCI environment. No new filesystem read or readiness grant. data-literal@696,file:ReadFile@202 b201174cac395aea50cbe7c306859c47a120d1a954d988a43e9746a1386f658a |
| +@coverage internal/execsandbox 26eb160586c30b71111fff99a1614e58602ab834e12c494a72d2a3eca9e22882 |
| @coverage internal/host 6c84353dc2f5a136936c4872f2a69454d0f0578fc49583879fe8fa06854e87ae |
| -@coverage internal/host/units bd5e78f37a4c2e876e5d5eb906e0bee0987eff2b8c61fb0fe130b09bdd4f0540 |
| -@coverage internal/instancectl a943ca98500fd1e41282a8cb1421428f53df5e6a5ec2a347d542b107df03a6c8 |
| -@coverage internal/instanceexec 92f855820c777b54d5ef9261dfb861d5cb59a228edd1030be30782d6b0282ae2 |
| +@coverage internal/host/units 92f06e9416505a1aa1912fa0bdf0666f3291c0a2c15923efac7e01065883d5e4 |
| +@coverage internal/instancectl b659d8723cb3011984e9de6c4a79f75afaf7dcee5031b4e338742a9400c40c8e |
| +@coverage internal/instanceexec 451a4cb9a8fc078f883afab1c361678185c332a1e294c24420ab4ae2fb3face9 |