Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(agent): enforce a demoted runtime boundary

OKNOTOKa28c5191dacf
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index eed27c0..6a1c34c 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -51,6 +51,10 @@ jobs:
- 'server/docker/agent-computer.Dockerfile.dockerignore'
- 'server/docker/agent-computer-cumora.sh'
- 'server/docker/agent-computer-entrypoint.sh'
+ - 'server/docker/agent-computer-bootstrap.sh'
+ - 'server/scripts/agent-boundary-smoke.mjs'
+ - 'server/scripts/fixtures/agent-boundary-loop.cjs'
+ - 'server/scripts/fixtures/agent-boundary-backend.py'
- 'agent-fuse/**'
- '.github/workflows/build.yml'
- 'package.json'
@@ -257,6 +261,23 @@ jobs:
# Same ignore-error rationale as the server image above.
cache-to: type=gha,scope=agent,mode=max,ignore-error=true
+ - name: Pull agent image for boundary smoke
+ run: |
+ docker pull "${{ env.AR_REGION }}-docker.pkg.dev/${{ env.GCP_PROJECT }}/${{ env.AR_REPO }}/agent-computer:${{ steps.meta.outputs.tag }}"
+
+ - name: Run real agent boundary smoke
+ env:
+ CUMORA_AGENT_BOUNDARY_IMAGE: ${{ env.AR_REGION }}-docker.pkg.dev/${{ env.GCP_PROJECT }}/${{ env.AR_REPO }}/agent-computer:${{ steps.meta.outputs.tag }}
+ run: node server/scripts/agent-boundary-smoke.mjs
+
+ - name: Upload boundary smoke report
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: agent-boundary-smoke-${{ steps.meta.outputs.tag }}
+ path: /tmp/cumora-agent-boundary-smoke-*/report.json
+ if-no-files-found: ignore
+
- name: Summary
run: |
echo "### Agent-computer image" >> $GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index fadbbc4..569bab6 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -1,8 +1,8 @@
# PR checks — fast feedback on every pull request to main.
#
-# Intentionally cheap: just tsc on both projects, plus `npm test` if a
-# test script exists. No Docker, no GCP auth, no secrets — these run
-# safely on forks too.
+# The ordinary checks stay cheap and require no cloud credentials. Boundary
+# changes additionally run the real Linux agent image smoke locally, without
+# pushing an image or contacting a provider.
name: PR
@@ -17,6 +17,72 @@ concurrency:
cancel-in-progress: true
jobs:
+ agent-boundary-changes:
+ name: Detect agent boundary changes
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ boundary: ${{ steps.filter.outputs.boundary }}
+ steps:
+ - uses: actions/checkout@v4
+ - id: filter
+ uses: dorny/paths-filter@v3
+ with:
+ filters: |
+ boundary:
+ - 'agent-fuse/**'
+ - 'server/docker/agent-computer.Dockerfile'
+ - 'server/docker/agent-computer.Dockerfile.dockerignore'
+ - 'server/docker/agent-computer-bootstrap.sh'
+ - 'server/docker/agent-computer-entrypoint.sh'
+ - 'server/scripts/agent-boundary-smoke.mjs'
+ - 'server/scripts/fixtures/**'
+ - 'server/src/agents/runtime/orchestrator.ts'
+ - 'server/src/__tests__/agent-computer-image.test.ts'
+ - 'server/src/__tests__/agents-orchestrator.test.ts'
+ - 'server/k8s/cumora-agent-network-policy.yaml'
+ - 'server/k8s/cumora-server.gke.yaml'
+ - 'server/k8s/cumora-server.orbstack.yaml'
+ - 'server/k8s/gke.md'
+ - '.github/workflows/pr.yml'
+ - '.github/workflows/build.yml'
+ - '.github/workflows/agent-fuse.yml'
+
+ agent-boundary-smoke:
+ name: Real agent boundary smoke (Linux)
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ needs: [agent-boundary-changes]
+ if: needs.agent-boundary-changes.outputs.boundary == 'true'
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '24'
+ cache: 'npm'
+ - run: npm ci
+ - name: Bundle agent CLI
+ run: node server/src/scripts/build-agent-bundle.mjs
+ - name: Require Docker FUSE device
+ run: test -c /dev/fuse
+ - name: Build local Linux agent image
+ env:
+ IMAGE: cumora-agent-boundary-pr:${{ github.run_id }}
+ run: docker build --platform linux/amd64 -f server/docker/agent-computer.Dockerfile -t "$IMAGE" .
+ - name: Run real boundary smoke
+ env:
+ CUMORA_AGENT_BOUNDARY_IMAGE: cumora-agent-boundary-pr:${{ github.run_id }}
+ run: node server/scripts/agent-boundary-smoke.mjs
+ - name: Upload boundary smoke report
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: agent-boundary-smoke-pr-${{ github.run_id }}
+ path: /tmp/cumora-agent-boundary-smoke-*/report.json
+ if-no-files-found: ignore
+
# P0 tripwire: the BIG (brain) model may ONLY do real, heavy tasks. Any
# ungated big-model selection is a P0 incident. This job runs the static
# scanner first and fast — no npm install, no deps — so a regression turns
diff --git a/agent-fuse/cli.go b/agent-fuse/cli.go
new file mode 100644
index 0000000..995195f
--- /dev/null
+++ b/agent-fuse/cli.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "net/url"
+ "path/filepath"
+ "strings"
+)
+
+// runtimeConfig is intentionally limited to non-secret launch parameters.
+// The bearer is read from a root-only file after the process starts and never
+// accepted as an argv value.
+type runtimeConfig struct {
+ baseURL string
+ mountPoint string
+ tokenFile string
+ logFile string
+ readyFD int
+ lifetimeFD int
+}
+
+func parseRuntimeConfig(args []string) (runtimeConfig, error) {
+ var cfg runtimeConfig
+ fs := flag.NewFlagSet("cumora-fuse", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ fs.StringVar(&cfg.baseURL, "runtime-base-url", "", "runtime server base URL")
+ fs.StringVar(&cfg.mountPoint, "mount-point", "", "FUSE mount point")
+ fs.StringVar(&cfg.tokenFile, "token-file", "", "root-only bearer token file")
+ fs.StringVar(&cfg.logFile, "log-file", "", "optional FUSE log file")
+ fs.IntVar(&cfg.readyFD, "ready-fd", -1, "write-only readiness pipe FD")
+ fs.IntVar(&cfg.lifetimeFD, "lifetime-fd", -1, "write-only lifetime pipe FD")
+ if err := fs.Parse(args); err != nil {
+ return runtimeConfig{}, err
+ }
+ if fs.NArg() != 0 {
+ return runtimeConfig{}, fmt.Errorf("unexpected positional arguments")
+ }
+ if cfg.baseURL == "" {
+ return runtimeConfig{}, errors.New("--runtime-base-url is required")
+ }
+ u, err := url.Parse(cfg.baseURL)
+ if err != nil || u.Scheme == "" || u.Host == "" || u.User != nil || u.Fragment != "" {
+ return runtimeConfig{}, errors.New("--runtime-base-url must be an absolute http(s) URL without userinfo or fragment")
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return runtimeConfig{}, errors.New("--runtime-base-url must use http or https")
+ }
+ cfg.baseURL = strings.TrimRight(cfg.baseURL, "/")
+ if cfg.mountPoint == "" || !filepath.IsAbs(cfg.mountPoint) || filepath.Clean(cfg.mountPoint) == "/" {
+ return runtimeConfig{}, errors.New("--mount-point must be an absolute non-root path")
+ }
+ if cfg.tokenFile == "" || !filepath.IsAbs(cfg.tokenFile) {
+ return runtimeConfig{}, errors.New("--token-file must be an absolute path")
+ }
+ if cfg.logFile != "" && !filepath.IsAbs(cfg.logFile) {
+ return runtimeConfig{}, errors.New("--log-file must be an absolute path")
+ }
+ if cfg.readyFD < 3 || cfg.lifetimeFD < 3 || cfg.readyFD == cfg.lifetimeFD {
+ return runtimeConfig{}, errors.New("--ready-fd and --lifetime-fd must be distinct inherited FDs >= 3")
+ }
+ return cfg, nil
+}
diff --git a/agent-fuse/go.mod b/agent-fuse/go.mod
index 77f49c3..4b74e0b 100644
--- a/agent-fuse/go.mod
+++ b/agent-fuse/go.mod
@@ -2,6 +2,7 @@ module github.com/cumora/agent-fuse
go 1.24
-require github.com/hanwen/go-fuse/v2 v2.5.1
-
-require golang.org/x/sys v0.15.0 // indirect
+require (
+ github.com/hanwen/go-fuse/v2 v2.5.1
+ golang.org/x/sys v0.15.0
+)
diff --git a/agent-fuse/main.go b/agent-fuse/main.go
index 7bd645a..5ae6ff1 100644
--- a/agent-fuse/main.go
+++ b/agent-fuse/main.go
@@ -1,7 +1,12 @@
// cumora-fuse — a FUSE driver that maps the agent's slice of the
// `agent_workspace` table to a real filesystem at the mount point.
//
-// cumora-fuse "$CUMORA_AGENT_RUNTIME_URL" "$CUMORA_AGENT_RUNTIME_TOKEN" /workspace
+// cumora-fuse \
+// --runtime-base-url "$CUMORA_AGENT_RUNTIME_URL" \
+// --mount-point /workspace \
+// --token-file /run/cumora/fuse-token \
+// --ready-fd 4 --lifetime-fd 5 \
+// --log-file /tmp/cumora-fuse.log
//
// Instead of connecting to Postgres directly, the FUSE driver issues
// HTTP requests to the cumora server's `/runtime/fs/*` endpoints.
@@ -494,18 +499,41 @@ func joinRel(parent, name string) string {
// ─── main ──────────────────────────────────────────────────────────
func main() {
- if len(os.Args) != 4 {
- fmt.Fprintln(os.Stderr, "usage: cumora-fuse <runtime-base-url> <bearer-token> <mount-point>")
+ cfg, err := parseRuntimeConfig(os.Args[1:])
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "cumora-fuse: %v\n", err)
os.Exit(2)
}
- baseURL := os.Args[1]
- token := os.Args[2]
- mountPoint := os.Args[3]
- w := newWs(baseURL, token)
+ var fuseLogFile *os.File
+ if cfg.logFile != "" {
+ fuseLogFile, err = openSecureLogFile(cfg.logFile)
+ if err != nil {
+ log.Fatalf("open FUSE log: %v", err)
+ }
+ defer fuseLogFile.Close()
+ log.SetOutput(fuseLogFile)
+ }
+
+ token, err := readRootOnlyToken(cfg.tokenFile)
+ if err != nil {
+ log.Fatalf("read FUSE token: %v", err)
+ }
+ readyFD, lifetimeFD, err := prepareNotifierFDs(cfg.readyFD, cfg.lifetimeFD)
+ if err != nil {
+ log.Fatalf("prepare readiness/lifetime FDs: %v", err)
+ }
+ // Keep the lifetime writer open until this process exits. The bootstrap
+ // owns the reader and uses EOF as an unambiguous process-lifetime signal;
+ // CloseOnExec is set by prepareNotifierFDs so a fusermount helper cannot
+ // accidentally keep that pipe open.
+ defer lifetimeFD.Close()
+
+ parentPID := os.Getppid()
+ w := newWs(cfg.baseURL, token)
// Probe once so we fail fast if the URL is wrong.
if _, errno := w.stat(""); errno != 0 {
- log.Fatalf("[cumora-fuse] sanity-stat failed: errno=%d (is %s reachable?)", errno, baseURL)
+ log.Fatalf("[cumora-fuse] sanity-stat failed: errno=%d (is %s reachable?)", errno, cfg.baseURL)
}
root := &dirNode{w: w, relPath: ""}
@@ -514,21 +542,30 @@ func main() {
MountOptions: fuse.MountOptions{
Name: "cumora-workspace",
FsName: "cumora-workspace",
- AllowOther: false,
+ AllowOther: true,
+ Options: []string{"default_permissions"},
DisableXAttrs: true,
Debug: os.Getenv("CUMORA_FUSE_DEBUG") == "1",
DirectMount: false,
},
+ UID: modelUID,
+ GID: modelGID,
EntryTimeout: durptr(0),
AttrTimeout: durptr(0),
NegativeTimeout: durptr(0),
}
- srv, err := fs.Mount(mountPoint, root, opts)
+ srv, err := fs.Mount(cfg.mountPoint, root, opts)
if err != nil {
- log.Fatalf("[cumora-fuse] mount %q: %v", mountPoint, err)
+ log.Fatalf("[cumora-fuse] mount %q: %v", cfg.mountPoint, err)
+ }
+ if err := demoteAfterMount(parentPID); err != nil {
+ log.Fatalf("[cumora-fuse] privilege drop failed after mount: %v", err)
+ }
+ if err := writeReadyMarker(readyFD); err != nil {
+ log.Fatalf("[cumora-fuse] readiness marker failed: %v", err)
}
- log.Printf("[cumora-fuse] mounted at %s (backend %s)", mountPoint, baseURL)
+ log.Printf("[cumora-fuse] mounted at %s (backend %s)", cfg.mountPoint, cfg.baseURL)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
@@ -539,14 +576,18 @@ func main() {
// Unmount() ends up blocking on a stuck in-flight request.
// go-fuse's Wait() is documented to return after Unmount, but
// in practice we've seen it stall waiting on the IO loop. The
- // kernel mount goes away the moment Unmount returns; once it
- // does there's nothing useful left to do, so just leave.
+ // A successful Unmount removes the kernel mount. After a demoted
+ // daemon, EPERM is possible; container namespace teardown remains
+ // responsible for reclaiming the mount in that case.
time.AfterFunc(3*time.Second, func() {
- log.Printf("[cumora-fuse] grace period elapsed, exit 0")
+ log.Printf("[cumora-fuse] grace period elapsed; exiting; container namespace teardown is required")
os.Exit(0)
})
if err := srv.Unmount(); err != nil {
- log.Printf("[cumora-fuse] unmount error: %v", err)
+ // After the daemon has dropped CAP_SYS_ADMIN, EPERM is expected
+ // on the container stop path. The parent/container teardown owns
+ // final mount-namespace cleanup; do not claim that unmount worked.
+ log.Printf("[cumora-fuse] unmount error (namespace teardown may be required): %v", err)
}
}()
diff --git a/agent-fuse/privilege.go b/agent-fuse/privilege.go
new file mode 100644
index 0000000..a106fdd
--- /dev/null
+++ b/agent-fuse/privilege.go
@@ -0,0 +1,100 @@
+package main
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+)
+
+const (
+ modelUID = 65532
+ modelGID = 65532
+ fuseUID = 65533
+ fuseGID = 65533
+)
+
+var errLinuxBoundaryUnsupported = errors.New("FUSE privilege boundary requires Linux all-thread syscalls")
+
+func statusFields(status, key string) ([]string, bool) {
+ for _, line := range strings.Split(status, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) >= 2 && strings.TrimSuffix(fields[0], ":") == key {
+ return fields[1:], true
+ }
+ }
+ return nil, false
+}
+
+func statusValue(status, key string) (string, bool) {
+ values, ok := statusFields(status, key)
+ if !ok || len(values) == 0 {
+ return "", false
+ }
+ return values[0], true
+}
+
+func validateStatusText(status, taskPath string) error {
+ for key, want := range map[string]int{"Uid": fuseUID, "Gid": fuseGID} {
+ values, ok := statusFields(status, key)
+ wantValue := strconv.Itoa(want)
+ if !ok || len(values) != 4 {
+ return fmt.Errorf("task %s %s=%q, want four identity fields all %d", taskPath, key, values, want)
+ }
+ for index, value := range values {
+ if value != wantValue {
+ return fmt.Errorf("task %s %s[%d]=%q, want %d", taskPath, key, index, value, want)
+ }
+ }
+ }
+ for _, key := range []string{"CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"} {
+ value, ok := statusValue(status, key)
+ if !ok || strings.TrimLeft(strings.ToLower(value), "0") != "" {
+ return fmt.Errorf("task %s %s=%q, want zero", taskPath, key, value)
+ }
+ }
+ noNewPrivs, ok := statusValue(status, "NoNewPrivs")
+ if !ok || noNewPrivs != "1" {
+ return fmt.Errorf("task %s NoNewPrivs=%q, want 1", taskPath, noNewPrivs)
+ }
+ groupsSeen := false
+ for _, line := range strings.Split(status, "\n") {
+ if strings.HasPrefix(line, "Groups:") && strings.TrimSpace(strings.TrimPrefix(line, "Groups:")) != "" {
+ return fmt.Errorf("task %s has supplementary groups: %q", taskPath, line)
+ }
+ if strings.HasPrefix(line, "Groups:") {
+ groupsSeen = true
+ }
+ }
+ if !groupsSeen {
+ return fmt.Errorf("task %s Groups field is missing", taskPath)
+ }
+ return nil
+}
+
+func writeReadyMarker(readyFD *os.File) error {
+ if readyFD == nil {
+ return errors.New("readiness FD is unavailable")
+ }
+ defer readyFD.Close()
+ const marker = "READY\n"
+ n, err := readyFD.WriteString(marker)
+ if err != nil {
+ return err
+ }
+ if n != len(marker) {
+ return fmt.Errorf("short readiness marker write: %d/%d bytes", n, len(marker))
+ }
+ return nil
+}
+
+// The platform files provide the security-sensitive implementations. The
+// non-Linux build remains compilable for static/unit tests but fails closed if
+// someone tries to run the boundary there.
+func demoteAfterMount(parentPID int) error { return demoteAfterMountPlatform(parentPID) }
+func readRootOnlyToken(name string) (string, error) { return readRootOnlyTokenPlatform(name) }
+func openSecureLogFile(name string) (*os.File, error) { return openSecureLogFilePlatform(name) }
+func prepareNotifierFDs(readyFD, lifetimeFD int) (*os.File, *os.File, error) {
+ return prepareNotifierFDsPlatform(readyFD, lifetimeFD)
+}
diff --git a/agent-fuse/privilege_linux.go b/agent-fuse/privilege_linux.go
new file mode 100644
index 0000000..71c9f9b
--- /dev/null
+++ b/agent-fuse/privilege_linux.go
@@ -0,0 +1,284 @@
+//go:build linux
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ capVersion3 = 0x20080522
+ prCapAmbient = 47
+ prCapAmbientClearAll = 4
+)
+
+func allThreadsPrctl(option, arg2, arg3 uintptr) error {
+ _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, option, arg2, arg3)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+func clearCapabilities() error {
+ header := struct {
+ version uint32
+ pid int32
+ }{version: capVersion3}
+ data := [2]struct {
+ effective uint32
+ permitted uint32
+ inheritable uint32
+ }{}
+ _, _, errno := syscall.AllThreadsSyscall6(
+ syscall.SYS_CAPSET,
+ uintptr(unsafe.Pointer(&header)),
+ uintptr(unsafe.Pointer(&data[0])),
+ 0, 0, 0, 0,
+ )
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+func capLast() (int, error) {
+ b, err := os.ReadFile("/proc/sys/kernel/cap_last_cap")
+ if err != nil {
+ return 0, err
+ }
+ last, err := strconv.Atoi(strings.TrimSpace(string(b)))
+ if err != nil || last < 0 {
+ return 0, fmt.Errorf("invalid cap_last_cap: %q", string(b))
+ }
+ return last, nil
+}
+
+func validateTaskStatus(taskPath string) error {
+ b, err := os.ReadFile(filepath.Join(taskPath, "status"))
+ if err != nil {
+ return err
+ }
+ return validateStatusText(string(b), taskPath)
+}
+
+func validateAllThreads() error {
+ for pass := 0; pass < 2; pass++ {
+ entries, err := os.ReadDir("/proc/self/task")
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if _, err := strconv.Atoi(entry.Name()); err != nil {
+ continue
+ }
+ if err := validateTaskStatus(filepath.Join("/proc/self/task", entry.Name())); err != nil {
+ // A thread may exit between ReadDir and status read. It cannot
+ // become an unsafe surviving thread, so ignore only ENOENT and
+ // fail closed for every other read/validation error.
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ return err
+ }
+ }
+ // A second pass catches threads created while the first status set
+ // was being read. New Go threads inherit this already-demoted
+ // process context, but READY must still be based on an observed
+ // all-thread check.
+ if pass == 0 {
+ continue
+ }
+ }
+ return nil
+}
+
+func demoteAfterMountPlatform(parentPID int) error {
+ // Every operation is applied to all current Go runtime threads. CGO=0 is
+ // part of the production build contract; an unsupported all-thread syscall
+ // is an error and never falls back to the calling thread only.
+ const prSetNoNewPrivs = 38
+ if err := allThreadsPrctl(prSetNoNewPrivs, 1, 0); err != nil {
+ return fmt.Errorf("PR_SET_NO_NEW_PRIVS: %w", err)
+ }
+ if err := allThreadsPrctl(prCapAmbient, prCapAmbientClearAll, 0); err != nil {
+ return fmt.Errorf("clear ambient capabilities: %w", err)
+ }
+ last, err := capLast()
+ if err != nil {
+ return err
+ }
+ // CAP_SETPCAP remains effective while the bounding set is cleared. The
+ // subsequent UID transition and capset(2) remove the effective/permitted
+ // sets; validation below proves every set is zero.
+ for cap := 0; cap <= last; cap++ {
+ if err := allThreadsPrctl(syscall.PR_CAPBSET_DROP, uintptr(cap), 0); err != nil {
+ return fmt.Errorf("drop bounding capability %d: %w", cap, err)
+ }
+ }
+ if err := syscall.Setgroups(nil); err != nil {
+ return fmt.Errorf("clear supplementary groups: %w", err)
+ }
+ if err := syscall.Setresgid(fuseGID, fuseGID, fuseGID); err != nil {
+ return fmt.Errorf("setresgid: %w", err)
+ }
+ if err := syscall.Setresuid(fuseUID, fuseUID, fuseUID); err != nil {
+ return fmt.Errorf("setresuid: %w", err)
+ }
+ if err := clearCapabilities(); err != nil {
+ return fmt.Errorf("capset zero: %w", err)
+ }
+ // Linux clears PDEATHSIG during a setuid transition. Re-arm it after the
+ // transition and ensure the root bootstrap PID did not disappear during
+ // the privilege drop.
+ if err := allThreadsPrctl(syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGTERM), 0); err != nil {
+ return fmt.Errorf("set parent-death signal: %w", err)
+ }
+ if os.Getppid() != parentPID {
+ return fmt.Errorf("parent changed during privilege drop: got %d want %d", os.Getppid(), parentPID)
+ }
+ return validateAllThreads()
+}
+
+func readRootOnlyTokenPlatform(name string) (string, error) {
+ fd, err := unix.Open(name, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
+ if err != nil {
+ return "", err
+ }
+ f := os.NewFile(uintptr(fd), name)
+ if f == nil {
+ _ = unix.Close(fd)
+ return "", errors.New("token file descriptor unavailable")
+ }
+ defer f.Close()
+ var st unix.Stat_t
+ if err := unix.Fstat(fd, &st); err != nil {
+ return "", err
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFREG {
+ return "", errors.New("token file is not a regular file")
+ }
+ if st.Uid != 0 || st.Gid != 0 || st.Mode&0777 != 0400 {
+ return "", fmt.Errorf("token file must be root:root mode 0400 (uid=%d gid=%d mode=%#o)", st.Uid, st.Gid, st.Mode&0777)
+ }
+ if st.Size <= 0 || st.Size > 64*1024 {
+ return "", errors.New("token file has invalid size")
+ }
+ b, err := io.ReadAll(io.LimitReader(f, 64*1024+1))
+ if err != nil {
+ return "", err
+ }
+ if len(b) > 64*1024 {
+ return "", errors.New("token file is too large")
+ }
+ token := strings.TrimSpace(string(b))
+ if token == "" {
+ return "", errors.New("token file is empty")
+ }
+ return token, nil
+}
+
+func validateSecureParent(name string) error {
+ parent := filepath.Dir(name)
+ var st unix.Stat_t
+ if err := unix.Lstat(parent, &st); err != nil {
+ return err
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFDIR || st.Uid != 0 {
+ return fmt.Errorf("log parent %q must be a root-owned directory", parent)
+ }
+ perm := st.Mode & 0777
+ // /tmp is root-owned and sticky (01777), so it is acceptable when the
+ // final component is opened with O_NOFOLLOW and verified as root:root
+ // 0600. A non-sticky writable parent would permit replacement attacks.
+ if st.Mode&01000 == 0 && (perm&0070 != 0 || perm&0002 != 0) {
+ return fmt.Errorf("log parent %q is writable by a non-root process", parent)
+ }
+ return nil
+}
+
+func openSecureLogFilePlatform(name string) (*os.File, error) {
+ if err := validateSecureParent(name); err != nil {
+ return nil, err
+ }
+ fd, err := unix.Open(name, unix.O_WRONLY|unix.O_CREAT|unix.O_APPEND|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0600)
+ if err != nil {
+ return nil, err
+ }
+ f := os.NewFile(uintptr(fd), name)
+ if f == nil {
+ _ = unix.Close(fd)
+ return nil, errors.New("log file descriptor unavailable")
+ }
+ var st unix.Stat_t
+ if err := unix.Fstat(fd, &st); err != nil {
+ _ = f.Close()
+ return nil, err
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Uid != 0 || st.Mode&0777 != 0600 {
+ _ = f.Close()
+ return nil, errors.New("log file must remain root-owned regular mode 0600")
+ }
+ return f, nil
+}
+
+func validateNotifierFD(fd int) (unix.Stat_t, error) {
+ if fd < 3 {
+ return unix.Stat_t{}, errors.New("notifier FD must be >= 3")
+ }
+ flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
+ if err != nil {
+ return unix.Stat_t{}, err
+ }
+ if flags&unix.O_ACCMODE != unix.O_WRONLY && flags&unix.O_ACCMODE != unix.O_RDWR {
+ return unix.Stat_t{}, errors.New("notifier FD is not writable")
+ }
+ var st unix.Stat_t
+ if err := unix.Fstat(fd, &st); err != nil {
+ return unix.Stat_t{}, err
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFIFO {
+ return unix.Stat_t{}, errors.New("notifier FD is not a pipe")
+ }
+ unix.CloseOnExec(fd)
+ return st, nil
+}
+
+func prepareNotifierFDsPlatform(readyFD, lifetimeFD int) (*os.File, *os.File, error) {
+ if readyFD == lifetimeFD {
+ return nil, nil, errors.New("readiness and lifetime FDs must be distinct")
+ }
+ readyStat, err := validateNotifierFD(readyFD)
+ if err != nil {
+ return nil, nil, fmt.Errorf("ready FD %d: %w", readyFD, err)
+ }
+ lifetimeStat, err := validateNotifierFD(lifetimeFD)
+ if err != nil {
+ return nil, nil, fmt.Errorf("lifetime FD %d: %w", lifetimeFD, err)
+ }
+ if readyStat.Dev != lifetimeStat.Dev || readyStat.Ino != lifetimeStat.Ino {
+ return nil, nil, errors.New("readiness and lifetime FDs must refer to the same pipe")
+ }
+ ready := os.NewFile(uintptr(readyFD), "cumora-fuse-ready")
+ lifetime := os.NewFile(uintptr(lifetimeFD), "cumora-fuse-lifetime")
+ if ready == nil || lifetime == nil {
+ if ready != nil {
+ _ = ready.Close()
+ }
+ if lifetime != nil {
+ _ = lifetime.Close()
+ }
+ return nil, nil, errors.New("notifier FD unavailable")
+ }
+ return ready, lifetime, nil
+}
diff --git a/agent-fuse/privilege_linux_test.go b/agent-fuse/privilege_linux_test.go
new file mode 100644
index 0000000..d5278aa
--- /dev/null
+++ b/agent-fuse/privilege_linux_test.go
@@ -0,0 +1,104 @@
+//go:build linux
+
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/sys/unix"
+)
+
+func TestReadRootOnlyTokenRejectsSymlink(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "token")
+ link := filepath.Join(dir, "token-link")
+ if err := os.WriteFile(target, []byte("fixture-token"), 0400); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readRootOnlyTokenPlatform(link); err == nil {
+ t.Fatal("symlink token path was accepted")
+ }
+}
+
+func TestReadRootOnlyTokenRejectsBroadPermissions(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "token")
+ if err := os.WriteFile(path, []byte("fixture-token"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readRootOnlyTokenPlatform(path); err == nil {
+ t.Fatal("token file readable by non-root was accepted")
+ }
+}
+
+func TestPrepareNotifierFDsRejectsRegularFiles(t *testing.T) {
+ f, err := os.CreateTemp(t.TempDir(), "notifier")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if _, _, err := prepareNotifierFDsPlatform(int(f.Fd()), int(f.Fd())+1); err == nil {
+ t.Fatal("regular file was accepted as notifier pipe")
+ }
+}
+
+func TestPrepareNotifierFDsRequiresTheSamePipe(t *testing.T) {
+ readyReader, readyWriter, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer readyReader.Close()
+ defer readyWriter.Close()
+ lifetimeReader, lifetimeWriter, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lifetimeReader.Close()
+ defer lifetimeWriter.Close()
+ if _, _, err := prepareNotifierFDsPlatform(int(readyWriter.Fd()), int(lifetimeWriter.Fd())); err == nil {
+ t.Fatal("write ends of different pipes were accepted")
+ }
+}
+
+func TestPrepareNotifierFDsAcceptsDistinctWriteEndsOfTheSamePipe(t *testing.T) {
+ reader, writer, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reader.Close()
+ defer writer.Close()
+ dup, err := unix.Dup(int(writer.Fd()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ready, lifetime, err := prepareNotifierFDsPlatform(int(writer.Fd()), dup)
+ if err != nil {
+ _ = unix.Close(dup)
+ t.Fatalf("same-pipe notifier FDs rejected: %v", err)
+ }
+ if err := ready.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := lifetime.Close(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestOpenSecureLogFileRejectsFinalSymlink(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "target.log")
+ link := filepath.Join(dir, "fuse.log")
+ if err := os.WriteFile(target, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := openSecureLogFilePlatform(link); err == nil {
+ t.Fatal("log symlink was followed")
+ }
+}
diff --git a/agent-fuse/privilege_other.go b/agent-fuse/privilege_other.go
new file mode 100644
index 0000000..772def8
--- /dev/null
+++ b/agent-fuse/privilege_other.go
@@ -0,0 +1,22 @@
+//go:build !linux
+
+package main
+
+import (
+ "errors"
+ "os"
+)
+
+func demoteAfterMountPlatform(int) error { return errLinuxBoundaryUnsupported }
+
+func readRootOnlyTokenPlatform(string) (string, error) {
+ return "", errLinuxBoundaryUnsupported
+}
+
+func openSecureLogFilePlatform(string) (*os.File, error) {
+ return nil, errLinuxBoundaryUnsupported
+}
+
+func prepareNotifierFDsPlatform(int, int) (*os.File, *os.File, error) {
+ return nil, nil, errors.New("readiness/lifetime pipes require Linux")
+}
diff --git a/agent-fuse/privilege_test.go b/agent-fuse/privilege_test.go
new file mode 100644
index 0000000..d6a9215
--- /dev/null
+++ b/agent-fuse/privilege_test.go
@@ -0,0 +1,127 @@
+package main
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestParseRuntimeConfigUsesOnlyNonSecretArguments(t *testing.T) {
+ cfg, err := parseRuntimeConfig([]string{
+ "--runtime-base-url", "http://server.example/runtime/",
+ "--mount-point", "/workspace",
+ "--token-file", "/run/cumora/fuse-token",
+ "--ready-fd", "4",
+ "--lifetime-fd", "5",
+ "--log-file", "/run/cumora/fuse.log",
+ })
+ if err != nil {
+ t.Fatalf("parseRuntimeConfig() error = %v", err)
+ }
+ if cfg.baseURL != "http://server.example/runtime" {
+ t.Fatalf("baseURL = %q, want trailing slash trimmed", cfg.baseURL)
+ }
+ if cfg.tokenFile != "/run/cumora/fuse-token" {
+ t.Fatalf("tokenFile = %q", cfg.tokenFile)
+ }
+ if cfg.readyFD != 4 || cfg.lifetimeFD != 5 {
+ t.Fatalf("notifier FDs = (%d, %d), want (4, 5)", cfg.readyFD, cfg.lifetimeFD)
+ }
+}
+
+func TestParseRuntimeConfigRejectsBearerInArgvAndUnsafeInputs(t *testing.T) {
+ cases := [][]string{
+ {"http://server/runtime", "secret-token", "/workspace"},
+ {"--runtime-base-url", "http://user:secret@server/runtime", "--mount-point", "/workspace", "--token-file", "/run/t", "--ready-fd", "4", "--lifetime-fd", "5"},
+ {"--runtime-base-url", "http://server/runtime", "--mount-point", "/", "--token-file", "/run/t", "--ready-fd", "4", "--lifetime-fd", "5"},
+ {"--runtime-base-url", "http://server/runtime", "--mount-point", "/workspace", "--token-file", "/run/t", "--ready-fd", "4", "--lifetime-fd", "4"},
+ }
+ for i, args := range cases {
+ if _, err := parseRuntimeConfig(args); err == nil {
+ t.Fatalf("case %d unexpectedly accepted unsafe arguments", i)
+ }
+ }
+}
+
+func TestValidateStatusTextRequiresFixedUIDCapsAndNoNewPrivs(t *testing.T) {
+ good := "Uid:\t65533\t65533\t65533\t65533\n" +
+ "Gid:\t65533\t65533\t65533\t65533\n" +
+ "Groups:\t\n" +
+ "CapInh:\t0000000000000000\n" +
+ "CapPrm:\t0000000000000000\n" +
+ "CapEff:\t0000000000000000\n" +
+ "CapBnd:\t0000000000000000\n" +
+ "CapAmb:\t0000000000000000\n" +
+ "NoNewPrivs:\t1\n"
+ if err := validateStatusText(good, "/proc/self/task/1"); err != nil {
+ t.Fatalf("validateStatusText(good) error = %v", err)
+ }
+ for name, bad := range map[string]string{
+ "uid": replaceStatus(good, "Uid:", "65532 65532 65532 65533"),
+ "uid-saved-root": replaceStatus(good, "Uid:", "65533 65533 0 65533"),
+ "uid-fs-root": replaceStatus(good, "Uid:", "65533 65533 65533 0"),
+ "gid": replaceStatus(good, "Gid:", "65532 65532 65532 65533"),
+ "gid-saved-root": replaceStatus(good, "Gid:", "65533 65533 0 65533"),
+ "gid-fs-root": replaceStatus(good, "Gid:", "65533 65533 65533 0"),
+ "caps": replaceStatus(good, "CapEff:", "0000000000000001"),
+ "nnp": replaceStatus(good, "NoNewPrivs:", "0"),
+ "grp": replaceStatus(good, "Groups:", "1000"),
+ } {
+ if err := validateStatusText(bad, "/proc/self/task/1"); err == nil {
+ t.Errorf("validateStatusText(%s) unexpectedly accepted insecure status", name)
+ }
+ }
+}
+
+func replaceStatus(status, key, value string) string {
+ lines := strings.Split(status, "\n")
+ for i, line := range lines {
+ if strings.HasPrefix(line, key) {
+ lines[i] = key + "\t" + value
+ return strings.Join(lines, "\n")
+ }
+ }
+ return status
+}
+
+func TestWriteReadyMarkerClosesOnlyTheReadyWriter(t *testing.T) {
+ readyReader, readyWriter, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer readyReader.Close()
+ lifetimeReader, lifetimeWriter, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lifetimeReader.Close()
+ defer lifetimeWriter.Close()
+
+ if err := writeReadyMarker(readyWriter); err != nil {
+ t.Fatalf("writeReadyMarker() error = %v", err)
+ }
+ ready, err := io.ReadAll(readyReader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(ready) != "READY\n" {
+ t.Fatalf("ready marker = %q", ready)
+ }
+ if _, err := lifetimeWriter.Write([]byte("alive")); err != nil {
+ t.Fatalf("lifetime writer closed with ready FD: %v", err)
+ }
+ buf := make([]byte, 5)
+ if _, err := io.ReadFull(lifetimeReader, buf); err != nil {
+ t.Fatal(err)
+ }
+ if string(buf) != "alive" {
+ t.Fatalf("lifetime marker = %q", buf)
+ }
+}
+
+func TestUnsupportedPlatformBoundaryIsExplicit(t *testing.T) {
+ if errLinuxBoundaryUnsupported == nil {
+ t.Fatal("unsupported-platform error must be non-nil")
+ }
+}
diff --git a/server/docker/agent-computer-bootstrap.sh b/server/docker/agent-computer-bootstrap.sh
new file mode 100755
index 0000000..6baf045
--- /dev/null
+++ b/server/docker/agent-computer-bootstrap.sh
@@ -0,0 +1,219 @@
+#!/usr/bin/env bash
+# Trusted root bootstrap for the agent-computer image.
+#
+# This script is PID 1. It performs only mount preparation and FUSE readiness
+# validation, then execs setpriv -> non-root tini -> agent-entrypoint. Keeping
+# the root phase small is deliberate: browser, OpenCLI, Node, and their
+# children are never started while this process still has capabilities.
+set -Eeuo pipefail
+umask 077
+
+MODEL_UID=65532
+MODEL_GID=65532
+FUSE_UID=65533
+BOOTSTRAP_PID=$$
+RUN_DIR=/run/cumora
+TOKEN_FILE="$RUN_DIR/fuse-token"
+WORKSPACE=/workspace
+FUSE_BIN=/usr/local/bin/cumora-fuse
+SUPERVISOR=/usr/local/bin/agent-entrypoint
+READY_TIMEOUT_SECONDS="${CUMORA_FUSE_READY_TIMEOUT_SECONDS:-60}"
+
+fail() {
+ echo "[agent-bootstrap] $1" >&2
+ exit 1
+}
+
+stop_fuse_during_bootstrap_failure() {
+ local pid=${FUSE_PID:-}
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 0
+ kill -TERM "$pid" 2>/dev/null || true
+ # No model has started yet. If the daemon is stuck in mount setup, do not
+ # leave a root child holding the container open while the bootstrap exits.
+ sleep 0.2
+ kill -KILL "$pid" 2>/dev/null || true
+}
+
+if [[ "$(id -u)" -ne 0 ]]; then
+ fail 'must start as root'
+fi
+
+if [[ ! -x "$FUSE_BIN" || ! -x /usr/bin/setpriv || ! -x /usr/bin/tini ]]; then
+ fail 'required runtime binaries are missing'
+fi
+if [[ ! -x "$SUPERVISOR" ]]; then
+ fail 'agent supervisor is missing'
+fi
+if [[ ! "$READY_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
+ fail 'invalid FUSE readiness timeout'
+fi
+
+cap_has() {
+ local hex=$1 bit=$2 value
+ value=$((16#$hex))
+ (( (value & (1 << bit)) != 0 ))
+}
+
+require_capability() {
+ local name=$1 bit=$2 hex
+ hex=$(awk '/^CapEff:/ { print $2; exit }' "/proc/$BOOTSTRAP_PID/status")
+ if [[ -z "$hex" ]] || ! cap_has "$hex" "$bit"; then
+ fail "missing bootstrap capability: $name"
+ fi
+}
+
+# SYS_ADMIN mounts FUSE; SETUID/SETGID and SETPCAP are required for the Go
+# driver's all-thread demotion. Failing before model startup is part of the
+# boundary and is covered by the negative image smoke.
+require_capability CAP_SYS_ADMIN 21
+require_capability CAP_SETUID 7
+require_capability CAP_SETGID 6
+require_capability CAP_SETPCAP 8
+require_capability CAP_KILL 5
+
+if [[ -L "$WORKSPACE" ]]; then
+ fail '/workspace must not be a symlink'
+fi
+mkdir -p "$WORKSPACE"
+workspace_owner=$(stat -c '%u:%g' "$WORKSPACE") || fail 'cannot inspect /workspace'
+[[ "$workspace_owner" == "0:0" ]] || fail '/workspace is not root-owned'
+workspace_mode=$(stat -c '%a' "$WORKSPACE") || fail 'cannot inspect /workspace mode'
+workspace_mode_value=$((8#$workspace_mode))
+# Group/world write would make an unmounted local directory a model write
+# surface. The image creates 0755; a PVC or operator override must remain
+# root-owned and equally non-writable.
+(( (workspace_mode_value & 0022) == 0 )) || fail '/workspace is writable outside root'
+
+if [[ -L "$RUN_DIR" ]]; then
+ fail "$RUN_DIR must not be a symlink"
+fi
+mkdir -p "$RUN_DIR"
+run_owner=$(stat -c '%u:%g' "$RUN_DIR") || fail 'cannot inspect token directory'
+[[ "$run_owner" == "0:0" ]] || fail 'token directory is not root-owned'
+chmod 0700 "$RUN_DIR"
+run_mode=$(stat -c '%a' "$RUN_DIR") || fail 'cannot inspect token directory mode'
+[[ "$run_mode" == "700" ]] || fail 'token directory is not private'
+
+if [[ -z "${CUMORA_AGENT_RUNTIME_URL:-}" ]]; then
+ fail 'CUMORA_AGENT_RUNTIME_URL is required'
+fi
+if [[ -z "${CUMORA_AGENT_RUNTIME_TOKEN:-}" ]]; then
+ fail 'CUMORA_AGENT_RUNTIME_TOKEN is required'
+fi
+
+if [[ -e "$TOKEN_FILE" || -L "$TOKEN_FILE" ]]; then
+ fail 'stale FUSE token file exists'
+fi
+printf '%s' "$CUMORA_AGENT_RUNTIME_TOKEN" >"$TOKEN_FILE"
+chmod 0400 "$TOKEN_FILE"
+token_owner=$(stat -c '%u:%g:%a' "$TOKEN_FILE") || fail 'cannot inspect FUSE token'
+[[ "$token_owner" == "0:0:400" ]] || fail 'FUSE token has unsafe ownership or mode'
+
+NOTIFY_FIFO="$RUN_DIR/notify.$$.fifo"
+rm -f "$NOTIFY_FIFO"
+mkfifo -m 0600 "$NOTIFY_FIFO"
+
+cleanup_bootstrap() {
+ rm -f "$NOTIFY_FIFO" "$TOKEN_FILE"
+}
+trap cleanup_bootstrap EXIT
+trap 'stop_fuse_during_bootstrap_failure; exit 143' INT TERM
+
+# Opening the FIFO read/write in this root process prevents startup races.
+# READY and lifetime are two write descriptions of this same FIFO, as checked
+# by cumora-fuse. The child closes the bootstrap description before execing Go,
+# and this process replaces itself after closing its own writer, so no
+# parent/model writer can keep EOF from arriving on the lifetime read end.
+exec 3<>"$NOTIFY_FIFO"
+(
+ exec 4>"$NOTIFY_FIFO"
+ exec 5>"$NOTIFY_FIFO"
+ exec 3>&-
+ exec env -u CUMORA_AGENT_RUNTIME_TOKEN \
+ CUMORA_FUSE_TOKEN_FILE="$TOKEN_FILE" \
+ CUMORA_FUSE_READY_FD=4 \
+ CUMORA_FUSE_LIFETIME_FD=5 \
+ /usr/local/bin/cumora-fuse \
+ --runtime-base-url "$CUMORA_AGENT_RUNTIME_URL" \
+ --mount-point "$WORKSPACE" \
+ --token-file "$TOKEN_FILE" \
+ --ready-fd 4 \
+ --lifetime-fd 5 \
+ --log-file /tmp/cumora-fuse.log
+) &
+FUSE_PID=$!
+
+# One read description is duplicated so READY cannot be consumed by the
+# lifetime reader. Bootstrap reads fd 7, then closes it; the same open-file
+# description remains as fd 8 for the post-setpriv supervisor.
+exec 7<"$NOTIFY_FIFO"
+exec 8<&7
+exec 3>&-
+rm -f "$NOTIFY_FIFO"
+
+marker=''
+if ! IFS= read -r -t "$READY_TIMEOUT_SECONDS" marker <&7; then
+ stop_fuse_during_bootstrap_failure
+ fail 'FUSE readiness timed out'
+fi
+if [[ "$marker" != READY ]]; then
+ stop_fuse_during_bootstrap_failure
+ fail 'unexpected FUSE readiness marker'
+fi
+
+mount_is_expected() {
+ awk '$5 == "/workspace" { sep=0; for (i=6; i<=NF; i++) { if ($i == "-") { sep=i; break } } if (sep > 0 && $(sep+1) == "fuse.cumora-workspace" && $(sep+2) == "cumora-workspace") count++ } END { exit(count == 1 ? 0 : 1) }' /proc/self/mountinfo
+}
+
+proc_snapshot() {
+ local line rest
+ [[ -r "/proc/$1/stat" ]] || return 1
+ line=$(<"/proc/$1/stat") || return 1
+ rest=${line##*) }
+ [[ "$rest" != "$line" ]] || return 1
+ awk '{ print $1, $20 }' <<<"$rest"
+}
+
+if ! mount_is_expected; then
+ stop_fuse_during_bootstrap_failure
+ fail 'FUSE READY arrived without the expected /workspace mount'
+fi
+fuse_snapshot=$(proc_snapshot "$FUSE_PID") || {
+ stop_fuse_during_bootstrap_failure
+ fail 'FUSE process disappeared after READY'
+}
+read -r fuse_state FUSE_STARTTIME <<<"$fuse_snapshot"
+case "$fuse_state" in
+ R|S|D) ;;
+ *) stop_fuse_during_bootstrap_failure; fail 'FUSE process is not live after READY' ;;
+esac
+if [[ ! "$FUSE_STARTTIME" =~ ^[0-9]+$ ]]; then
+ stop_fuse_during_bootstrap_failure
+ fail 'FUSE process is not live after READY'
+fi
+
+printf '%s\n' "$FUSE_PID" >"$RUN_DIR/fuse.pid"
+chmod 0400 "$RUN_DIR/fuse.pid"
+
+# The token file is no longer needed after READY and is removed before any
+# model process exists. The runtime token environment remains available to
+# the legitimate Node/runtime client; only the FUSE child receives an env -u
+# override above. The bearer is never placed in the FUSE argv.
+rm -f "$TOKEN_FILE"
+exec 7<&-
+
+export CUMORA_FUSE_PID="$FUSE_PID"
+export CUMORA_FUSE_STARTTIME="$FUSE_STARTTIME"
+export CUMORA_FUSE_LIFETIME_FD=8
+
+# Preserve fd 8 through setpriv and non-root tini. The bootstrap shell itself
+# is replaced, so there is no long-lived root process around the model.
+exec /usr/bin/setpriv \
+ --reuid="$MODEL_UID" \
+ --regid="$MODEL_GID" \
+ --clear-groups \
+ --inh-caps=-all \
+ --ambient-caps=-all \
+ --bounding-set=-all \
+ --no-new-privs \
+ /usr/bin/tini -- "$SUPERVISOR"
diff --git a/server/docker/agent-computer-entrypoint.sh b/server/docker/agent-computer-entrypoint.sh
index 93d0115..c524ef9 100755
--- a/server/docker/agent-computer-entrypoint.sh
+++ b/server/docker/agent-computer-entrypoint.sh
@@ -1,86 +1,294 @@
-#!/bin/sh
-# cumora-agent-computer entrypoint.
+#!/usr/bin/env bash
+# Already-demoted agent-computer supervisor.
#
-# Brings up the agent's runtime in dependency order, then execs the
-# long-running agent loop:
-#
-# 1. Xvfb on :99 — virtual X display for Chromium
-# 2. Chromium — loaded with the OpenCLI browser-bridge
-# extension; --user-data-dir on the PVC so
-# cookies / login state survive pod restarts
-# 3. opencli daemon — local bridge (port 19825) the agent uses
-# via `opencli browser ...` to drive Chromium
-# 4. cumora-fuse on /workspace — agent's per-agent slice of the DB-FS
-# 5. node /app/agent-computer.cjs — the agent loop
-#
-# All side processes are backgrounded; the agent loop holds the wait
-# slot so PID 1 (tini) sees a single "real" foreground child. On SIGTERM
-# we forward to every side process and give them time to exit cleanly
-# before SIGKILL takes over.
-set -eu
+# This path is deliberately kept separate from the trusted bootstrap. It is
+# only valid after setpriv has switched the process to UID 65532 with no
+# capabilities and NoNewPrivs=1. Direct root invocation is a fail-closed
+# configuration error; there is no compatibility path back to the old root
+# entrypoint.
+set -Eeuo pipefail
+
+MODEL_UID=65532
+MODEL_GID=65532
+FUSE_UID=65533
+FUSE_LIFETIME_FD="${CUMORA_FUSE_LIFETIME_FD:-8}"
+FUSE_PID="${CUMORA_FUSE_PID:-}"
+FUSE_STARTTIME="${CUMORA_FUSE_STARTTIME:-}"
+WORKSPACE=/workspace
+FAILURE_MARKER=/tmp/cumora-fuse-supervisor-failure
+SUPERVISOR_PID=$$
+
+if [[ "$(id -u)" -eq 0 ]]; then
+ echo "[agent-supervisor] refusing direct root invocation" >&2
+ exit 126
+fi
+
+if [[ "$(id -u)" != "$MODEL_UID" || "$(id -g)" != "$MODEL_GID" ]]; then
+ echo "[agent-supervisor] unexpected model identity" >&2
+ exit 126
+fi
+
+if [[ ! "$FUSE_PID" =~ ^[1-9][0-9]*$ || ! "$FUSE_STARTTIME" =~ ^[0-9]+$ ]]; then
+ echo "[agent-supervisor] missing FUSE lifecycle identity" >&2
+ exit 126
+fi
+
+if [[ ! "$FUSE_LIFETIME_FD" =~ ^[0-9]+$ ]]; then
+ echo "[agent-supervisor] invalid FUSE lifetime FD" >&2
+ exit 126
+fi
-: "${CUMORA_AGENT_RUNTIME_URL:?CUMORA_AGENT_RUNTIME_URL not set — orchestrator should inject it}"
-: "${CUMORA_AGENT_RUNTIME_TOKEN:?CUMORA_AGENT_RUNTIME_TOKEN not set — orchestrator should inject it}"
+if [[ ! -L "/proc/self/fd/$FUSE_LIFETIME_FD" ]]; then
+ echo "[agent-supervisor] FUSE lifetime FD is not inherited" >&2
+ exit 126
+fi
+
+status_value() {
+ local key=$1
+ awk -v key="$key" '$1 == key ":" { print $2; exit }' "/proc/$SUPERVISOR_PID/status"
+}
+
+status_four_values() {
+ local key=$1
+ awk -v key="$key" '$1 == key ":" { printf "%s %s %s %s\n", $2, $3, $4, $5; exit }' "/proc/$SUPERVISOR_PID/status"
+}
+
+# setpriv is the boundary, but keep a local assertion next to the consumers
+# so a future launcher cannot silently reintroduce a privileged model.
+if [[ "$(status_four_values Uid)" != "$MODEL_UID $MODEL_UID $MODEL_UID $MODEL_UID" || "$(status_four_values Gid)" != "$MODEL_GID $MODEL_GID $MODEL_GID $MODEL_GID" ]]; then
+ echo "[agent-supervisor] /proc identity check failed" >&2
+ exit 126
+fi
+if [[ -n "$(awk '$1 == "Groups:" { $1=""; sub(/^[[:space:]]+/, ""); print; exit }' "/proc/$SUPERVISOR_PID/status")" ]]; then
+ echo "[agent-supervisor] supplementary groups are present" >&2
+ exit 126
+fi
+for cap in CapInh CapPrm CapEff CapBnd CapAmb; do
+ if [[ "$(status_value "$cap")" != "0000000000000000" ]]; then
+ echo "[agent-supervisor] $cap is not empty" >&2
+ exit 126
+ fi
+done
+if [[ "$(status_value NoNewPrivs)" != "1" ]]; then
+ echo "[agent-supervisor] NoNewPrivs is not set" >&2
+ exit 126
+fi
+
+proc_snapshot() {
+ # /proc/<pid>/stat has a parenthesized comm field. Strip through its final
+ # ')' before asking awk for state (field 1) and starttime (field 20).
+ local pid=$1 line rest
+ [[ -r "/proc/$pid/stat" ]] || return 1
+ line=$(<"/proc/$pid/stat") || return 1
+ rest=${line##*) }
+ [[ "$rest" != "$line" ]] || return 1
+ awk '{ print $1, $20 }' <<<"$rest"
+}
+
+fuse_alive_with_same_starttime() {
+ local state starttime
+ read -r state starttime < <(proc_snapshot "$FUSE_PID") || return 1
+ case "$state" in
+ R|S|D) ;;
+ *) return 1 ;;
+ esac
+ [[ "$starttime" == "$FUSE_STARTTIME" ]]
+}
+
+workspace_mount_is_expected() {
+ [[ -r /proc/self/mountinfo ]] || return 1
+ # Mountpoint is field 5. After the separator, the filesystem type and
+ # source must remain the product's FUSE values. Scan once per health check;
+ # starting an awk process for every mountinfo line would fork repeatedly
+ # while the monitor runs once per second.
+ awk '$5 == "/workspace" { sep=0; for (i=6; i<=NF; i++) { if ($i == "-") { sep=i; break } } if (sep > 0 && $(sep+1) == "fuse.cumora-workspace" && $(sep+2) == "cumora-workspace") count++ } END { exit(count == 1 ? 0 : 1) }' /proc/self/mountinfo
+}
+
+fuse_failure() {
+ local reason=$1
+ # Keep the marker non-sensitive and one-line so the fixture/CI can prove the
+ # failure path without exposing URLs, JWTs, or process environments.
+ printf 'reason=%s\n' "$reason" >"$FAILURE_MARKER"
+ chmod 0644 "$FAILURE_MARKER"
+ kill -TERM "$SUPERVISOR_PID" 2>/dev/null || true
+}
+
+monitor_fuse() {
+ local byte rc
+ trap - TERM INT
+ while :; do
+ if ! fuse_alive_with_same_starttime; then
+ fuse_failure 'process-dead-or-replaced'
+ return 1
+ fi
+ if ! workspace_mount_is_expected; then
+ fuse_failure 'mount-missing-or-unexpected'
+ return 1
+ fi
+
+ # cumora-fuse never writes the lifetime pipe. A byte is a protocol error;
+ # EOF means the daemon exited. Timeout lets us re-check /proc and mountinfo
+ # while the writer remains open. Bash returns 142 for read timeout and 1
+ # for EOF on this descriptor.
+ if IFS= read -r -t 1 -n 1 byte <&"$FUSE_LIFETIME_FD"; then
+ fuse_failure 'unexpected-lifetime-data'
+ return 1
+ else
+ rc=$?
+ if [[ "$rc" -eq 1 ]]; then
+ fuse_failure 'lifetime-eof'
+ return 1
+ fi
+ if [[ "$rc" -ne 142 ]]; then
+ fuse_failure 'lifetime-read-error'
+ return 1
+ fi
+ fi
+ done
+}
CHROME_PROFILE_DIR="${CHROME_PROFILE_DIR:-/opt/chrome-profile}"
OPENCLI_EXTENSION_DIR="${OPENCLI_EXTENSION_DIR:-/opt/opencli-extension}"
CHROMIUM_BIN="${CHROMIUM_BIN:-/usr/bin/chromium}"
DISPLAY="${DISPLAY:-:99}"
-export DISPLAY
-
-mkdir -p /workspace "$CHROME_PROFILE_DIR"
-
-# Stale Chromium singleton locks. Chromium's profile lock symlinks
-# (SingletonLock / SingletonCookie / SingletonSocket) are written
-# directly into --user-data-dir and reference the original
-# container's hostname + pid. When the previous pod was killed
-# without a clean shutdown (kubelet SIGKILL, OOM, node reboot, etc.)
-# these symlinks survive on the PVC and the next pod's Chromium
-# refuses to attach to the profile ("appears to be in use by
-# another Chromium process … on another computer"). Sweeping them
-# at startup is safe: by the time we get here, no Chromium is
-# running in THIS pod, and the file lock would have been our own
-# previous pod's anyway.
+export DISPLAY HOME USER LOGNAME XDG_CONFIG_HOME XDG_CACHE_HOME XDG_RUNTIME_DIR
+
+# The profile may be a PVC. It must be prepared by the image or the runtime's
+# fsGroup; this process never recursively chowns attacker-writable state.
+if [[ ! -d "$CHROME_PROFILE_DIR" || ! -w "$CHROME_PROFILE_DIR" ]]; then
+ echo "[agent-supervisor] Chrome profile is not writable by model UID" >&2
+ exit 1
+fi
rm -f "$CHROME_PROFILE_DIR/SingletonLock" \
"$CHROME_PROFILE_DIR/SingletonCookie" \
- "$CHROME_PROFILE_DIR/SingletonSocket" 2>/dev/null || true
-
-# ─── 1. Xvfb ──────────────────────────────────────────────────────────
-# 1280x800x24 — enough headroom for any normal site layout. -ac disables
-# host access checks (we're the only X client). RANDR + GLX shut up
-# Chromium's "where's my display" warnings. Logs go to /tmp so they
-# don't drown stdout.
-Xvfb "$DISPLAY" -screen 0 1280x800x24 -ac +extension RANDR +extension GLX -nolisten tcp >/tmp/xvfb.log 2>&1 &
+ "$CHROME_PROFILE_DIR/SingletonSocket"
+
+if ! fuse_alive_with_same_starttime || ! workspace_mount_is_expected; then
+ echo "[agent-supervisor] FUSE boundary is not ready" >&2
+ exit 1
+fi
+
+XVFB_PID=''
+CHROME_PID=''
+OPENCLI_DOCTOR_PID=''
+LOOP_PID=''
+MONITOR_PID=''
+STOPPING=0
+EXIT_STATUS=0
+
+children_of() {
+ pgrep -P "$1" 2>/dev/null || true
+}
+
+kill_tree() {
+ local pid=$1 child
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 0
+ while read -r child; do
+ [[ "$child" =~ ^[1-9][0-9]*$ ]] || continue
+ kill_tree "$child"
+ kill -TERM "$child" 2>/dev/null || true
+ done < <(children_of "$pid")
+ kill -TERM "$pid" 2>/dev/null || true
+}
+
+model_processes() {
+ # The container has one model identity. Restrict discovery to this UID and
+ # the known executables so a fixture cannot terminate unrelated host state.
+ pgrep -u "$MODEL_UID" -f '(^|/)(Xvfb|chromium|chromium-browser|opencli|node)( |$)' 2>/dev/null || true
+}
+
+stop_model_processes() {
+ local pid
+ for pid in "$LOOP_PID" "$CHROME_PID" "$XVFB_PID" "$OPENCLI_DOCTOR_PID"; do
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue
+ kill_tree "$pid"
+ done
+ while read -r pid; do
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue
+ kill -TERM "$pid" 2>/dev/null || true
+ done < <(model_processes)
+}
+
+shutdown() {
+ [[ "$STOPPING" -eq 0 ]] || return 0
+ STOPPING=1
+ trap - TERM INT
+
+ # Stop the observer first. The FUSE daemon is a separate UID and is never
+ # signalled here; its parent-death signal and namespace teardown own it.
+ if [[ "$MONITOR_PID" =~ ^[1-9][0-9]*$ ]]; then
+ kill -TERM "$MONITOR_PID" 2>/dev/null || true
+ fi
+ stop_model_processes
+
+ local i alive pid
+ for i in {1..40}; do
+ alive=0
+ while read -r pid; do
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue
+ if kill -0 "$pid" 2>/dev/null; then
+ alive=1
+ break
+ fi
+ done < <(model_processes)
+ [[ "$alive" -eq 0 ]] && break
+ sleep 0.25
+ done
+
+ while read -r pid; do
+ [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue
+ kill -KILL "$pid" 2>/dev/null || true
+ done < <(model_processes)
+
+ if [[ "$MONITOR_PID" =~ ^[1-9][0-9]*$ ]]; then
+ wait "$MONITOR_PID" 2>/dev/null || true
+ fi
+}
+
+trap 'shutdown' EXIT
+
+on_signal() {
+ EXIT_STATUS=143
+ shutdown
+ if [[ -s "$FAILURE_MARKER" ]]; then
+ EXIT_STATUS=70
+ fi
+ exit "$EXIT_STATUS"
+}
+
+trap on_signal TERM INT
+
+# The observer runs before any browser or model process. Its only way to stop
+# the FUSE daemon is to let this non-root PID 1 exit; it never relies on
+# cross-UID kill(2) or kill -0(2).
+monitor_fuse &
+MONITOR_PID=$!
+
+# ─── Xvfb ─────────────────────────────────────────────────────────────
+Xvfb "$DISPLAY" -screen 0 1280x800x24 -ac +extension RANDR +extension GLX \
+ -nolisten tcp >/tmp/xvfb.log 2>&1 &
XVFB_PID=$!
-# Wait for the X display to be live before launching anything that
-# expects it. Without this race, Chromium's startup occasionally races
-# Xvfb and bails with "cannot open display". Cap at 5s — Xvfb usually
-# comes up in <500ms and a longer wait just delays the agent loop.
i=0
-while [ $i -lt 50 ]; do
- if [ -e "/tmp/.X${DISPLAY#:}-lock" ]; then break; fi
+while [[ "$i" -lt 50 ]]; do
+ [[ -e "/tmp/.X${DISPLAY#:}-lock" ]] && break
+ if ! kill -0 "$XVFB_PID" 2>/dev/null; then
+ echo "[agent-supervisor] Xvfb exited before display became ready" >&2
+ EXIT_STATUS=1
+ shutdown
+ exit "$EXIT_STATUS"
+ fi
sleep 0.1
i=$((i + 1))
done
+if [[ ! -e "/tmp/.X${DISPLAY#:}-lock" ]]; then
+ echo "[agent-supervisor] Xvfb display readiness timed out" >&2
+ EXIT_STATUS=1
+ shutdown
+ exit "$EXIT_STATUS"
+fi
-# ─── 2. Chromium ──────────────────────────────────────────────────────
-# Flags rationale:
-# --no-sandbox + --disable-setuid-sandbox — Chromium's sandbox requires
-# either a setuid helper or user namespaces, neither of which we can
-# reliably get inside a K8s pod (even with CAP_SYS_ADMIN). The pod
-# itself is the security boundary.
-# --disable-dev-shm-usage — /dev/shm is tiny in containers by default
-# and Chromium loves OOMing on it. Forces tmpfs-on-disk fallback.
-# --no-first-run / --no-default-browser-check / --disable-default-apps
-# — skip every interactive welcome screen.
-# --remote-debugging-port=9222 — OpenCLI's daemon talks CDP to this
-# port. Bound to localhost only (default for Chromium).
-# --user-data-dir on the PVC mount — cookies, history, login state,
-# extension storage all survive pod restarts.
-# --load-extension — points at the unpacked OpenCLI extension baked
-# into the image. The extension persists its state inside
-# --user-data-dir, so settings survive too.
+# ─── Chromium ─────────────────────────────────────────────────────────
"$CHROMIUM_BIN" \
--no-sandbox \
--disable-setuid-sandbox \
@@ -94,72 +302,39 @@ done
--user-data-dir="$CHROME_PROFILE_DIR" \
--load-extension="$OPENCLI_EXTENSION_DIR" \
--window-size=1280,800 \
- about:blank \
- >/tmp/chromium.log 2>&1 &
+ about:blank >/tmp/chromium.log 2>&1 &
CHROME_PID=$!
-# ─── 3. OpenCLI daemon ────────────────────────────────────────────────
-# Daemon auto-starts on first CLI invocation, but priming it eagerly
-# means the first `opencli browser ...` call doesn't pay the spin-up
-# cost. Failure to start here is non-fatal — the CLI will try again
-# on demand.
-(opencli doctor >/tmp/opencli-doctor.log 2>&1 || true) &
-
-# ─── 4. cumora-fuse ───────────────────────────────────────────────────
-/usr/local/bin/cumora-fuse \
- "$CUMORA_AGENT_RUNTIME_URL" \
- "$CUMORA_AGENT_RUNTIME_TOKEN" \
- /workspace &
-FUSE_PID=$!
-
-# Shutdown forwarder. Kills every side process in reverse-bringup
-# order with a 6s grace per group, then SIGKILL fallback. The agent
-# loop itself shuts down via its own signal handling; we get here on
-# pod terminate OR after the agent loop exits.
-shutdown() {
- echo "[entrypoint] shutdown: fuse=$FUSE_PID chrome=$CHROME_PID xvfb=$XVFB_PID"
- for pid in "$FUSE_PID" "$CHROME_PID" "$XVFB_PID"; do
- [ -n "$pid" ] || continue
- kill -TERM "$pid" 2>/dev/null || true
- done
- for _ in 1 2 3 4 5 6 7 8 9 10 11 12; do
- alive=0
- for pid in "$FUSE_PID" "$CHROME_PID" "$XVFB_PID"; do
- [ -n "$pid" ] || continue
- if kill -0 "$pid" 2>/dev/null; then alive=1; break; fi
- done
- [ "$alive" -eq 0 ] && return
- sleep 0.5
- done
- echo "[entrypoint] side processes didn't exit in 6s, SIGKILL"
- for pid in "$FUSE_PID" "$CHROME_PID" "$XVFB_PID"; do
- [ -n "$pid" ] || continue
- kill -KILL "$pid" 2>/dev/null || true
- done
-}
-trap shutdown TERM INT
-
-# Wait up to 10s for /workspace to become a mountpoint.
-i=0
-while [ $i -lt 100 ]; do
- if mountpoint -q /workspace 2>/dev/null; then break; fi
- sleep 0.1
- i=$((i + 1))
-done
-
-if ! mountpoint -q /workspace 2>/dev/null; then
- echo "[entrypoint] warning: /workspace did not become a FUSE mountpoint within 10s"
-else
- echo "[entrypoint] /workspace mounted via cumora-fuse"
+# OpenCLI's daemon is deliberately started in the already-demoted context.
+# A transient doctor failure is left to the runtime call to report; the image
+# smoke explicitly exercises the real doctor/browser path.
+if command -v opencli >/dev/null 2>&1; then
+ opencli doctor >/tmp/opencli-doctor.log 2>&1 &
+ OPENCLI_DOCTOR_PID=$!
fi
-# ─── 5. agent loop ────────────────────────────────────────────────────
-# Background it so we can keep handling SIGTERM (forwarded above) when
-# the pod terminates.
+# ─── agent loop ───────────────────────────────────────────────────────
node /app/agent-computer.cjs &
LOOP_PID=$!
-wait $LOOP_PID
-LOOP_EXIT=$?
+
+# Polling keeps this script portable across the Debian bash versions used by
+# local ARM64 and Linux CI images while still reacting promptly to observer
+# failures and model completion.
+while :; do
+ if ! kill -0 "$LOOP_PID" 2>/dev/null; then
+ wait "$LOOP_PID" 2>/dev/null || EXIT_STATUS=$?
+ break
+ fi
+ if ! kill -0 "$MONITOR_PID" 2>/dev/null && [[ "$STOPPING" -eq 0 ]]; then
+ EXIT_STATUS=70
+ shutdown
+ break
+ fi
+ sleep 0.2
+done
shutdown
-exit $LOOP_EXIT
+if [[ -s "$FAILURE_MARKER" ]]; then
+ EXIT_STATUS=70
+fi
+exit "$EXIT_STATUS"
diff --git a/server/docker/agent-computer.Dockerfile b/server/docker/agent-computer.Dockerfile
index 7b1c6b6..d8d140e 100644
--- a/server/docker/agent-computer.Dockerfile
+++ b/server/docker/agent-computer.Dockerfile
@@ -1,13 +1,10 @@
# cumora-agent-computer — the per-agent pod image.
#
-# Inside the pod two processes run:
-# 1. /usr/local/bin/cumora-fuse — mounts the agent's slice of
-# `agent_workspace` from Postgres at /workspace, via FUSE. The
-# agent's persona dir, memory, skills, scratch — all on the FS,
-# backed by DB rows.
-# 2. node /app/agent-computer.cjs — the agent loop. Connects to the
-# cumora server's /runtime/wake-stream over SSE, processes wakes,
-# idle-times-out and exits cleanly when there's no work.
+# The root bootstrap is PID 1 only for the short, trusted mount setup. It
+# starts cumora-fuse with a token file and dedicated READY/lifetime FDs, then
+# replaces itself with a capless, no-new-privileges model supervisor. The
+# supervisor owns the browser and Node process tree; FUSE remains a separate
+# UID and is observed through its lifetime FD and /proc/mountinfo.
#
# Build (from repo root, AFTER running build-agent-bundle.mjs):
# docker build \
@@ -58,7 +55,7 @@ FROM node:20-bookworm-slim
# Without these, OpenCLI's DOM snapshots come back with tofu boxes
# and the LLM can't tell what's on the page.
# unzip — for unpacking the OpenCLI browser-bridge extension at build time
-# procps — for pgrep used by the entrypoint heartbeat
+# procps — for pgrep used by the supervisor's child-tree shutdown
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
tini \
@@ -81,9 +78,30 @@ RUN apt-get update \
fonts-noto-cjk \
fonts-noto-color-emoji \
unzip \
+ passwd \
+ util-linux \
procps \
&& rm -rf /var/lib/apt/lists/*
+# The runtime intentionally uses numeric identities at the trust boundary.
+# Keep real passwd/group/home entries in the image: OpenCLI resolves $HOME
+# through libc and otherwise tries to create /.opencli after setpriv.
+RUN groupadd --gid 65532 cumora-agent \
+ && useradd --uid 65532 --gid 65532 --home-dir /home/cumora-agent \
+ --create-home --shell /usr/sbin/nologin cumora-agent \
+ && groupadd --gid 65533 cumora-fuse \
+ && useradd --uid 65533 --gid 65533 --home-dir /home/cumora-fuse \
+ --create-home --shell /usr/sbin/nologin cumora-fuse \
+ && install -d -o 65532 -g 65532 -m 0700 \
+ /home/cumora-agent/.opencli \
+ /home/cumora-agent/.cache \
+ /home/cumora-agent/.config \
+ /opt/chrome-profile \
+ /run/user/65532 \
+ && chmod 0700 /home/cumora-agent /home/cumora-fuse \
+ && install -d -o 0 -g 0 -m 0755 /workspace \
+ && install -d -o 0 -g 0 -m 0700 /run/cumora
+
# ─── uv: Astral's Rust-built Python package/project manager ───────────
# Bundled because skill packages and many agent scripts assume `uv` for
# venv + dependency resolution. Sourced from the named `uv-stage` at
@@ -142,9 +160,11 @@ COPY server/docker/agent-computer-cumora.sh /usr/local/bin/cumora
COPY server/docker/agent-computer-cumora-web.sh /usr/local/bin/cumora-web
RUN chmod +x /usr/local/bin/cumora /usr/local/bin/cumora-web /usr/local/bin/cumora-fuse
-# Entrypoint: mount FUSE first, then exec the agent loop.
+# Legacy path retained as the already-demoted supervisor. It rejects direct
+# root invocation; only the bootstrap may invoke it after setpriv.
COPY server/docker/agent-computer-entrypoint.sh /usr/local/bin/agent-entrypoint
-RUN chmod +x /usr/local/bin/agent-entrypoint
+COPY server/docker/agent-computer-bootstrap.sh /usr/local/bin/cumora-agent-bootstrap
+RUN chmod +x /usr/local/bin/agent-entrypoint /usr/local/bin/cumora-agent-bootstrap
# Env contract — orchestrator injects all of these at pod-spawn time:
# CUMORA_AGENT_ID which agent to wake
@@ -156,8 +176,16 @@ RUN chmod +x /usr/local/bin/agent-entrypoint
ENV CUMORA_RUNTIME_CLIENT=http \
NODE_ENV=production \
DISPLAY=:99 \
+ HOME=/home/cumora-agent \
+ USER=cumora-agent \
+ LOGNAME=cumora-agent \
+ XDG_CONFIG_HOME=/home/cumora-agent/.config \
+ XDG_CACHE_HOME=/home/cumora-agent/.cache \
+ XDG_RUNTIME_DIR=/run/user/65532 \
OPENCLI_EXTENSION_DIR=/opt/opencli-extension \
CHROME_PROFILE_DIR=/opt/chrome-profile \
CHROMIUM_BIN=/usr/bin/chromium
-ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agent-entrypoint"]
+# Do not add an outer root tini. The bootstrap is the trusted PID 1 and
+# execs setpriv -> tini after FUSE has reported READY.
+ENTRYPOINT ["/usr/local/bin/cumora-agent-bootstrap"]
diff --git a/server/docker/agent-computer.Dockerfile.dockerignore b/server/docker/agent-computer.Dockerfile.dockerignore
index 9a3cc29..7a08736 100644
--- a/server/docker/agent-computer.Dockerfile.dockerignore
+++ b/server/docker/agent-computer.Dockerfile.dockerignore
@@ -6,4 +6,5 @@
!server/docker/agent-computer-cumora.sh
!server/docker/agent-computer-cumora-web.sh
!server/docker/agent-computer-entrypoint.sh
+!server/docker/agent-computer-bootstrap.sh
!agent-fuse/**
diff --git a/server/k8s/cumora-agent-network-policy.yaml b/server/k8s/cumora-agent-network-policy.yaml
new file mode 100644
index 0000000..b3b40f0
--- /dev/null
+++ b/server/k8s/cumora-agent-network-policy.yaml
@@ -0,0 +1,115 @@
+# Pre-deploy these policies in the namespace selected by
+# CUMORA_AGENT_NAMESPACE. They are intentionally separate from the server
+# Deployment manifest so the same server image can target an explicitly
+# chosen agent namespace without silently moving existing PVCs.
+# The server namespace selector below defaults to `default`; if trusted
+# cumora-server Pods live elsewhere, update it and set
+# CUMORA_AGENT_SERVER_NAMESPACE on the server Deployment.
+#
+# Example:
+# kubectl apply -n "$CUMORA_AGENT_NAMESPACE" \
+# -f server/k8s/cumora-agent-network-policy.yaml
+#
+# The orchestrator only reads and validates these objects. It never applies
+# them at wake time. NetworkPolicy enforcement is asynchronous and depends
+# on the cluster CNI; see server/k8s/gke.md for the required CNI checks. Both
+# objects select only `app=cumora-agent`, so server/Redis/other Pods in a
+# shared namespace are outside this policy set.
+---
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: cumora-agent-default-deny
+ labels:
+ cumora.dev/security-profile: fuse-demoted-v1
+ cumora.dev/network-policy-version: v1
+spec:
+ podSelector:
+ matchLabels:
+ app: cumora-agent
+ policyTypes:
+ - Ingress
+ - Egress
+---
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: cumora-agent-egress
+ labels:
+ cumora.dev/security-profile: fuse-demoted-v1
+ cumora.dev/network-policy-version: v1
+spec:
+ podSelector:
+ matchLabels:
+ app: cumora-agent
+ policyTypes:
+ - Egress
+ egress:
+ # Cluster DNS. If the CNI uses a different DNS label, update this peer
+ # explicitly and update the orchestrator's policy contract together.
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: kube-system
+ podSelector:
+ matchLabels:
+ k8s-app: kube-dns
+ ports:
+ - protocol: UDP
+ port: 53
+ - protocol: TCP
+ port: 53
+ # The in-cluster runtime server. Replace the namespace label when
+ # CUMORA_AGENT_SERVER_NAMESPACE is changed.
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: default
+ podSelector:
+ matchLabels:
+ app: cumora-server
+ ports:
+ - protocol: TCP
+ port: 5181
+ # Public IPv4 Web only. RFC1918, CGNAT, loopback, link-local, metadata,
+ # documentation, multicast, and reserved ranges stay excluded.
+ - to:
+ - ipBlock:
+ cidr: 0.0.0.0/0
+ except:
+ - 0.0.0.0/8
+ - 10.0.0.0/8
+ - 100.64.0.0/10
+ - 127.0.0.0/8
+ - 169.254.0.0/16
+ - 172.16.0.0/12
+ - 192.0.0.0/24
+ - 192.0.2.0/24
+ - 192.168.0.0/16
+ - 198.18.0.0/15
+ - 198.51.100.0/24
+ - 203.0.113.0/24
+ - 224.0.0.0/4
+ - 240.0.0.0/4
+ ports:
+ - protocol: TCP
+ port: 80
+ - protocol: TCP
+ port: 443
+ # Public IPv6 Web only. ULA/private, link-local, loopback, multicast,
+ # and documentation ranges stay excluded when the CNI supports IPv6.
+ - to:
+ - ipBlock:
+ cidr: ::/0
+ except:
+ - ::/128
+ - ::1/128
+ - fc00::/7
+ - fe80::/10
+ - ff00::/8
+ - 2001:db8::/32
+ ports:
+ - protocol: TCP
+ port: 80
+ - protocol: TCP
+ port: 443
diff --git a/server/k8s/cumora-server.gke.yaml b/server/k8s/cumora-server.gke.yaml
index b63bb3d..0d84e56 100644
--- a/server/k8s/cumora-server.gke.yaml
+++ b/server/k8s/cumora-server.gke.yaml
@@ -58,6 +58,11 @@ rules:
- apiGroups: [""]
resources: ["persistentvolumeclaims"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
+# The orchestrator reads the pre-deployed agent NetworkPolicies before it
+# creates or reuses a Pod. It never grants itself policy mutation rights.
+- apiGroups: ["networking.k8s.io"]
+ resources: ["networkpolicies"]
+ verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
@@ -142,6 +147,13 @@ spec:
# sure the Role above is bound in THAT namespace too.
- name: CUMORA_AGENT_NAMESPACE
value: "default"
+ # Namespace containing the trusted server Pods selected by the agent
+ # NetworkPolicy. Keep explicit when agents move to a dedicated ns.
+ - name: CUMORA_AGENT_SERVER_NAMESPACE
+ value: "default"
+ # Pre-deploy server/k8s/cumora-agent-network-policy.yaml in this
+ # namespace. The orchestrator checks its v1 objects and fails closed;
+ # it does not apply policies or infer URL-specific exceptions.
# Image for agent-computer pods. Must be pushed to a registry
# reachable from the cluster (and pull-secret-able if private).
- name: CUMORA_AGENT_COMPUTER_IMAGE
@@ -152,9 +164,11 @@ spec:
# spec. Comma-separated. Must exist in CUMORA_AGENT_NAMESPACE.
- name: CUMORA_AGENT_PULL_SECRETS
value: "quay-pull"
- # Optional: pin agent pods to a specific node pool / GKE
- # Workload Identity SA via CUMORA_AGENT_SERVICE_ACCOUNT
- # (defaults to namespace `default` SA when unset).
+ # Optional: pin agent Pods to a specific ServiceAccount identity via
+ # CUMORA_AGENT_SERVICE_ACCOUNT. Agent Pod token automount stays off;
+ # that only suppresses the projected Kubernetes token. GCP Workload
+ # Identity/metadata credentials remain a separate runtime/CNI/operator
+ # policy decision.
# Startup waits for the schema gate's bounded DB retry budget. Liveness
# only checks the process; readiness checks DB reachability and keeps a
# booting or degraded pod out of service without killing it.
diff --git a/server/k8s/cumora-server.orbstack.yaml b/server/k8s/cumora-server.orbstack.yaml
index 0ad6ee8..b1a7ff1 100644
--- a/server/k8s/cumora-server.orbstack.yaml
+++ b/server/k8s/cumora-server.orbstack.yaml
@@ -41,6 +41,17 @@ rules:
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get", "list"]
+# Per-agent Chromium profile PVCs outlive Pods so cookies/login state survive
+# an idle restart. Keep this namespace-local; never delete or recreate the
+# existing PVC as part of a Pod security upgrade.
+- apiGroups: [""]
+ resources: ["persistentvolumeclaims"]
+ verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
+# The orchestrator reads the pre-deployed agent NetworkPolicies before it
+# creates or reuses a Pod. It never grants itself policy mutation rights.
+- apiGroups: ["networking.k8s.io"]
+ resources: ["networkpolicies"]
+ verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
@@ -88,6 +99,13 @@ spec:
value: "http://cumora-server.default.svc.cluster.local:5181/runtime"
- name: CUMORA_AGENT_NAMESPACE
value: "default"
+ # Namespace containing the trusted server Pods selected by the agent
+ # NetworkPolicy. Keep explicit when agents move to a dedicated ns.
+ - name: CUMORA_AGENT_SERVER_NAMESPACE
+ value: "default"
+ # Pre-deploy server/k8s/cumora-agent-network-policy.yaml in this
+ # namespace. The orchestrator checks its v1 objects and fails closed;
+ # it does not apply policies or infer URL-specific exceptions.
- name: WORKSPACE_RUNTIME_CLEANUP_ENABLED
value: "true"
# In-cluster PG is also reachable via the service URL above
diff --git a/server/k8s/generic-device-plugin.note b/server/k8s/generic-device-plugin.note
index 0cb8b09..89767e7 100644
--- a/server/k8s/generic-device-plugin.note
+++ b/server/k8s/generic-device-plugin.note
@@ -26,8 +26,12 @@
# # Should show `devic.es/fuse: 800` under Allocatable.
#
# The agent Pod manifest (orchestrator.ts) requests this resource
-# via `resources.limits["devic.es/fuse"]: 1` and adds CAP_SYS_ADMIN.
-# No `privileged: true`. Runtime admission still applies the lower
+# via `resources.limits["devic.es/fuse"]: 1` and starts the trusted
+# bootstrap as root with the exact temporary capabilities
+# `SYS_ADMIN, SETUID, SETGID, SETPCAP, KILL`; it also drops `ALL` and
+# sets `RuntimeDefault` seccomp. The bootstrap must then exec the
+# capability-free, `NoNewPrivs=1` UID/GID 65532 supervisor. No
+# `privileged: true`. Runtime admission still applies the lower
# app-level AGENT_POD_ADMISSION_MAX cap (default 40), so this device
# count is not the effective production pod ceiling.
#
diff --git a/server/k8s/gke.md b/server/k8s/gke.md
index 54a8423..1e9e519 100644
--- a/server/k8s/gke.md
+++ b/server/k8s/gke.md
@@ -205,13 +205,102 @@ CPU, memory, API-server, and provider concurrency budget.
> `ClusterRoleBinding` for `nodes: [get, list]` is added, only
> `AGENT_POD_ADMISSION_MAX` actually bounds admission.
-On **GKE Autopilot**: the plugin DaemonSet works but Autopilot may
-reject `securityContext.capabilities.add: [SYS_ADMIN]` depending on
-admission policy. If so, switch to **GKE Standard**, OR fall back
-to `privileged: true` (Autopilot allows it for explicit workloads
-with extra annotations — read the Autopilot security docs).
+On **GKE Autopilot**: the agent Pod needs the checked-in FUSE capability
+envelope and `AppArmor: Unconfined` for the mount phase. If Autopilot rejects
+that envelope, use a GKE **Standard** node pool or stop the agent deployment;
+do not silently change the Pod to `privileged: true` or claim that a restricted
+profile preserves the FUSE contract.
+
+## 6. Agent policy and runtime security prerequisites
+
+The agent image and Pod use a short trusted bootstrap phase. The Pod starts
+`/usr/local/bin/cumora-agent-bootstrap` as UID/GID `0:0` with the exact
+bootstrap capability set `SYS_ADMIN, SETUID, SETGID, SETPCAP, KILL`; its
+container and Pod templates drop `ALL`, use `RuntimeDefault` seccomp, disable
+service-account-token mounting, and set `fsGroup: 65532`. The bootstrap must
+mount FUSE, verify readiness, then exec the demoted supervisor. Long-lived
+Node, browser, Xvfb, OpenCLI, and PID 1 processes must be UID/GID `65532:65532`
+with empty capability sets and `NoNewPrivs=1`; `allowPrivilegeEscalation: false`
+and `SYS_ADMIN` in the initial template do not prove that post-bootstrap state.
+AppArmor remains `Unconfined` because GKE's default profile blocks the FUSE
+mount syscall. This is a FUSE prerequisite, not a claim that the Pod is
+restricted during the mount phase.
+
+Pre-deploy the policy bundle in the exact namespace configured by
+`CUMORA_AGENT_NAMESPACE` and before waking any managed agent:
-## 6. Apply the manifest
+```sh
+AGENT_NS=default # must equal the server Deployment env
+kubectl apply -n "$AGENT_NS" -f server/k8s/cumora-agent-network-policy.yaml
+kubectl get networkpolicy -n "$AGENT_NS" \
+ cumora-agent-default-deny cumora-agent-egress
+```
+
+The server Role only has `get/list/watch` on `networkpolicies`; the agent Pod
+does not receive the projected Kubernetes API token and cannot mutate policy.
+That setting does not by itself suppress GCP Workload Identity or metadata
+credentials; those require separate runtime, CNI, and operator controls. The
+orchestrator checks the actual objects, labels, selectors, policy version,
+DNS/server ports, and public Web
+CIDR exclusions before creating or reusing a Pod. Missing or malformed policy
+objects fail closed. Both policies select only `app=cumora-agent`; the
+default-deny object therefore leaves server, Redis, and other namespace Pods
+outside its scope. The bundle permits DNS UDP/TCP 53, the trusted
+`kubernetes.io/metadata.name` namespace plus `app=cumora-server` on TCP 5181,
+and public TCP 80/443. Set `CUMORA_AGENT_SERVER_NAMESPACE` to the namespace
+whose `app=cumora-server` Pods are trusted, and update the server namespace
+selector in the policy bundle when that namespace differs from the agent
+namespace. IPv4 RFC1918, CGNAT, loopback, link-local, metadata,
+documentation, multicast, and reserved ranges are excluded. IPv6 excludes
+loopback, ULA/private, link-local, multicast, and documentation ranges.
+There is no automatic exception for `OPENAI_BASE_URL`, model URLs, or other
+per-user configuration; an operator exception must be an explicit reviewed
+NetworkPolicy change.
+
+NetworkPolicy objects are additive, enforcement is asynchronous, and a cluster
+without a NetworkPolicy-capable CNI ignores these manifests. Before enabling
+agents, verify the CNI's NetworkPolicy support and test from an ephemeral
+agent-like Pod in this namespace: DNS works, the server service on 5181 works,
+public HTTPS works, and RFC1918/metadata destinations fail. `kubectl apply`
+success alone is not enforcement evidence. This repository has no claim that
+OrbStack or this workstation has verified production CNI behavior.
+
+## 7. Existing Pods and Chrome PVC migration
+
+The orchestrator reuses a Running/Pending Pod only after parsing its live API
+object and matching the security profile label, exact bootstrap command and
+image, root bootstrap identity, capability set, seccomp/AppArmor, token
+automount setting, and `fsGroup`. A legacy or unknown Pod is deleted and
+confirmed absent with a bounded wait before a replacement is created; a timeout
+fails closed. It preserves the existing namespace, placement, tenant, capacity
+checks, and Chrome PVC. It never starts a second Pod with the same agent name
+while the old immutable object remains.
+
+The UID change leaves existing Chrome PVC data in place. Kubernetes storage
+drivers may apply `fsGroup` at mount time, but hostPath/local drivers often do
+not. For each existing PVC, first verify in the configured agent namespace
+that the mounted profile is readable and writable by UID/GID `65532:65532` and
+that Chromium can open the old profile. If the driver does not honor fsGroup,
+use a reviewed, offline operator migration that preserves the PVC and backup;
+do not recursively `chown` attacker-writable profile data in the bootstrap,
+delete the PVC, clear cookies, or move it to another namespace. A failed
+permission check must stop the rollout until the storage migration is done.
+
+For a manual upgrade, inspect one old Pod and PVC first, delete only that Pod,
+wait for its name to disappear, then let the next wake create the new template:
+
+```sh
+kubectl get pod -n "$AGENT_NS" agent-<id> -o yaml
+kubectl get pvc -n "$AGENT_NS" agent-<id>-chrome -o yaml
+kubectl delete pod -n "$AGENT_NS" agent-<id> --wait=true --timeout=30s
+kubectl wait -n "$AGENT_NS" --for=delete pod/agent-<id> --timeout=60s
+```
+
+Do not run a production-wide cleanup as part of this change. Roll out one
+agent, verify FUSE/browser/runtime and PVC behavior, then proceed using the
+normal capacity and placement controls.
+
+## 8. Apply the manifest
After replacing `REPLACE-*` placeholders in
`server/k8s/cumora-server.gke.yaml`:
@@ -240,7 +329,7 @@ Deploy workflow reapplies the same probe contract during its Pod-template
patch, so a manual `kubectl apply` does not require a follow-up imperative
probe patch.
-## 7. Verify end-to-end
+## 9. Verify end-to-end
```sh
# Server pods running, both 2/2 containers ready
diff --git a/server/scripts/agent-boundary-smoke.mjs b/server/scripts/agent-boundary-smoke.mjs
new file mode 100644
index 0000000..15bedcd
--- /dev/null
+++ b/server/scripts/agent-boundary-smoke.mjs
@@ -0,0 +1,540 @@
+#!/usr/bin/env node
+/*
+ * Linux Docker smoke for SEC-10/TST-C3.
+ *
+ * The image and entrypoint are real. Only /app/agent-computer.cjs and the
+ * runtime HTTP surface are replaced with local fixtures, so this never calls
+ * a real account, model provider, or Cumora deployment.
+ */
+import { createInterface } from 'node:readline'
+import { readFile, mkdir, writeFile } from 'node:fs/promises'
+import { existsSync } from 'node:fs'
+import { spawn, execFileSync } from 'node:child_process'
+import { randomBytes } from 'node:crypto'
+import { dirname, resolve } from 'node:path'
+
+const repoRoot = resolve(dirname(new URL(import.meta.url).pathname), '../..')
+const fixtureLoop = resolve(repoRoot, 'server/scripts/fixtures/agent-boundary-loop.cjs')
+const fixtureBackend = resolve(repoRoot, 'server/scripts/fixtures/agent-boundary-backend.py')
+const image = process.env.CUMORA_AGENT_BOUNDARY_IMAGE ?? process.argv[2]
+const smokeId = randomBytes(5).toString('hex')
+const reportDir = resolve(
+ process.env.CUMORA_AGENT_BOUNDARY_REPORT_DIR ?? `/tmp/cumora-agent-boundary-smoke-${smokeId}`,
+)
+const reportPath = resolve(reportDir, 'report.json')
+const token = 'local-boundary-fixture-token'
+const containerPrefix = `cumora-boundary-smoke-${process.pid}-${smokeId}`
+const containers = []
+const volumes = []
+const report = {
+ image,
+ reportDir,
+ checks: {},
+ failures: [],
+}
+
+if (!image) {
+ console.error('usage: node server/scripts/agent-boundary-smoke.mjs IMAGE[:TAG]')
+ process.exit(2)
+}
+
+await mkdir(reportDir, { recursive: true })
+
+function decode(value) {
+ return Buffer.isBuffer(value) ? value.toString('utf8') : String(value ?? '')
+}
+
+function docker(args, options = {}) {
+ try {
+ const stdout = execFileSync('docker', args, {
+ encoding: 'utf8',
+ timeout: options.timeout ?? 20_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ return { status: 0, stdout: decode(stdout), stderr: '' }
+ } catch (error) {
+ return {
+ status: Number.isInteger(error.status) ? error.status : 1,
+ stdout: decode(error.stdout),
+ stderr: decode(error.stderr),
+ }
+ }
+}
+
+function check(name, passed, detail = undefined) {
+ const entry = { passed: Boolean(passed) }
+ if (detail !== undefined) entry.detail = detail
+ report.checks[name] = entry
+ if (!passed) report.failures.push(name)
+}
+
+function inspect(name) {
+ const result = docker(['inspect', '-f', '{{.State.Status}} {{.State.ExitCode}}', name])
+ if (result.status !== 0) return { status: 'missing', exitCode: null }
+ const [status, exitCode] = result.stdout.trim().split(/\s+/)
+ return { status, exitCode: Number(exitCode) }
+}
+
+function execIn(name, args, user = 0, timeout = 20_000) {
+ return docker(['exec', '--user', String(user), name, ...args], { timeout })
+}
+
+function logs(name) {
+ return docker(['logs', name], { timeout: 10_000 })
+}
+
+async function waitFor(predicate, timeoutMs = 60_000, intervalMs = 250) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const result = await predicate()
+ if (result) return result
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, intervalMs))
+ }
+ return false
+}
+
+async function readJson(path) {
+ try {
+ return JSON.parse(await readFile(path, 'utf8'))
+ } catch {
+ return {}
+ }
+}
+
+function parseStatus(text) {
+ const out = {}
+ for (const line of text.split('\n')) {
+ const match = line.match(/^([^:]+):\s*(.*)$/)
+ if (match) out[match[1]] = match[2].trim()
+ }
+ return out
+}
+
+function parseProcessList(text) {
+ return text
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => {
+ const match = line.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/)
+ if (!match) return null
+ return {
+ pid: Number(match[1]),
+ ppid: Number(match[2]),
+ uid: Number(match[3]),
+ gid: Number(match[4]),
+ command: match[5],
+ }
+ })
+ .filter(Boolean)
+}
+
+async function startContainer({ name, capabilities, profileVolume = undefined, startupSupervisor = undefined, startupBarrier = undefined }) {
+ containers.push(name)
+ const statePath = resolve(reportDir, `${name}.backend.json`)
+ const args = [
+ 'run',
+ '--detach',
+ '--name',
+ name,
+ '--label',
+ `io.cumora.agent-boundary-smoke=${smokeId}`,
+ '--device',
+ '/dev/fuse',
+ '--cap-drop',
+ 'ALL',
+ ...capabilities.flatMap((capability) => ['--cap-add', capability]),
+ '--security-opt',
+ 'apparmor=unconfined',
+ '--add-host',
+ 'host.docker.internal:host-gateway',
+ '-v',
+ `${fixtureLoop}:/app/agent-computer.cjs:ro`,
+ ...(startupSupervisor ? ['-v', `${startupSupervisor}:/usr/local/bin/agent-entrypoint:ro`] : []),
+ ...(profileVolume ? ['-v', `${profileVolume}:/opt/chrome-profile`] : []),
+ '-e',
+ `CUMORA_AGENT_RUNTIME_URL=http://host.docker.internal:${backendPort}/runtime`,
+ '-e',
+ `CUMORA_AGENT_RUNTIME_TOKEN=${token}`,
+ ...(startupBarrier ? ['-e', `CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER=${startupBarrier}`] : []),
+ '-e',
+ 'CUMORA_AGENT_ID=boundary-fixture',
+ image,
+ ]
+ const result = docker(args, { timeout: 30_000 })
+ if (result.status !== 0) {
+ throw new Error(`docker run failed for ${name}: ${result.stderr.trim()}`)
+ }
+ return { statePath }
+}
+
+async function makeStartupBarrierSupervisor({ legacyTrap = false } = {}) {
+ const sourcePath = resolve(repoRoot, 'server/docker/agent-computer-entrypoint.sh')
+ let source = await readFile(sourcePath, 'utf8')
+ if (legacyTrap) source = source.replace('trap on_signal TERM INT', "trap 'EXIT_STATUS=143; shutdown' TERM INT")
+ const marker = '# The observer runs before any browser or model process.'
+ const markerIndex = source.indexOf(marker)
+ if (markerIndex < 0) throw new Error('startup barrier marker is missing from the real supervisor')
+ const barrierDir = `/tmp/${containerPrefix}-startup-barrier`
+ const barrierVariable = '$' + '{CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER:-}'
+ const barrier = `# Test-only barrier inserted by agent-boundary-smoke; the surrounding supervisor is verbatim product code.\nif [[ -n "${barrierVariable}" ]]; then\n mkdir -p "$CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER"\n rm -f "$CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER/release"\n mkfifo -m 0600 "$CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER/release"\n exec 9<>"$CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER/release"\n : >"$CUMORA_AGENT_BOUNDARY_STARTUP_BARRIER/ready"\n IFS= read -r _ <&9 || true\nfi\n\n`
+ const suffix = legacyTrap ? 'legacy-trap' : 'fixed-trap'
+ const path = resolve(reportDir, `${containerPrefix}-supervisor-with-${suffix}-barrier.sh`)
+ await writeFile(path, `${source.slice(0, markerIndex)}${barrier}${source.slice(markerIndex)}`, { mode: 0o755 })
+ return { path, barrierDir }
+}
+
+async function prepareFsGroupProfile() {
+ const profileVolume = `${containerPrefix}-chrome-profile`
+ const created = docker([
+ 'volume',
+ 'create',
+ '--label',
+ `io.cumora.agent-boundary-smoke=${smokeId}`,
+ profileVolume,
+ ])
+ if (created.status !== 0) throw new Error(`PVC fixture volume setup failed: ${created.stderr.trim()}`)
+ volumes.push(profileVolume)
+ // This is an isolated bind mount fixture, not a CSI or kubelet test. The
+ // helper container applies the same root-owned/group-writable shape that a
+ // Kubernetes fsGroup setup would expose to UID/GID 65532.
+ const prepare = docker([
+ 'run',
+ '--rm',
+ '--entrypoint',
+ '/bin/sh',
+ '-v',
+ `${profileVolume}:/profile`,
+ image,
+ '-c',
+ 'chown 0:65532 /profile && chmod 0770 /profile && printf legacy-profile-fixture >/profile/legacy-login.txt && chown 0:65532 /profile/legacy-login.txt && chmod 0660 /profile/legacy-login.txt',
+ ])
+ if (prepare.status !== 0) throw new Error(`fsGroup fixture setup failed: ${prepare.stderr.trim()}`)
+ return profileVolume
+}
+
+async function waitForProbe(name) {
+ return waitFor(async () => {
+ const state = inspect(name)
+ if (state.status === 'exited' || state.status === 'dead' || state.status === 'missing') return false
+ const output = execIn(name, ['test', '-s', '/tmp/cumora-agent-boundary-fixture.json'], 65532)
+ return output.status === 0
+ }, 90_000)
+}
+
+async function inspectThreads(name, processes) {
+ const violations = []
+ for (const process of processes) {
+ const expectedUid = process.command.includes('cumora-fuse') ? 65533 : 65532
+ const taskList = execIn(
+ name,
+ ['sh', '-c', `for path in /proc/${process.pid}/task/*/status; do echo TASK:$path; cat "$path"; done`],
+ 0,
+ )
+ if (taskList.status !== 0) {
+ // Chromium can retire a renderer between ps(1) and the status read.
+ // It is not a long-lived process left by the boundary; only retain a
+ // violation when the task still exists and remains unreadable.
+ const stillPresent = execIn(name, ['test', '-e', `/proc/${process.pid}/status`], 0)
+ if (stillPresent.status === 0) violations.push(`${process.pid}:status-unreadable`)
+ continue
+ }
+ const taskStatuses = []
+ let currentTask = null
+ let currentStatus = null
+ const validateCurrentTask = () => {
+ if (!currentTask || !currentStatus) return
+ const required = ['Uid', 'Gid', 'Groups', 'CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb', 'NoNewPrivs']
+ for (const key of required) {
+ if (!(key in currentStatus)) violations.push(`${process.pid}/${currentTask}:missing-${key}`)
+ }
+ for (const key of ['Uid', 'Gid']) {
+ const ids = (currentStatus[key] ?? '').split(/\s+/).filter(Boolean)
+ if (ids.length !== 4 || ids.some((id) => id !== String(expectedUid))) {
+ violations.push(`${process.pid}/${currentTask}:${key}`)
+ }
+ }
+ for (const key of ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb']) {
+ if (currentStatus[key] !== '0000000000000000') violations.push(`${process.pid}/${currentTask}:${key}`)
+ }
+ if (currentStatus.NoNewPrivs !== '1') violations.push(`${process.pid}/${currentTask}:NoNewPrivs`)
+ if (currentStatus.Groups !== '') violations.push(`${process.pid}/${currentTask}:Groups`)
+ taskStatuses.push(currentTask)
+ }
+ for (const line of taskList.stdout.split('\n')) {
+ if (line.startsWith('TASK:')) {
+ validateCurrentTask()
+ currentTask = line.slice(5)
+ currentStatus = {}
+ continue
+ }
+ const match = line.match(/^(Uid|Gid|Groups|CapInh|CapPrm|CapEff|CapBnd|CapAmb|NoNewPrivs):\s*(.*)$/)
+ if (!match) continue
+ const [key, value] = match.slice(1)
+ if (currentStatus) currentStatus[key] = value
+ }
+ validateCurrentTask()
+ if (taskStatuses.length === 0) violations.push(`${process.pid}:no-task-status`)
+ }
+ return violations
+}
+
+let backend
+let backendPort
+try {
+ backend = spawn('python3', [fixtureBackend, '--state', resolve(reportDir, 'backend-state.json')], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ const lines = createInterface({ input: backend.stdout })
+ backendPort = Number(
+ await new Promise((resolvePort, reject) => {
+ const timer = setTimeout(() => reject(new Error('fixture backend did not announce a port')), 10_000)
+ lines.once('line', (line) => {
+ clearTimeout(timer)
+ resolvePort(line)
+ })
+ backend.once('exit', (code) => reject(new Error(`fixture backend exited (${code})`)))
+ }),
+ )
+ if (!Number.isInteger(backendPort) || backendPort <= 0) throw new Error('invalid fixture backend port')
+
+ const imageCheck = docker(['image', 'inspect', image])
+ if (imageCheck.status !== 0) throw new Error(`image is unavailable: ${image}`)
+ check('image_available', true)
+ const directRootSupervisor = docker([
+ 'run',
+ '--rm',
+ '--entrypoint',
+ '/usr/local/bin/agent-entrypoint',
+ image,
+ ])
+ check('direct_root_supervisor_rejected', directRootSupervisor.status === 126)
+
+ // Read the real supervisor and insert a test-only FIFO barrier immediately
+ // after its signal trap. The image still uses the real bootstrap/entrypoint;
+ // the barrier simply makes the pre-browser/model signal window deterministic
+ // without adding a production sleep or test hook to the image.
+ const startupBarrier = await makeStartupBarrierSupervisor()
+ const startupName = `${containerPrefix}-bootstrap-signal`
+ await startContainer({
+ name: startupName,
+ capabilities: ['SYS_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'],
+ startupSupervisor: startupBarrier.path,
+ startupBarrier: startupBarrier.barrierDir,
+ })
+ const startupBarrierReady = await waitFor(async () => {
+ const ready = execIn(startupName, ['test', '-f', `${startupBarrier.barrierDir}/ready`], 65532)
+ return ready.status === 0
+ }, 30_000)
+ check('supervisor_startup_barrier_reached', startupBarrierReady)
+ if (startupBarrierReady) {
+ const startupProcesses = parseProcessList(execIn(startupName, ['ps', '-eo', 'pid=,ppid=,uid=,gid=,args='], 0).stdout)
+ check('startup_barrier_has_no_model_or_browser', !startupProcesses.some((process) => /\b(node|Xvfb|chromium|opencli)\b/.test(process.command)))
+ const startupTerm = execIn(startupName, ['kill', '-TERM', '1'], 65532)
+ check('supervisor_startup_signal_sent', startupTerm.status === 0)
+ }
+ const startupExited = await waitFor(() => {
+ const state = inspect(startupName)
+ return state.status === 'exited' || state.status === 'dead'
+ }, 30_000)
+ const startupState = inspect(startupName)
+ report.startupContainerState = startupState
+ check('supervisor_startup_signal_exits_nonzero_143', startupExited && startupState.exitCode === 143)
+ const startupFixturePath = resolve(reportDir, `${startupName}.fixture.json`)
+ const startupFixtureCopy = docker(['cp', `${startupName}:/tmp/cumora-agent-boundary-fixture.json`, startupFixturePath])
+ check('supervisor_startup_signal_does_not_start_model_fixture', startupFixtureCopy.status !== 0 && !existsSync(startupFixturePath))
+
+ // Run the identical barrier against a temporary copy of the pre-fix trap.
+ // It must continue into the model fixture after TERM, proving the fixed
+ // on_signal exit is what closes the race rather than a timing accident.
+ const legacyBarrier = await makeStartupBarrierSupervisor({ legacyTrap: true })
+ const legacyName = `${containerPrefix}-legacy-trap`
+ await startContainer({
+ name: legacyName,
+ capabilities: ['SYS_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'],
+ startupSupervisor: legacyBarrier.path,
+ startupBarrier: legacyBarrier.barrierDir,
+ })
+ const legacyBarrierReady = await waitFor(async () => {
+ const ready = execIn(legacyName, ['test', '-f', `${legacyBarrier.barrierDir}/ready`], 65532)
+ return ready.status === 0
+ }, 30_000)
+ check('legacy_trap_barrier_reached', legacyBarrierReady)
+ if (legacyBarrierReady) {
+ const legacyTerm = execIn(legacyName, ['kill', '-TERM', '1'], 65532)
+ check('legacy_trap_signal_sent', legacyTerm.status === 0)
+ const legacyRelease = execIn(legacyName, ['sh', '-c', `printf '%s\n' release > ${legacyBarrier.barrierDir}/release`], 65532)
+ check('legacy_trap_barrier_released', legacyRelease.status === 0)
+ const legacyFixtureStarted = await waitForProbe(legacyName)
+ check('legacy_trap_continues_into_model', legacyFixtureStarted)
+ if (legacyFixtureStarted) {
+ const legacyStop = execIn(legacyName, ['kill', '-TERM', '1'], 65532)
+ check('legacy_trap_cleanup_signal_sent', legacyStop.status === 0)
+ }
+ }
+ const legacyExited = await waitFor(() => {
+ const state = inspect(legacyName)
+ return state.status === 'exited' || state.status === 'dead'
+ }, 30_000)
+ report.legacyTrapContainerState = inspect(legacyName)
+ check('legacy_trap_container_cleaned', legacyExited)
+
+ const normalName = `${containerPrefix}-normal`
+ const profileVolume = await prepareFsGroupProfile()
+ await startContainer({
+ name: normalName,
+ capabilities: ['SYS_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'],
+ profileVolume,
+ })
+ const normalReady = await waitForProbe(normalName)
+ check('model_fixture_started', normalReady)
+ if (!normalReady) {
+ const containerLogs = logs(normalName)
+ throw new Error(`normal boundary container did not reach fixture: ${(containerLogs.stdout + containerLogs.stderr).trim()}`)
+ }
+
+ const fusePidResult = execIn(normalName, ['cat', '/run/cumora/fuse.pid'], 0)
+ const fusePid = fusePidResult.stdout.trim()
+ check('fuse_pid_file', fusePidResult.status === 0 && /^[1-9][0-9]*$/.test(fusePid))
+ if (!/^[1-9][0-9]*$/.test(fusePid)) throw new Error('FUSE pid file is unavailable')
+
+ const processResult = execIn(normalName, ['ps', '-eo', 'pid=,ppid=,uid=,gid=,args='], 0)
+ const processes = parseProcessList(processResult.stdout)
+ const persistentProcesses = processes.filter((process) => !/\bps -eo\b|^sleep\s/.test(process.command))
+ report.processes = processes
+ check('process_list_readable', processResult.status === 0 && processes.length > 0)
+ check('no_long_lived_root_process', persistentProcesses.every((process) => process.uid !== 0))
+ check('fuse_process_present', persistentProcesses.some((process) => String(process.pid) === fusePid))
+ const threadViolations = await inspectThreads(normalName, persistentProcesses)
+ report.threadViolations = threadViolations
+ check('all_threads_fixed_identity_caps_nnp', threadViolations.length === 0, threadViolations)
+
+ const mountInfo = execIn(normalName, ['sh', '-c', 'grep " /workspace " /proc/self/mountinfo'], 0)
+ check(
+ 'exact_fuse_mount',
+ mountInfo.status === 0 && / \/workspace .* - fuse\.cumora-workspace cumora-workspace /.test(mountInfo.stdout),
+ )
+ const workspaceStat = execIn(normalName, ['stat', '-c', '%u:%g:%a', '/workspace/probe.txt'], 65532)
+ check('fuse_owner_is_model', workspaceStat.stdout.trim().startsWith('65532:65532:'), workspaceStat.stdout.trim())
+ const fixtureReport = execIn(normalName, ['cat', '/tmp/cumora-agent-boundary-fixture.json'], 65532)
+ let fixtureProbe = {}
+ try {
+ fixtureProbe = JSON.parse(fixtureReport.stdout)
+ } catch {
+ fixtureProbe = {}
+ }
+ check('runtime_token_available_to_model_client', fixtureReport.status === 0 && fixtureProbe.runtimeTokenPresent === true)
+
+ const cdp = execIn(normalName, ['curl', '-fsS', 'http://127.0.0.1:9222/json/version'], 65532)
+ check('real_chromium_cdp', cdp.status === 0 && cdp.stdout.includes('webSocketDebuggerUrl'))
+ const doctor = execIn(normalName, ['sh', '-c', 'opencli doctor'], 65532, 30_000)
+ // OpenCLI writes human diagnostics to stderr in non-TTY docker execs. The
+ // successful exit is the stable contract; browser open/state below proves
+ // the daemon and extension are actually usable.
+ check('real_opencli_doctor', doctor.status === 0)
+ const open = execIn(normalName, ['sh', '-c', `opencli browser synthetic-agent open http://host.docker.internal:${backendPort}/`], 65532, 30_000)
+ const browserState = execIn(normalName, ['sh', '-c', 'opencli browser synthetic-agent state'], 65532, 30_000)
+ check('real_opencli_browser', open.status === 0 && browserState.status === 0)
+
+ const status1 = parseStatus(execIn(normalName, ['cat', '/proc/1/status'], 0).stdout)
+ check('pid1_is_nonroot_tini', status1.Name === 'tini' && status1.Uid?.split(/\s+/)[0] === '65532')
+ check('pid1_is_capless_nnp', ['CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb'].every((key) => status1[key] === '0000000000000000') && status1.NoNewPrivs === '1')
+
+ const modelMount = execIn(normalName, ['sh', '-c', 'mkdir -p /tmp/model-mount && mount -t tmpfs none /tmp/model-mount'], 65532)
+ check('model_cannot_mount', modelMount.status !== 0)
+ const modelSignal = execIn(normalName, ['sh', '-c', `kill -TERM ${fusePid}`], 65532)
+ check('model_cannot_signal_fuse', modelSignal.status !== 0)
+ const tokenRootProbe = execIn(normalName, ['test', '!', '-e', '/run/cumora/fuse-token'], 0)
+ check('token_deleted_after_ready_root_observer', tokenRootProbe.status === 0)
+ const tokenModelProbe = execIn(normalName, ['sh', '-c', 'cat /run/cumora/fuse-token >/dev/null'], 65532)
+ check('model_cannot_read_deleted_token', tokenModelProbe.status !== 0)
+ const fuseEnvProbe = execIn(normalName, ['sh', '-c', `cat /proc/${fusePid}/environ >/dev/null`], 65532)
+ check('model_cannot_read_fuse_environ', fuseEnvProbe.status !== 0)
+ const fuseArgv = execIn(normalName, ['sh', '-c', `tr "\\000" "\\n" </proc/${fusePid}/cmdline`], 0)
+ check('fuse_argv_readable_to_root_observer', fuseArgv.status === 0)
+ check('token_absent_from_fuse_argv', fuseArgv.status === 0 && !fuseArgv.stdout.includes(token))
+ const fuseEnv = execIn(normalName, ['sh', '-c', `tr "\\000" "\\n" </proc/${fusePid}/environ`], 0)
+ check('fuse_environ_readable_to_root_observer', fuseEnv.status === 0)
+ check('token_absent_from_fuse_environ', fuseEnv.status === 0 && !fuseEnv.stdout.includes(token))
+
+ const homeStats = execIn(normalName, ['stat', '-c', '%u:%g:%a', '/home/cumora-agent', '/opt/chrome-profile', '/run/user/65532'], 0)
+ const homeStatLines = homeStats.stdout.split('\n').filter(Boolean)
+ check('image_users_and_runtime_dirs', homeStats.status === 0 && homeStatLines[0]?.startsWith('65532:65532:') && homeStatLines[2]?.startsWith('65532:65532:'))
+ check('fsGroup_simulated_profile_owner_mode', homeStatLines[1] === '0:65532:770')
+ check('fsGroup_simulated_legacy_profile_readable', execIn(normalName, ['cat', '/opt/chrome-profile/legacy-login.txt'], 65532).stdout.trim() === 'legacy-profile-fixture')
+ const profileWrite = execIn(normalName, ['sh', '-c', 'printf fsGroup-write-fixture >/opt/chrome-profile/new-session.txt && test -s /opt/chrome-profile/new-session.txt'], 65532)
+ check('fsGroup_simulated_legacy_profile_writable', profileWrite.status === 0)
+
+ const normalStop = execIn(normalName, ['kill', '-TERM', '1'], 65532)
+ check('model_can_request_normal_stop', normalStop.status === 0)
+ const normalExited = await waitFor(() => {
+ const state = inspect(normalName)
+ return state.status === 'exited' || state.status === 'dead'
+ }, 60_000)
+ check('normal_stop_exits_container', normalExited)
+ const normalState = inspect(normalName)
+ report.normalContainerState = normalState
+ check('normal_stop_nonzero_exit', normalState.exitCode !== 0)
+ const normalFiles = await readJson(resolve(reportDir, 'backend-state.json'))
+ report.normalBackendFiles = normalFiles
+ check('backend_probe_write_persisted', normalFiles['probe.txt'] === 'fuse-fixture')
+ check('backend_probe_fsync_persisted', normalFiles['probe-fsync.txt'] === 'fsync-fixture')
+ check('normal_stop_final_fsync_persisted', normalFiles['final-stop.txt'] === 'final-fsync-fixture')
+
+ const failureName = `${containerPrefix}-fuse-failure`
+ await startContainer({
+ name: failureName,
+ capabilities: ['SYS_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'],
+ })
+ const failureReady = await waitForProbe(failureName)
+ check('failure_fixture_started', failureReady)
+ if (failureReady) {
+ const failurePidResult = execIn(failureName, ['cat', '/run/cumora/fuse.pid'], 0)
+ const failurePid = failurePidResult.stdout.trim()
+ const killFuse = execIn(failureName, ['kill', '-TERM', failurePid], 0)
+ check('root_can_trigger_fuse_failure', killFuse.status === 0)
+ const failureExited = await waitFor(() => {
+ const state = inspect(failureName)
+ return state.status === 'exited' || state.status === 'dead'
+ }, 60_000)
+ const failureState = inspect(failureName)
+ report.failureContainerState = failureState
+ check('fuse_failure_ends_container', failureExited)
+ check('fuse_failure_nonzero_exit_70', failureState.exitCode === 70)
+ const markerPath = resolve(reportDir, `${failureName}.marker`)
+ const copiedMarker = docker(['cp', `${failureName}:/tmp/cumora-fuse-supervisor-failure`, markerPath])
+ let markerText = ''
+ if (copiedMarker.status === 0 && existsSync(markerPath)) markerText = await readFile(markerPath, 'utf8')
+ check('fuse_failure_reason_recorded', copiedMarker.status === 0 && /reason=/.test(markerText))
+ }
+
+ for (const missing of ['SYS_ADMIN', 'SETPCAP']) {
+ const name = `${containerPrefix}-missing-${missing.toLowerCase()}`
+ const capabilities = ['SETUID', 'SETGID', 'KILL']
+ if (missing !== 'SYS_ADMIN') capabilities.push('SYS_ADMIN')
+ if (missing !== 'SETPCAP') capabilities.push('SETPCAP')
+ await startContainer({ name, capabilities })
+ const exited = await waitFor(() => {
+ const state = inspect(name)
+ return state.status === 'exited' || state.status === 'dead'
+ }, 30_000)
+ const output = logs(name)
+ const missingState = inspect(name)
+ check(`missing_${missing.toLowerCase()}_fails_closed`, exited && missingState.exitCode !== 0 && !output.stdout.includes('BOUNDARY_PROBE'))
+ report[`missing_${missing.toLowerCase()}_state`] = missingState
+ }
+} catch (error) {
+ report.error = error instanceof Error ? error.message : String(error)
+ report.failures.push('smoke_execution')
+} finally {
+ for (const name of containers) docker(['rm', '--force', name], { timeout: 20_000 })
+ for (const volume of volumes) docker(['volume', 'rm', '--force', volume], { timeout: 20_000 })
+ if (backend && !backend.killed) backend.kill('SIGTERM')
+ await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8')
+}
+
+if (report.failures.length > 0) {
+ console.error(`agent-boundary-smoke: FAIL (${report.failures.join(', ')}) report=${reportPath}`)
+ process.exit(1)
+}
+console.log(`agent-boundary-smoke: PASS report=${reportPath}`)
diff --git a/server/scripts/fixtures/agent-boundary-backend.py b/server/scripts/fixtures/agent-boundary-backend.py
new file mode 100644
index 0000000..693b56e
--- /dev/null
+++ b/server/scripts/fixtures/agent-boundary-backend.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""Small local-only /runtime/fs fixture for the agent image boundary smoke.
+
+It intentionally has no authentication, account, or model integration. The
+smoke passes a throwaway token so the real image exercises token-file handling
+without contacting a Cumora deployment.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import threading
+import urllib.parse
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+
+class FixtureState:
+ def __init__(self, state_path: Path) -> None:
+ self.files: dict[str, str] = {}
+ self.lock = threading.Lock()
+ self.state_path = state_path
+
+ def snapshot(self) -> None:
+ self.state_path.write_text(
+ json.dumps(self.files, sort_keys=True), encoding="utf-8"
+ )
+
+
+class Handler(BaseHTTPRequestHandler):
+ state: FixtureState
+
+ def log_message(self, *_args: object) -> None:
+ # Keep smoke output free of request data and token-bearing headers.
+ return
+
+ def reply(self, status: int, value: object) -> None:
+ body = json.dumps(value, sort_keys=True).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def request_path(self) -> str:
+ query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
+ return query.get("path", [""])[0]
+
+ def do_GET(self) -> None: # noqa: N802
+ url_path = urllib.parse.urlsplit(self.path).path
+ path = self.request_path()
+ with self.state.lock:
+ if url_path == "/runtime/fs/stat":
+ if path == "":
+ return self.reply(200, {"exists": True, "isDir": True, "size": 0})
+ value = self.state.files.get(path)
+ return self.reply(
+ 200,
+ {"exists": value is not None, "isDir": False, "size": len(value or "")},
+ )
+ if url_path == "/runtime/fs/read":
+ if path not in self.state.files:
+ return self.reply(404, {})
+ return self.reply(200, {"body": self.state.files[path]})
+ if url_path == "/runtime/fs/list":
+ prefix = f"{path}/" if path else ""
+ names: set[str] = set()
+ for key in self.state.files:
+ if key.startswith(prefix):
+ remainder = key[len(prefix) :]
+ if remainder:
+ names.add(remainder.split("/", 1)[0])
+ return self.reply(
+ 200,
+ {
+ "entries": [
+ {"name": name, "isDir": False} for name in sorted(names)
+ ]
+ },
+ )
+ return self.reply(404, {})
+
+ def do_PUT(self) -> None: # noqa: N802
+ url_path = urllib.parse.urlsplit(self.path).path
+ if url_path != "/runtime/fs/write":
+ return self.reply(404, {})
+ try:
+ length = int(self.headers.get("Content-Length", "0"))
+ value = json.loads(self.rfile.read(length))
+ path = value["path"]
+ body = value["body"]
+ if not isinstance(path, str) or not isinstance(body, str) or not path:
+ raise ValueError("invalid fixture write")
+ except (ValueError, TypeError, KeyError, json.JSONDecodeError):
+ return self.reply(400, {})
+ with self.state.lock:
+ self.state.files[path] = body
+ self.state.snapshot()
+ return self.reply(200, {"ok": True})
+
+ def do_DELETE(self) -> None: # noqa: N802
+ url_path = urllib.parse.urlsplit(self.path).path
+ if url_path != "/runtime/fs/unlink":
+ return self.reply(404, {})
+ path = self.request_path()
+ with self.state.lock:
+ self.state.files.pop(path, None)
+ self.state.snapshot()
+ return self.reply(200, {"ok": True})
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--port", type=int, default=0)
+ parser.add_argument("--state", type=Path, required=True)
+ args = parser.parse_args()
+ args.state.unlink(missing_ok=True)
+ state = FixtureState(args.state)
+ Handler.state = state
+ server = ThreadingHTTPServer(("0.0.0.0", args.port), Handler)
+ print(server.server_port, flush=True)
+ try:
+ server.serve_forever()
+ finally:
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/server/scripts/fixtures/agent-boundary-loop.cjs b/server/scripts/fixtures/agent-boundary-loop.cjs
new file mode 100644
index 0000000..45bfc22
--- /dev/null
+++ b/server/scripts/fixtures/agent-boundary-loop.cjs
@@ -0,0 +1,46 @@
+const fs = require('node:fs')
+
+function procStatus() {
+ const source = fs.readFileSync('/proc/self/status', 'utf8')
+ const status = {}
+ for (const key of ['Uid', 'Gid', 'CapInh', 'CapPrm', 'CapEff', 'CapBnd', 'CapAmb', 'NoNewPrivs']) {
+ status[key] = source.match(new RegExp(`^${key}:\\s+([^\\n]+)$`, 'm'))?.[1]?.trim() ?? ''
+ }
+ return status
+}
+
+function writeAndFsync(path, body) {
+ const fd = fs.openSync(path, 'w', 0o644)
+ try {
+ fs.writeSync(fd, body)
+ fs.fsyncSync(fd)
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+
+writeAndFsync('/workspace/probe.txt', 'fuse-fixture')
+writeAndFsync('/workspace/probe-fsync.txt', 'fsync-fixture')
+const probe = {
+ uid: process.getuid(),
+ gid: process.getgid(),
+ runtimeTokenPresent: typeof process.env.CUMORA_AGENT_RUNTIME_TOKEN === 'string' && process.env.CUMORA_AGENT_RUNTIME_TOKEN.length > 0,
+ status: procStatus(),
+ read: fs.readFileSync('/workspace/probe.txt', 'utf8'),
+ fsyncRead: fs.readFileSync('/workspace/probe-fsync.txt', 'utf8'),
+ owner: `${fs.statSync('/workspace/probe.txt').uid}:${fs.statSync('/workspace/probe.txt').gid}`,
+}
+writeAndFsync('/tmp/cumora-agent-boundary-fixture.json', JSON.stringify(probe))
+console.log(`BOUNDARY_PROBE ${JSON.stringify(probe)}`)
+
+let stopping = false
+function stop() {
+ if (stopping) return
+ stopping = true
+ writeAndFsync('/workspace/final-stop.txt', 'final-fsync-fixture')
+ console.log('BOUNDARY_FINAL_FSYNC')
+ setTimeout(() => process.exit(0), 100)
+}
+process.on('SIGTERM', stop)
+process.on('SIGINT', stop)
+setInterval(() => {}, 1000)
diff --git a/server/src/__tests__/agent-computer-image.test.ts b/server/src/__tests__/agent-computer-image.test.ts
index b6e1150..fc6c1be 100644
--- a/server/src/__tests__/agent-computer-image.test.ts
+++ b/server/src/__tests__/agent-computer-image.test.ts
@@ -10,3 +10,31 @@ test('agent-computer image installs the shell and JSON tools required by the bas
assert.match(dockerfile, /apt-get install[\s\S]*\bbash\b/)
assert.match(dockerfile, /apt-get install[\s\S]*\bjq\b/)
})
+
+test('agent-computer uses the trusted bootstrap and a capless supervisor boundary', async () => {
+ const dockerfile = await readFile(
+ new URL('../../../server/docker/agent-computer.Dockerfile', import.meta.url),
+ 'utf8',
+ )
+ const bootstrap = await readFile(
+ new URL('../../../server/docker/agent-computer-bootstrap.sh', import.meta.url),
+ 'utf8',
+ )
+ const supervisor = await readFile(
+ new URL('../../../server/docker/agent-computer-entrypoint.sh', import.meta.url),
+ 'utf8',
+ )
+
+ assert.match(dockerfile, /apt-get install[\s\S]*\butil-linux\b/)
+ assert.match(dockerfile, /groupadd --gid 65532 cumora-agent/)
+ assert.match(dockerfile, /groupadd --gid 65533 cumora-fuse/)
+ assert.match(dockerfile, /ENTRYPOINT \["\/usr\/local\/bin\/cumora-agent-bootstrap"\]/)
+ assert.match(bootstrap, /--ready-fd 4/)
+ assert.match(bootstrap, /--lifetime-fd 5/)
+ assert.match(bootstrap, /env -u CUMORA_AGENT_RUNTIME_TOKEN/)
+ assert.match(bootstrap, /--bounding-set=-all/)
+ assert.match(bootstrap, /--no-new-privs/)
+ assert.match(supervisor, /refusing direct root invocation/)
+ assert.match(supervisor, /lifetime-eof/)
+ assert.match(supervisor, /fuse\.cumora-workspace/)
+})
diff --git a/server/src/__tests__/agents-orchestrator.test.ts b/server/src/__tests__/agents-orchestrator.test.ts
index 89d7e56..17ca96f 100644
--- a/server/src/__tests__/agents-orchestrator.test.ts
+++ b/server/src/__tests__/agents-orchestrator.test.ts
@@ -18,20 +18,34 @@
*
* Run: node --import tsx --test server/src/__tests__/agents-orchestrator.test.ts
*/
-import { test, after } from 'node:test'
import assert from 'node:assert/strict'
-import { pool } from '../db/pool.js'
+import { readFile } from 'node:fs/promises'
+import { dirname, resolve } from 'node:path'
+import { after, test } from 'node:test'
+import { fileURLToPath } from 'node:url'
+import { load, loadAll } from 'js-yaml'
import {
- parsePodHealth,
- stuckPendingReason,
- safeName,
- isRetryableKubectlError,
- planIdlePvcGc,
_testing,
+ isRetryableKubectlError,
type KubectlResult,
+ parsePodHealth,
+ planIdlePvcGc,
+ safeName,
+ stuckPendingReason,
+ waitForPodDeletion,
} from '../agents/runtime/orchestrator.js'
+import { pool } from '../db/pool.js'
+
+const {
+ yamlQuote,
+ dnsLabelValue,
+ podManifest,
+ isSecureManagedPod,
+ isRequiredAgentNetworkPolicy,
+} = _testing
-const { yamlQuote, dnsLabelValue, podManifest } = _testing
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
+const readRepo = (path: string): Promise<string> => readFile(resolve(repoRoot, path), 'utf8')
after(async () => {
// orchestrator.ts transitively imports inproc-client.ts → redis.ts
@@ -462,6 +476,254 @@ test('podManifest: well-formed inputs produce a parseable manifest with the slug
assert.match(m, /volumes:\n\s+- name: chrome-profile\n\s+persistentVolumeClaim:\n\s+claimName: "agent-iris-0c97-chrome"/)
})
+test('podManifest: parsed API shape contains the complete bootstrap security contract', () => {
+ const image = 'quay.io/img:security-test'
+ const manifest = podManifest({
+ agentId: 'iris-0c97',
+ token: 'jwt.token.part',
+ image,
+ serverUrl: 'http://server/runtime',
+ openaiKey: 'sk-test',
+ openaiBaseUrl: '',
+ idleMs: 600_000,
+ noWorkMs: 90_000,
+ })
+ const pod = load(manifest) as unknown
+ assert.equal(isSecureManagedPod(pod, image, 'iris-0c97'), true)
+ const root = pod as {
+ metadata?: { labels?: Record<string, string> }
+ spec?: {
+ automountServiceAccountToken?: boolean
+ securityContext?: {
+ runAsUser?: number
+ runAsGroup?: number
+ runAsNonRoot?: boolean
+ fsGroup?: number
+ seccompProfile?: { type?: string }
+ }
+ containers?: Array<{
+ command?: string[]
+ securityContext?: {
+ runAsUser?: number
+ runAsGroup?: number
+ capabilities?: { drop?: string[]; add?: string[] }
+ }
+ }>
+ }
+ }
+ assert.equal(root.metadata?.labels?.['cumora.dev/security-profile'], 'fuse-demoted-v1')
+ assert.equal(root.spec?.automountServiceAccountToken, false)
+ assert.equal(root.spec?.securityContext?.runAsUser, 0)
+ assert.equal(root.spec?.securityContext?.runAsGroup, 0)
+ assert.equal(root.spec?.securityContext?.fsGroup, 65532)
+ assert.equal(root.spec?.securityContext?.seccompProfile?.type, 'RuntimeDefault')
+ const security = root.spec?.containers?.[0]
+ assert.deepEqual(security?.command, ['/usr/local/bin/cumora-agent-bootstrap'])
+ assert.equal(security?.securityContext?.runAsUser, 0)
+ assert.equal(security?.securityContext?.runAsGroup, 0)
+ assert.deepEqual(security?.securityContext?.capabilities?.drop, ['ALL'])
+ assert.deepEqual(
+ [...(security?.securityContext?.capabilities?.add ?? [])].sort(),
+ ['KILL', 'SETGID', 'SETPCAP', 'SETUID', 'SYS_ADMIN'],
+ )
+})
+
+test('isSecureManagedPod: stale label and legacy command cannot be reused', () => {
+ const image = 'quay.io/img:security-test'
+ const pod = load(podManifest({
+ agentId: 'iris-0c97',
+ token: 'jwt',
+ image,
+ serverUrl: 'http://server/runtime',
+ openaiKey: 'sk-test',
+ openaiBaseUrl: '',
+ idleMs: 600_000,
+ noWorkMs: 90_000,
+ })) as Record<string, unknown>
+ const spec = pod.spec as Record<string, unknown>
+ const container = (spec.containers as Array<Record<string, unknown>>)[0]
+ container.command = ['/usr/local/bin/agent-computer-entrypoint.sh']
+ assert.equal(isSecureManagedPod(pod, image, 'iris-0c97'), false)
+})
+
+test('isSecureManagedPod: namespace/process/mount hooks cannot shadow the trusted bootstrap', () => {
+ const image = 'quay.io/img:security-test'
+ const secure = load(podManifest({
+ agentId: 'iris-0c97',
+ token: 'jwt',
+ image,
+ serverUrl: 'http://server/runtime',
+ openaiKey: 'sk-test',
+ openaiBaseUrl: '',
+ idleMs: 600_000,
+ noWorkMs: 90_000,
+ })) as Record<string, unknown>
+ const reject = (label: string, mutate: (pod: Record<string, unknown>) => void) => {
+ const candidate = structuredClone(secure) as Record<string, unknown>
+ mutate(candidate)
+ assert.equal(isSecureManagedPod(candidate, image, 'iris-0c97'), false, label)
+ }
+ const apiDefaulted = structuredClone(secure) as Record<string, unknown>
+ const apiDefaultedSpec = apiDefaulted.spec as Record<string, unknown>
+ for (const field of ['hostPID', 'hostIPC', 'hostNetwork', 'shareProcessNamespace']) delete apiDefaultedSpec[field]
+ assert.equal(isSecureManagedPod(apiDefaulted, image, 'iris-0c97'), true, 'API omission of default-false host fields remains secure')
+ const spec = (pod: Record<string, unknown>) => pod.spec as Record<string, unknown>
+ const container = (pod: Record<string, unknown>) => (spec(pod).containers as Array<Record<string, unknown>>)[0]
+ reject('host PID namespace is rejected', (pod) => { spec(pod).hostPID = true })
+ reject('host IPC namespace is rejected', (pod) => { spec(pod).hostIPC = true })
+ reject('host network namespace is rejected', (pod) => { spec(pod).hostNetwork = true })
+ reject('shared process namespace is rejected', (pod) => { spec(pod).shareProcessNamespace = true })
+ reject('init containers are rejected', (pod) => { spec(pod).initContainers = [{ name: 'shadow' }] })
+ reject('ephemeral containers are rejected', (pod) => { spec(pod).ephemeralContainers = [{ name: 'shadow' }] })
+ reject('container lifecycle hooks are rejected', (pod) => { container(pod).lifecycle = { postStart: { exec: { command: ['sh'] } } } })
+ reject('extra args are rejected', (pod) => { container(pod).args = ['--legacy'] })
+ reject('exec probes are rejected', (pod) => { container(pod).livenessProbe = { exec: { command: ['sh'] } } })
+ reject('extra volume mounts are rejected', (pod) => {
+ const mounts = container(pod).volumeMounts as Array<Record<string, unknown>>
+ mounts.push({ name: 'shadow', mountPath: '/shadow' })
+ })
+ reject('hostPath volumes are rejected', (pod) => {
+ const volume = (spec(pod).volumes as Array<Record<string, unknown>>)[0]
+ delete volume.persistentVolumeClaim
+ volume.hostPath = { path: '/' }
+ })
+ reject('a PVC for another agent is rejected', (pod) => {
+ const volume = (spec(pod).volumes as Array<Record<string, unknown>>)[0]
+ const pvc = volume.persistentVolumeClaim as Record<string, unknown>
+ pvc.claimName = 'agent-other-chrome'
+ })
+})
+
+test('secure reuse, legacy/unknown replacement, and bounded deletion are fail-closed', async () => {
+ const image = 'quay.io/img:security-test'
+ const secure = load(podManifest({
+ agentId: 'iris-0c97',
+ token: 'jwt',
+ image,
+ serverUrl: 'http://server/runtime',
+ openaiKey: 'sk-test',
+ openaiBaseUrl: '',
+ idleMs: 600_000,
+ noWorkMs: 90_000,
+ })) as Record<string, unknown>
+ assert.equal(isSecureManagedPod(secure, image, 'iris-0c97'), true, 'secure live object is reusable')
+ assert.equal(isSecureManagedPod({ metadata: { labels: { app: 'cumora-agent' } } }, image, 'iris-0c97'), false, 'unknown object is not reusable')
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-egress', null, 'default'), false, 'missing policy fails closed')
+
+ const calls: string[][] = []
+ let getCount = 0
+ const eventuallyGone = await waitForPodDeletion('iris-0c97', async (args) => {
+ calls.push(args)
+ if (args[0] === 'delete') return { code: 0, out: '', err: '', timedOut: false }
+ getCount++
+ return getCount === 1
+ ? { code: 0, out: JSON.stringify(secure), err: '', timedOut: false }
+ : { code: 0, out: '', err: '', timedOut: false }
+ }, { deadlineMs: 100, pollMs: 0, sleep: async () => {} })
+ assert.deepEqual(eventuallyGone, { ok: true })
+ assert.equal(calls[0][0], 'delete')
+ assert.ok(calls.filter((args) => args[0] === 'get').length >= 2, 'waits for the old name to disappear')
+
+ const stuck = await waitForPodDeletion('iris-0c97', async (args) => (
+ args[0] === 'delete'
+ ? { code: 0, out: '', err: '', timedOut: false }
+ : { code: 0, out: JSON.stringify(secure), err: '', timedOut: false }
+ ), { deadlineMs: 0, pollMs: 0, sleep: async () => {} })
+ assert.equal(stuck.ok, false, 'a Pod that never disappears blocks replacement')
+
+ const authFailure = await waitForPodDeletion('iris-0c97', async (args) => (
+ args[0] === 'delete'
+ ? { code: 0, out: '', err: '', timedOut: false }
+ : { code: 1, out: '', err: 'exec: gke-gcloud-auth-plugin: not found', timedOut: false }
+ ), { deadlineMs: 100, pollMs: 0, sleep: async () => {} })
+ assert.equal(authFailure.ok, false, 'auth/plugin failure is not resource absence')
+})
+
+test('checked-in NetworkPolicies parse and match the orchestrator contract', async () => {
+ const docs = loadAll(await readRepo('server/k8s/cumora-agent-network-policy.yaml')) as unknown[]
+ assert.equal(docs.length, 2, 'policy bundle must contain only scoped deny and egress policies')
+ const byName = new Map<string, unknown>()
+ for (const doc of docs) {
+ const metadata = (doc as { metadata?: { name?: unknown } } | null)?.metadata
+ if (typeof metadata?.name === 'string') byName.set(metadata.name, doc)
+ }
+ for (const name of ['cumora-agent-default-deny', 'cumora-agent-egress']) {
+ assert.equal(byName.has(name), true, `${name} must be present in the checked-in policy bundle`)
+ assert.equal(isRequiredAgentNetworkPolicy(name, byName.get(name), 'default'), true, `${name} must satisfy v1`)
+ }
+ const deny = byName.get('cumora-agent-default-deny') as Record<string, unknown>
+ const denySelector = ((deny.spec as Record<string, unknown>).podSelector as Record<string, unknown>).matchLabels as Record<string, string>
+ const selected = (labels: Record<string, string>) => Object.entries(denySelector).every(([key, value]) => labels[key] === value)
+ assert.equal(selected({ app: 'cumora-agent' }), true)
+ assert.equal(selected({ app: 'cumora-server' }), false, 'default namespace server is not selected')
+ assert.equal(selected({ app: 'redis' }), false, 'default namespace Redis is not selected')
+ assert.equal(selected({ app: 'other-workload' }), false, 'other workloads are not selected')
+ const broad = structuredClone(deny)
+ ;(broad.spec as Record<string, unknown>).podSelector = {}
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-default-deny', broad, 'default'), false, 'namespace-wide selector is rejected')
+ const extraLabel = structuredClone(deny)
+ const extraSelector = ((extraLabel.spec as Record<string, unknown>).podSelector as Record<string, unknown>).matchLabels as Record<string, string>
+ extraSelector.team = 'agents'
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-default-deny', extraLabel, 'default'), false, 'extra selector labels are rejected')
+ const extraExpression = structuredClone(deny)
+ const expressionSelector = (extraExpression.spec as Record<string, unknown>).podSelector as Record<string, unknown>
+ expressionSelector.matchExpressions = [{ key: 'team', operator: 'Exists' }]
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-default-deny', extraExpression, 'default'), false, 'selector expressions are rejected')
+ const egress = byName.get('cumora-agent-egress') as Record<string, unknown>
+ const egressSpec = egress.spec as Record<string, unknown>
+ assert.deepEqual((egressSpec.podSelector as Record<string, unknown>).matchLabels, { app: 'cumora-agent' })
+ const egressRules = egressSpec.egress as Array<Record<string, unknown>>
+ const publicIpv4 = egressRules[2].to as Array<Record<string, unknown>>
+ const block = publicIpv4[0].ipBlock as { except?: string[] }
+ assert.ok(block.except?.includes('169.254.0.0/16'), 'metadata/link-local range must be excluded')
+ assert.ok(block.except?.includes('100.64.0.0/10'), 'CGNAT range must be excluded')
+ const tampered = structuredClone(egress)
+ const tamperedRules = (tampered.spec as Record<string, unknown>).egress as Array<Record<string, unknown>>
+ const tamperedBlock = ((tamperedRules[2].to as Array<Record<string, unknown>>)[0].ipBlock) as { except?: string[] }
+ tamperedBlock.except = tamperedBlock.except?.filter((cidr) => cidr !== '100.64.0.0/10')
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-egress', tampered, 'default'), false, 'a broad private-range exception is rejected')
+
+ const wideDns = structuredClone(egress)
+ const wideDnsRules = (wideDns.spec as Record<string, unknown>).egress as Array<Record<string, unknown>>
+ const wideDnsPorts = wideDnsRules[0].ports as Array<Record<string, unknown>>
+ wideDnsPorts[0].endPort = 65535
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-egress', wideDns, 'default'), false, 'DNS port ranges are rejected')
+
+ const wideServer = structuredClone(egress)
+ const wideServerRules = (wideServer.spec as Record<string, unknown>).egress as Array<Record<string, unknown>>
+ const wideServerPorts = wideServerRules[1].ports as Array<Record<string, unknown>>
+ wideServerPorts[0].endPort = 65535
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-egress', wideServer, 'default'), false, 'server port ranges are rejected')
+
+ const wideWeb = structuredClone(egress)
+ const wideWebRules = (wideWeb.spec as Record<string, unknown>).egress as Array<Record<string, unknown>>
+ const wideWebPorts = wideWebRules[2].ports as Array<Record<string, unknown>>
+ wideWebPorts[0].endPort = 65535
+ assert.equal(isRequiredAgentNetworkPolicy('cumora-agent-egress', wideWeb, 'default'), false, 'public Web port ranges are rejected')
+})
+
+test('server RBAC manifests grant policy reads only and disable agent SA tokens', async () => {
+ for (const path of ['server/k8s/cumora-server.gke.yaml', 'server/k8s/cumora-server.orbstack.yaml']) {
+ const docs = loadAll(await readRepo(path)) as unknown[]
+ const role = docs.find((doc) => {
+ const object = doc as { kind?: unknown; metadata?: { name?: unknown } } | null
+ return object?.kind === 'Role' && object.metadata?.name === 'cumora-server-agent-pods'
+ }) as { rules?: Array<{ apiGroups?: string[]; resources?: string[]; verbs?: string[] }> } | undefined
+ assert.ok(role, `${path} must define the server Role`)
+ const policyRule = role.rules?.find((rule) => rule.resources?.includes('networkpolicies'))
+ assert.deepEqual(policyRule?.apiGroups, ['networking.k8s.io'], `${path} policy API group`)
+ assert.deepEqual(policyRule?.verbs, ['get', 'list', 'watch'], `${path} policy verbs are read-only`)
+ const deployment = docs.find((doc) => (doc as { kind?: unknown } | null)?.kind === 'Deployment') as {
+ spec?: { template?: { spec?: { containers?: Array<{ name?: string; automountServiceAccountToken?: boolean }> } } }
+ } | undefined
+ const server = deployment?.spec?.template?.spec?.containers?.find((container) => container.name === 'server')
+ assert.ok(server, `${path} must contain the server container`)
+ // Agent token mounting is controlled by the generated agent Pod, not the
+ // server container; ensure the checked-in Role has no policy mutation path.
+ assert.equal(policyRule?.verbs?.includes('create'), false)
+ }
+})
+
test('podManifest: image with embedded quote is escaped (CUMORA_AGENT_COMPUTER_IMAGE env is user-set)', () => {
// An attacker who controlled CUMORA_AGENT_COMPUTER_IMAGE could
// historically have tried `legit-image"\ninjected: yaml` to break
diff --git a/server/src/agents/runtime/orchestrator.ts b/server/src/agents/runtime/orchestrator.ts
index 77cf46e..26728ce 100644
--- a/server/src/agents/runtime/orchestrator.ts
+++ b/server/src/agents/runtime/orchestrator.ts
@@ -22,18 +22,18 @@
* laptop.
*/
import { spawn } from 'node:child_process'
-import { env } from '../../env.js'
-import { pool } from '../../db/pool.js'
-import { sub2apiConfigured, sub2apiOpenAIBaseURL } from '../../sub2api.js'
-import { inprocClient } from './inproc-client.js'
-import { signAgentToken } from './jwt.js'
import { notifyAlert } from '../../alerting.js'
import { Semaphore } from '../../concurrency.js'
+import { pool } from '../../db/pool.js'
+import { env } from '../../env.js'
+import { sub2apiConfigured, sub2apiOpenAIBaseURL } from '../../sub2api.js'
import {
+ type AgentHostResolution,
managedPodPlacement,
resolveAgentHost,
- type AgentHostResolution,
} from '../computer/registry.js'
+import { inprocClient } from './inproc-client.js'
+import { signAgentToken } from './jwt.js'
const KUBECTL = process.env.CUMORA_KUBECTL ?? 'kubectl'
/** kubectl context to target. In dev we pin to OrbStack so a stray
@@ -53,6 +53,23 @@ const IMAGE = process.env.CUMORA_AGENT_COMPUTER_IMAGE
const TOKEN_TTL_SECONDS = Number(process.env.CUMORA_AGENT_TOKEN_TTL_SECONDS ?? 24 * 60 * 60)
/** K8s namespace pods land in. Default = current context's namespace. */
const NS = process.env.CUMORA_AGENT_NAMESPACE ?? 'default'
+/** Namespace carrying the trusted cumora-server Service/Pods. Keep this an
+ * explicit operator setting; never derive it from a per-user runtime URL. */
+const SERVER_NS = process.env.CUMORA_AGENT_SERVER_NAMESPACE ?? 'default'
+/** Stable labels and command that identify the post-SEC-10 agent contract.
+ * These values are deliberately constants rather than derived from a
+ * per-user URL or model setting. A running Pod is reusable only when its
+ * actual API object proves this contract. */
+export const AGENT_SECURITY_PROFILE_LABEL = 'cumora.dev/security-profile'
+export const AGENT_SECURITY_PROFILE = 'fuse-demoted-v1'
+export const AGENT_BOOTSTRAP_COMMAND = '/usr/local/bin/cumora-agent-bootstrap'
+export const AGENT_NETWORK_POLICY_VERSION = 'v1'
+export const REQUIRED_AGENT_NETWORK_POLICIES = [
+ 'cumora-agent-default-deny',
+ 'cumora-agent-egress',
+] as const
+const BOOTSTRAP_CAPABILITIES = ['SYS_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'] as const
+const MODEL_UID = 65532
/** Comma-separated list of imagePullSecrets to attach to the agent
* Pod. Needed when the image lives in a private registry (e.g.
* quay.io with auth, gcr.io / Artifact Registry without Workload
@@ -60,10 +77,11 @@ const NS = process.env.CUMORA_AGENT_NAMESPACE ?? 'default'
* OrbStack-local builds. */
const PULL_SECRETS = (process.env.CUMORA_AGENT_PULL_SECRETS ?? '')
.split(',').map((s) => s.trim()).filter(Boolean)
-/** Optional ServiceAccount the agent Pod runs as. Useful for GKE
- * Workload Identity (binding to a GCP service account) when the
- * agent's bash tool ends up calling GCP APIs. Empty = use the
- * namespace's `default` SA. */
+/** Optional ServiceAccount identity for the agent Pod. The Pod explicitly
+ * disables automountServiceAccountToken, which only suppresses the projected
+ * Kubernetes API token. It does not by itself suppress GCP Workload Identity
+ * or metadata credentials; those remain governed by runtime/CNI/operator
+ * policy. Empty = namespace `default` SA. */
const POD_SERVICE_ACCOUNT = process.env.CUMORA_AGENT_SERVICE_ACCOUNT ?? ''
export interface KubectlResult { code: number; out: string; err: string; timedOut: boolean }
@@ -302,14 +320,41 @@ metadata:
name: ${podName(args.agentId)}
labels:
app: cumora-agent
+ ${AGENT_SECURITY_PROFILE_LABEL}: ${yamlQuote(AGENT_SECURITY_PROFILE)}
cumora.agent: ${yamlQuote(labelValue)}
spec:
- restartPolicy: OnFailure${saBlock}${pullSecretsBlock}
+ restartPolicy: OnFailure
+ automountServiceAccountToken: false
+ securityContext:
+ runAsUser: 0
+ runAsGroup: 0
+ runAsNonRoot: false
+ fsGroup: ${MODEL_UID}
+ fsGroupChangePolicy: OnRootMismatch
+ seccompProfile:
+ type: RuntimeDefault${saBlock}${pullSecretsBlock}
+ hostPID: false
+ hostIPC: false
+ hostNetwork: false
+ shareProcessNamespace: false
containers:
- name: agent-computer
image: ${yamlQuote(args.image)}
imagePullPolicy: IfNotPresent
+ command: [${yamlQuote(AGENT_BOOTSTRAP_COMMAND)}]
securityContext:
+ # The container starts as root only for the trusted FUSE bootstrap.
+ # The bootstrap must then exec setpriv -> tini as UID/GID 65532 with
+ # all capabilities cleared and NoNewPrivs=1. These fields describe
+ # the pre-mount capability envelope; they are not the post-bootstrap
+ # process boundary.
+ runAsUser: 0
+ runAsGroup: 0
+ runAsNonRoot: false
+ allowPrivilegeEscalation: false
+ privileged: false
+ seccompProfile:
+ type: RuntimeDefault
# FUSE mount needs three things to work on GKE-COS:
# 1. CAP_SYS_ADMIN — for the mount(2) syscall.
# 2. /dev/fuse in the cgroup device whitelist — granted by the
@@ -325,7 +370,8 @@ spec:
appArmorProfile:
type: Unconfined
capabilities:
- add: ["SYS_ADMIN"]
+ drop: ["ALL"]
+ add: ["SYS_ADMIN", "SETUID", "SETGID", "SETPCAP", "KILL"]
resources:
requests:
# Measured in prod, per-pod working-set ≈ 420 MiB, but only
@@ -428,8 +474,282 @@ spec:
`
}
+type JsonRecord = Record<string, unknown>
+
+function asRecord(value: unknown): JsonRecord | null {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? value as JsonRecord
+ : null
+}
+
+function asStringRecord(value: unknown): Record<string, string> {
+ const record = asRecord(value)
+ if (!record) return {}
+ const out: Record<string, string> = {}
+ for (const [key, item] of Object.entries(record)) {
+ if (typeof item === 'string') out[key] = item
+ }
+ return out
+}
+
+function asArray(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : []
+}
+
+function hasExactStringSet(value: unknown, expected: readonly string[]): boolean {
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) return false
+ if (value.length !== expected.length) return false
+ const actual = [...new Set(value as string[])].sort()
+ return actual.length === expected.length
+ && actual.every((item, index) => item === [...expected].sort()[index])
+}
+
+function hasStringArray(value: unknown, expected: readonly string[]): boolean {
+ return Array.isArray(value)
+ && value.length === expected.length
+ && value.every((item, index) => item === expected[index])
+}
+
+/**
+ * Parse the API representation of a Pod and prove that it is the exact
+ * trusted bootstrap shape emitted by podManifest(). This is intentionally
+ * stricter than checking the profile label: labels can be stale, copied, or
+ * changed by an operator while an immutable Pod template remains legacy.
+ */
+export function isSecureManagedPod(
+ raw: unknown,
+ expectedImage: string = IMAGE,
+ expectedAgentId?: string,
+): boolean {
+ let pod = raw
+ if (typeof raw === 'string') {
+ try { pod = JSON.parse(raw) as unknown } catch { return false }
+ }
+ const root = asRecord(pod)
+ const metadata = asRecord(root?.metadata)
+ const labels = asStringRecord(metadata?.labels)
+ if (labels.app !== 'cumora-agent' || labels[AGENT_SECURITY_PROFILE_LABEL] !== AGENT_SECURITY_PROFILE) {
+ return false
+ }
+ if (expectedAgentId !== undefined) {
+ const slug = safeName(expectedAgentId).replace(/^agent-/, '') || 'unknown'
+ if (labels['cumora.agent'] !== slug) return false
+ }
+
+ const spec = asRecord(root?.spec)
+ if (spec?.automountServiceAccountToken !== false) return false
+ for (const field of ['hostPID', 'hostIPC', 'hostNetwork', 'shareProcessNamespace']) {
+ const value = spec?.[field]
+ // These API fields are Go bool/pointer fields with omitempty, so a
+ // correctly defaulted Pod may omit false. Accept only false or omitted;
+ // true and every malformed value still fail closed.
+ if (value !== undefined && value !== false) return false
+ }
+ for (const field of ['initContainers', 'ephemeralContainers']) {
+ const value = spec?.[field]
+ if (value !== undefined) return false
+ }
+ const podSecurity = asRecord(spec?.securityContext)
+ if (podSecurity?.runAsUser !== 0 || podSecurity?.runAsGroup !== 0 || podSecurity?.runAsNonRoot !== false) return false
+ if (podSecurity?.fsGroup !== MODEL_UID) return false
+ const podSeccomp = asRecord(podSecurity?.seccompProfile)
+ if (podSeccomp?.type !== 'RuntimeDefault') return false
+
+ const containers = asArray(spec?.containers)
+ if (containers.length !== 1) return false
+ const container = asRecord(containers[0])
+ if (!container || container.name !== 'agent-computer') return false
+ if (container.image !== expectedImage) return false
+ if (!hasStringArray(container.command, [AGENT_BOOTSTRAP_COMMAND])) return false
+ if (container.args !== undefined && (!Array.isArray(container.args) || container.args.length !== 0)) return false
+ if (container.lifecycle !== undefined) return false
+ for (const field of ['startupProbe', 'readinessProbe', 'livenessProbe']) {
+ const probe = asRecord(container[field])
+ if (probe?.exec !== undefined) return false
+ }
+ const volumeMounts = container.volumeMounts
+ if (!Array.isArray(volumeMounts) || volumeMounts.length !== 1) return false
+ const chromeMount = asRecord(volumeMounts[0])
+ if (!chromeMount || chromeMount.name !== 'chrome-profile' || chromeMount.mountPath !== '/opt/chrome-profile') return false
+ for (const field of ['subPath', 'subPathExpr']) {
+ if (chromeMount[field] !== undefined) return false
+ }
+ if (chromeMount.mountPropagation !== undefined && chromeMount.mountPropagation !== 'None') return false
+ if (container.volumeDevices !== undefined) return false
+ const volumes = spec.volumes
+ if (!Array.isArray(volumes) || volumes.length !== 1) return false
+ const chromeVolume = asRecord(volumes[0])
+ if (!chromeVolume || chromeVolume.name !== 'chrome-profile') return false
+ const volumeSources = Object.keys(chromeVolume).filter((key) => key !== 'name')
+ if (volumeSources.length !== 1) return false
+ const pvc = asRecord(chromeVolume.persistentVolumeClaim)
+ const emptyDir = asRecord(chromeVolume.emptyDir)
+ if (!pvc && !emptyDir) return false
+ if (pvc) {
+ if (expectedAgentId === undefined || pvc.claimName !== chromeProfilePvcName(expectedAgentId)) return false
+ }
+ const security = asRecord(container.securityContext)
+ if (!security) return false
+ if (security.runAsUser !== 0 || security.runAsGroup !== 0) return false
+ if (security.runAsNonRoot !== false) return false
+ if (security.allowPrivilegeEscalation !== false) return false
+ if (security.privileged !== false) return false
+ const seccomp = asRecord(security.seccompProfile)
+ if (seccomp?.type !== 'RuntimeDefault') return false
+ const appArmor = asRecord(security.appArmorProfile)
+ if (appArmor?.type !== 'Unconfined') return false
+ const capabilities = asRecord(security.capabilities)
+ if (!capabilities) return false
+ if (!hasStringArray(capabilities.drop, ['ALL'])) return false
+ if (!hasExactStringSet(capabilities.add, BOOTSTRAP_CAPABILITIES)) return false
+ return true
+}
+
+function policyMetadataMatches(policy: JsonRecord, expectedName: string): boolean {
+ const metadata = asRecord(policy.metadata)
+ const labels = asStringRecord(metadata?.labels)
+ return metadata?.name === expectedName
+ && labels[AGENT_SECURITY_PROFILE_LABEL] === AGENT_SECURITY_PROFILE
+ && labels['cumora.dev/network-policy-version'] === AGENT_NETWORK_POLICY_VERSION
+}
+
+function policyTypesExactly(policy: JsonRecord, ...types: string[]): boolean {
+ const spec = asRecord(policy.spec)
+ const raw = asArray(spec?.policyTypes)
+ if (raw.some((type) => typeof type !== 'string')) return false
+ const actual = raw as string[]
+ actual.sort()
+ const expected = [...types].sort()
+ return actual.length === expected.length && actual.every((type, index) => type === expected[index])
+}
+
+function selectorHasLabels(value: unknown, expected: Record<string, string>): boolean {
+ const selector = asRecord(value)
+ if (!selector) return false
+ const labels = asRecord(selector.matchLabels)
+ if (!labels || Object.values(labels).some((item) => typeof item !== 'string')) return false
+ const expectedKeys = Object.keys(expected).sort()
+ const actualKeys = Object.keys(labels).sort()
+ if (actualKeys.length !== expectedKeys.length || actualKeys.some((key, index) => key !== expectedKeys[index])) return false
+ if (!Object.entries(expected).every(([key, item]) => labels[key] === item)) return false
+ const matchExpressions = selector.matchExpressions
+ return matchExpressions === undefined || (Array.isArray(matchExpressions) && matchExpressions.length === 0)
+}
+
+function portMatches(value: unknown, protocol: string, port: number): boolean {
+ const item = asRecord(value)
+ return item?.protocol === protocol
+ && item.endPort === undefined
+ && (item.port === port || item.port === String(port))
+}
+
+function hasPeerSelector(
+ peer: unknown,
+ namespaceName: string,
+ podLabels: Record<string, string>,
+): boolean {
+ const item = asRecord(peer)
+ return selectorHasLabels(item?.namespaceSelector, { 'kubernetes.io/metadata.name': namespaceName })
+ && selectorHasLabels(item?.podSelector, podLabels)
+}
+
+function hasPublicWebBlock(value: unknown, cidr: string, requiredExcept: readonly string[]): boolean {
+ const blocks = asArray(value)
+ if (blocks.length !== 1) return false
+ const peer = asRecord(blocks[0])
+ const block = asRecord(peer?.ipBlock)
+ if (block?.cidr !== cidr) return false
+ const except = asArray(block.except)
+ return requiredExcept.every((item) => except.includes(item))
+}
+
+/**
+ * Validate the required pre-deployed NetworkPolicies. NetworkPolicy
+ * objects are additive and their enforcement is asynchronous, so this only
+ * proves the required API objects/version exist. It deliberately does not
+ * infer allowlists from OPENAI_BASE_URL or another per-user setting.
+ */
+export function isRequiredAgentNetworkPolicy(
+ expectedName: string,
+ raw: unknown,
+ agentNamespace: string = NS,
+ trustedServerNamespace: string = SERVER_NS,
+): boolean {
+ const policy = typeof raw === 'string'
+ ? (() => { try { return JSON.parse(raw) as unknown } catch { return null } })()
+ : raw
+ const object = asRecord(policy)
+ if (!object || !policyMetadataMatches(object, expectedName)) return false
+ const metadata = asRecord(object.metadata)
+ if (typeof metadata?.namespace === 'string' && metadata.namespace !== agentNamespace) return false
+ const spec = asRecord(object.spec)
+ if (!spec) return false
+
+ if (expectedName === 'cumora-agent-default-deny') {
+ return selectorHasLabels(spec.podSelector, { app: 'cumora-agent' })
+ && policyTypesExactly(object, 'Ingress', 'Egress')
+ && asArray(spec.ingress).length === 0
+ && asArray(spec.egress).length === 0
+ }
+
+ if (expectedName === 'cumora-agent-egress') {
+ const egress = asArray(spec.egress)
+ if (!selectorHasLabels(spec.podSelector, { app: 'cumora-agent' })
+ || !policyTypesExactly(object, 'Egress')
+ || asArray(spec.ingress).length !== 0
+ || egress.length !== 4) return false
+ const dns = asRecord(egress[0])
+ const server = asRecord(egress[1])
+ const ipv4 = asRecord(egress[2])
+ const ipv6 = asRecord(egress[3])
+ const dnsPeers = asArray(dns?.to)
+ const dnsPorts = asArray(dns?.ports)
+ const serverPeers = asArray(server?.to)
+ const serverPorts = asArray(server?.ports)
+ const webPorts4 = asArray(ipv4?.ports)
+ const webPorts6 = asArray(ipv6?.ports)
+ const dnsPeer = asRecord(dnsPeers[0])
+ const dnsNamespace = asRecord(dnsPeer?.namespaceSelector)
+ const dnsPod = asRecord(dnsPeer?.podSelector)
+ return dnsPeers.length === 1
+ && selectorHasLabels(dnsNamespace, { 'kubernetes.io/metadata.name': 'kube-system' })
+ && selectorHasLabels(dnsPod, { 'k8s-app': 'kube-dns' })
+ && dnsPorts.length === 2
+ && dnsPorts.some((port) => portMatches(port, 'UDP', 53))
+ && dnsPorts.some((port) => portMatches(port, 'TCP', 53))
+ && serverPeers.length === 1
+ && hasPeerSelector(serverPeers[0], trustedServerNamespace, { app: 'cumora-server' })
+ && serverPorts.length === 1
+ && portMatches(serverPorts[0], 'TCP', 5181)
+ && hasPublicWebBlock(ipv4?.to, '0.0.0.0/0', [
+ '0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
+ '169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24',
+ '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24',
+ '224.0.0.0/4', '240.0.0.0/4',
+ ])
+ && webPorts4.length === 2
+ && webPorts4.some((port) => portMatches(port, 'TCP', 80))
+ && webPorts4.some((port) => portMatches(port, 'TCP', 443))
+ && hasPublicWebBlock(ipv6?.to, '::/0', [
+ '::/128', '::1/128', 'fc00::/7', 'fe80::/10', 'ff00::/8', '2001:db8::/32',
+ ])
+ && webPorts6.length === 2
+ && webPorts6.some((port) => portMatches(port, 'TCP', 80))
+ && webPorts6.some((port) => portMatches(port, 'TCP', 443))
+ }
+ return false
+}
+
/** Exported for tests — production callers go through ensurePod. */
-export const _testing = { podManifest, yamlQuote, dnsLabelValue, chromeProfilePvcManifest, chromeProfilePvcName }
+export const _testing = {
+ podManifest,
+ yamlQuote,
+ dnsLabelValue,
+ chromeProfilePvcManifest,
+ chromeProfilePvcName,
+ isSecureManagedPod,
+ isRequiredAgentNetworkPolicy,
+}
// ─── cluster-wide FUSE admission control ─────────────────────────────
//
@@ -587,11 +907,133 @@ export function parsePodHealth(rawJson: string): PodHealth {
return { phase, waitingReasons, unschedulable }
}
-async function podHealth(agentId: string): Promise<PodHealth> {
- // `get pod` is the read path — retry on transient API-server issues.
- const r = await kubectlWithRetry(['get', 'pod', podName(agentId), '-o', 'json'])
- if (r.code !== 0) return { phase: '', waitingReasons: [], unschedulable: false }
- return parsePodHealth(r.out)
+interface PodSnapshot {
+ exists: boolean
+ lookupFailed: boolean
+ raw: unknown
+ health: PodHealth
+ error?: string
+}
+
+/** With --ignore-not-found=true, kubectl reports a missing named object as
+ * success with no stdout. A nonzero result is always an API/auth/transport
+ * failure; an error message containing "not found" is not resource absence
+ * evidence (for example, an auth plugin executable may be missing). */
+function resultIsMissingWithIgnoreNotFound(r: KubectlResult): boolean {
+ return r.code === 0 && r.out.trim() === ''
+}
+
+/** Read both health and the actual API object. Reusing a Pod is allowed only
+ * after the latter passes isSecureManagedPod(); a status-only read cannot
+ * distinguish a secure immutable template from a legacy one. */
+async function podSnapshot(agentId: string): Promise<PodSnapshot> {
+ const r = await kubectlWithRetry(['get', 'pod', podName(agentId), '--ignore-not-found=true', '-o', 'json'])
+ if (r.code !== 0) {
+ return {
+ exists: false,
+ lookupFailed: true,
+ raw: null,
+ health: { phase: '', waitingReasons: [], unschedulable: false },
+ error: (r.err || r.out).trim(),
+ }
+ }
+ if (resultIsMissingWithIgnoreNotFound(r)) {
+ return {
+ exists: false,
+ lookupFailed: false,
+ raw: null,
+ health: { phase: '', waitingReasons: [], unschedulable: false },
+ }
+ }
+ let raw: unknown = null
+ try { raw = JSON.parse(r.out) as unknown } catch { /* malformed = existing unknown Pod */ }
+ return { exists: true, lookupFailed: false, raw, health: parsePodHealth(r.out) }
+}
+
+type NetworkPolicyPreflight = {
+ ok: true
+} | {
+ ok: false
+ code: 'network_policy_missing' | 'network_policy_invalid' | 'network_policy_lookup_failed'
+ reason: string
+}
+
+async function checkRequiredAgentNetworkPolicies(): Promise<NetworkPolicyPreflight> {
+ for (const name of REQUIRED_AGENT_NETWORK_POLICIES) {
+ const r = await kubectlWithRetry(
+ ['get', 'networkpolicy', name, '--ignore-not-found=true', '-o', 'json'],
+ { timeoutMs: 10_000 },
+ )
+ if (r.code !== 0) {
+ const detail = (r.err || r.out).trim().slice(0, 240)
+ return { ok: false, code: 'network_policy_lookup_failed', reason: `could not read required NetworkPolicy ${name}: ${detail}` }
+ }
+ if (resultIsMissingWithIgnoreNotFound(r)) {
+ return { ok: false, code: 'network_policy_missing', reason: `required NetworkPolicy ${name} is missing in namespace ${NS}` }
+ }
+ let raw: unknown
+ try { raw = JSON.parse(r.out) as unknown } catch {
+ return { ok: false, code: 'network_policy_invalid', reason: `required NetworkPolicy ${name} returned invalid JSON` }
+ }
+ if (!isRequiredAgentNetworkPolicy(name, raw, NS, SERVER_NS)) {
+ return { ok: false, code: 'network_policy_invalid', reason: `required NetworkPolicy ${name} does not match ${AGENT_NETWORK_POLICY_VERSION} contract` }
+ }
+ }
+ return { ok: true }
+}
+
+export type PodDeletionResult = { ok: true } | { ok: false; reason: string }
+type PodKubectlRunner = (
+ args: string[],
+ opts?: { timeoutMs?: number; maxAttempts?: number },
+) => Promise<KubectlResult>
+
+/** Delete an immutable Pod and prove its name is gone before a replacement
+ * can be applied. The runner/sleep seams keep this lifecycle testable without
+ * talking to a production cluster. */
+export async function waitForPodDeletion(
+ agentId: string,
+ runner: PodKubectlRunner = kubectlWithRetry,
+ options: { deadlineMs?: number; pollMs?: number; sleep?: (ms: number) => Promise<void> } = {},
+): Promise<PodDeletionResult> {
+ const name = podName(agentId)
+ const reap = await runner(
+ ['delete', 'pod', name, '--ignore-not-found=true', '--wait=true', '--timeout=30s'],
+ { timeoutMs: 40_000 },
+ )
+ if (reap.code !== 0) {
+ return { ok: false, reason: `delete failed: ${(reap.err || reap.out).trim()}` }
+ }
+
+ // `kubectl delete --wait` normally gives this guarantee, but it can return
+ // after an API timeout or a finalizer race. Confirm the name is gone before
+ // applying a replacement, otherwise an immutable Pod can leave two model
+ // lifecycles or turn the apply into a misleading AlreadyExists failure.
+ const deadline = Date.now() + (options.deadlineMs ?? 10_000)
+ const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
+ while (Date.now() < deadline) {
+ const check = await runner(
+ ['get', 'pod', name, '--ignore-not-found=true', '-o', 'json'],
+ { timeoutMs: 5_000, maxAttempts: 1 },
+ )
+ if (resultIsMissingWithIgnoreNotFound(check)) return { ok: true }
+ if (check.code !== 0 && !isRetryableKubectlError(check)) {
+ return { ok: false, reason: `deletion confirmation failed: ${(check.err || check.out).trim()}` }
+ }
+ await sleep(options.pollMs ?? 250)
+ }
+ return { ok: false, reason: `pod ${name} did not disappear before timeout` }
+}
+
+async function reapPodAndConfirmGone(agentId: string, reason: string): Promise<EnsurePodResult | null> {
+ const result = await waitForPodDeletion(agentId)
+ if (result.ok) return null
+ return {
+ created: false,
+ ok: false,
+ code: 'pod_reap_failed',
+ reason: `pod reap failed (${reason}): ${result.reason}`,
+ }
}
/** Waiting reasons that K8s will not recover from on its own — image
@@ -637,6 +1079,9 @@ export type EnsurePodResult =
| 'agent_not_found'
| 'placement_lookup_failed'
| 'placement_denied'
+ | 'network_policy_missing'
+ | 'network_policy_invalid'
+ | 'network_policy_lookup_failed'
| 'pod_apply_failed'
}
@@ -770,83 +1215,74 @@ async function ensurePodImpl(agentId: string): Promise<EnsurePodResult> {
}
return null
}
- const h = await podHealth(agentId)
- if (h.phase === 'Running') {
- const denied = await recheckPlacement()
- if (denied) return denied
- return { created: false, ok: true, reason: 'already running' }
+ const snapshot = await podSnapshot(agentId)
+ if (snapshot.lookupFailed) {
+ return {
+ created: false,
+ ok: false,
+ code: 'pod_reap_failed',
+ reason: `could not inspect existing pod before replacement: ${snapshot.error ?? 'kubectl failed'}`,
+ }
}
- if (h.phase === 'Pending') {
- const stuck = stuckPendingReason(h)
- if (!stuck) {
+
+ if (snapshot.exists) {
+ const secure = isSecureManagedPod(snapshot.raw, IMAGE, agentId)
+ const h = snapshot.health
+ const stuck = h.phase === 'Pending' ? stuckPendingReason(h) : null
+ const reusable = secure && (h.phase === 'Running' || (h.phase === 'Pending' && !stuck))
+
+ if (reusable) {
+ // A secure label alone is not enough: isSecureManagedPod already
+ // checked the immutable command/image/security fields. The policy
+ // check below proves the required pre-deployed objects are present
+ // before we treat the Pod as usable.
const denied = await recheckPlacement()
if (denied) return denied
- return { created: false, ok: true, reason: 'already pending' }
- }
- // Fall through to the stuck-Pending reap path below. Don't admission-
- // gate this: reaping is a cleanup that frees a slot, not a fresh
- // demand on cluster capacity.
- // Pod will never recover on its own (ImagePullBackOff / Unschedulable /
- // CrashLoopBackOff / etc.) — reap so the apply below installs a
- // fresh manifest. kubectl apply against an immutable existing Pod
- // would fail, hence the explicit delete first.
- //
- // Alert because stuck pods point at infra problems (bad image
- // tag, exhausted node pool) that need a human to look. The reap
- // unblocks the agent in the short term but the underlying cause
- // will re-surface on the NEXT ensurePod unless someone fixes it.
- console.warn(`[orchestrator] ${agentId} pending pod is stuck (${stuck}); reaping`)
- void notifyAlert({
- label: 'orchestrator.stuck_pending_reap',
- error: new Error(`pod for ${agentId} stuck in Pending (${stuck}); reaping for fresh start`),
- extras: { agentId, stuckReason: stuck, waitingReasons: h.waitingReasons.join(',') },
- })
- // `--timeout=30s` on the kubectl side AND our wrapper timeout —
- // belt-and-braces. A pod with stuck finalizers shouldn't block
- // the orchestrator's main loop indefinitely.
- const denied = await recheckPlacement()
- if (denied) return denied
- const reap = await kubectlWithRetry(
- ['delete', 'pod', podName(agentId), '--ignore-not-found=true', '--wait=true', '--timeout=30s'],
- { timeoutMs: 40_000 },
- )
- if (reap.code !== 0) {
- // The reap failed — apply will almost certainly fail too (it
- // can't create a Pod with the same name as an existing one).
- // Surface a precise error rather than letting the apply step
- // try and produce a misleading "already exists" message.
- return {
- created: false, ok: false, code: 'pod_reap_failed',
- reason: `pod reap failed (was stuck=${stuck}): ${(reap.err || reap.out).trim()}`,
- }
+ const policies = await checkRequiredAgentNetworkPolicies()
+ if (!policies.ok) return { created: false, ...policies }
+ return { created: false, ok: true, reason: h.phase === 'Running' ? 'already running' : 'already pending' }
}
- } else if (h.phase === 'Succeeded' || h.phase === 'Failed' || h.phase === 'Unknown') {
- // Plain Pods (not Jobs) don't have ttlSecondsAfterFinished, so a
- // Pod that idle-exited stays in Completed state until something
- // deletes it. Reap it before applying the new manifest so kubectl
- // apply doesn't see it as an existing immutable Pod. Unknown
- // (node lost / kubelet unreachable) is also a clean-slate case.
- if (h.phase === 'Failed') {
- // Failed = the container exited non-zero AND restartPolicy gave
- // up. That's a real bug inside the pod we should surface, not
- // just an idle teardown.
+
+ const reason = !secure
+ ? 'legacy or unknown security contract'
+ : stuck
+ ? `stuck pending=${stuck}`
+ : h.phase === 'Failed'
+ ? 'previous pod ended in Failed'
+ : h.phase === 'Succeeded'
+ ? 'previous pod completed'
+ : h.phase === 'Unknown'
+ ? 'previous pod phase is Unknown'
+ : `unrecognized pod phase=${h.phase || 'empty'}`
+ if (stuck) {
+ console.warn(`[orchestrator] ${agentId} pending pod is stuck (${stuck}); reaping`)
+ void notifyAlert({
+ label: 'orchestrator.stuck_pending_reap',
+ error: new Error(`pod for ${agentId} stuck in Pending (${stuck}); reaping for fresh start`),
+ extras: { agentId, stuckReason: stuck, waitingReasons: h.waitingReasons.join(',') },
+ })
+ } else if (h.phase === 'Failed') {
console.warn(`[orchestrator] ${agentId} previous pod ended in Failed; reaping to recreate`)
void notifyAlert({
label: 'orchestrator.previous_pod_failed',
error: new Error(`previous pod for ${agentId} ended in Failed phase; recreating`),
extras: { agentId, waitingReasons: h.waitingReasons.join(',') },
})
- } else if (h.phase === 'Unknown') {
- console.warn(`[orchestrator] ${agentId} previous pod was in Unknown phase (node lost?); reaping`)
+ } else if (h.phase === 'Unknown' || !secure) {
+ console.warn(`[orchestrator] ${agentId} ${reason}; deleting before replacement`)
}
const denied = await recheckPlacement()
if (denied) return denied
- await kubectlWithRetry(
- ['delete', 'pod', podName(agentId), '--ignore-not-found=true', '--wait=true', '--timeout=30s'],
- { timeoutMs: 40_000 },
- )
+ const reapFailure = await reapPodAndConfirmGone(agentId, reason)
+ if (reapFailure) return reapFailure
}
+ // NetworkPolicy objects are a deployment prerequisite. The orchestrator
+ // never applies them and never derives exceptions from a user-controlled
+ // model/provider URL; API success is not evidence that a CNI enforces them.
+ const policies = await checkRequiredAgentNetworkPolicies()
+ if (!policies.ok) return { created: false, ...policies }
+
// Cluster-wide FUSE admission: refuse the spawn if the cluster is
// near its /dev/fuse capacity. The scheduler puts durable
// message.new/manual wakes into a Redis retry queue when this