Skip to content

feat(desktop): contain daemonising apps and isolate session runtime - #92

Merged
ElbertePlinio merged 8 commits into
mainfrom
fix/alpha2-isolation
Sep 5, 2026
Merged

ElbertePlinio merged 8 commits into
mainfrom
fix/alpha2-isolation

Conversation

@ElbertePlinio

@ElbertePlinio ElbertePlinio commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Phase 1 isolation hardening for the 0.4.0-alpha.2 gate. Full report and raw
device-pass evidence: ~/Projects/Boards/pickforge/0.4-release/alpha2-isolation-report.md.

Review round 2 (f49fc01)

The independent review (review-pr92.md) found two blockers and four P2s;
all are fixed, plus the P3s. Each was reproduced first.

  • cgroup.kill never kills the caller. session destroy run from inside a
    contained shell used to kill itself before Xvfb/VNC/runtime cleanup. Cleanup
    now moves its own process chain into the parent cgroup, re-reads
    cgroup.procs and /proc/self/cgroup to confirm it is out, and only then
    writes cgroup.kill; if the chain cannot be moved it refuses with a reason
    ("run the command from outside the session") instead of terminating the
    caller. Pinned by a supervisor-started worker destroying its own scope
    (core) and a real-Xvfb session destroyed from inside (desktop-linux), and by
    a CLI device smoke.
  • Vanished PID is gone, not refused. A target that exits between the
    /proc scan and the pre-signal token re-read no longer fails the destroy.
    Only a live PID without the exact token is refused. Both cases are pinned
    with a deterministic seam on the environ read.
  • Late x11vnc gets the session runtime. ensureSessionVnc (watch),
    takeover start and takeover revert now go through one startSessionVnc
    helper, so no x11vnc keeps the caller's XDG_RUNTIME_DIR or D-Bus
    addresses. Pinned with a fake x11vnc that records its environment.
  • No code injection into the supervisor. NODE_OPTIONS, NODE_PATH,
    NODE_REPL_EXTERNAL_MODULE and BUN_OPTIONS are stripped from the desktop
    environment; desktop env lists them as unset. Control test proves the
    injection takes over a plain node; launchApp still joins and spawns.
  • Joins and paths are verified, not assumed. The supervisor reads its
    membership back from /proc/self/cgroup and exits 126 without spawning the
    app if the kernel disagrees (pinned with a writable non-cgroup impostor and
    with an unavailable scope). A recorded cgroup path must be a pickforge-*
    directory on a cgroup v2 filesystem before launch or destroy will use it;
    the lab's own delegated cgroup can never be targeted.
  • Dying descendants are not refused (d4fbfbc). CI's marker path caught
    a race the first fix left open: a supervised app probed a few microseconds
    after the forwarded SIGTERM is alive, not yet a zombie, has released its
    address space, and its environ read fails with EACCES; it was refused as an
    identity mismatch. The scan now records each contained process's start
    time, and the pre-signal probe uses it: changed start time is a recycled PID
    and is refused; missing or zombie is gone; the same process with a
    momentarily unreadable token is decided on a later pass. An empty scan must
    be confirmed by a second one. Reproduced and verified under full CPU load
    (8 x 25 marker destroys, 0 refusals, previously 1-3 per 25) using the new
    PICKFORGE_CONTAINMENT=marker override, which forces the fallback path on a
    delegated host.
  • Supervisor forwards SIGTERM instead of swallowing it, so a marker
    destroy no longer waits out the full SIGTERM budget.
  • Cgroup-only tests skip explicitly and the suite logs the mechanism the host
    selected; the runtime dir is removed only once apps, x11vnc and Xvfb are all
    confirmed gone; non-Linux reports cleanup as unconfirmed; header comment,
    SECURITY.md, README and release notes describe the actual mechanism.

Gates at d4fbfbc: typecheck, lint, bun run test clean on the cgroup path
(1238 passed / 4 skipped) and with the marker path forced (1234 passed /
8 skipped), coverage, build, complexity-gate check --changed clean, focused
stress 3× green, marker destroys under full CPU load 200/200 confirmed, CLI
device smoke of destroy-from-inside twice green.

Containment audit (#85)

A process group does not contain a GUI app: a double fork() or setsid()
leaves the group and survives the group signal. Under the hard constraint that
MCP never calls sudo:

  • PR_SET_PDEATHSIG — rejected. Wrong direction, cleared across fork, not
    reachable from Node, and it confirms nothing.
  • PR_SET_CHILD_SUBREAPER — rejected. Retains orphans but does not contain
    them, still needs a kill mechanism, and needs a native addon Node does not
    have.
  • PID namespace — rejected. Needs unprivileged userns (often off) and breaks the
    existing /proc start-time identity checks.
  • systemd-run --user --scope — rejected. Same cgroup idea, but needs a systemd
    user session CI and containers do not have.
  • cgroup v2 + cgroup.kill — chosen as primary.
  • Environment marker + /proc sweep — chosen as fallback and as the
    confirmation step.

Each desktop session owns a containment scope. Apps start through a supervisor
that joins the scope before spawning them and verifies the join from the
kernel's view, closing the window a "spawn, then migrate the pid" approach
leaves open.

Why it cannot signal anything unrelated: targets come from cgroup membership or
an exact 256-bit token match re-read from /proc/<pid>/environ immediately
before each signal; a pid that exited is skipped, a live pid whose identity no
longer matches is refused, not killed; the cleaning process and its ancestors
are excluded (moved out of the cgroup first on the cgroup path); an inherited
foreign token is stripped before the session's own is set.
destroyContainmentScope reports confirmed only when the scope is empty and
nothing was refused, and session destroy fails loudly with the surviving pids
otherwise.

Runtime and D-Bus isolation (#86)

Per-session <sessionDir>/runtime, mode 0700 (explicit chmod, umask-proof),
carrying XDG_RUNTIME_DIR and both D-Bus addresses. The bus sockets are never
created, so an app fails to connect instead of reaching the user's bus —
unsetting the addresses would not be equivalent, since libdbus then falls back to
$XDG_RUNTIME_DIR/bus and X11 autolaunch. Stray DBUS_* variables are dropped;
every x11vnc start (create, watch, takeover, revert) gets the same treatment;
desktop env prints the same recipe plus the token so hand-started apps are
torn down with the session. Removal happens only after apps, x11vnc and Xvfb
are confirmed gone, and is refused for any path not confined to the session
directory, symlinks included.

Xvfb teardown (#57)

stopOwnedDaemon now uses one shared stopOwnedDaemonGroup in
@pickforge/lab-core — group signal plus isProcessGroupAlive confirmation —
and the browser supervisor's private copy was deleted in favour of it.
Unconfirmed cleanup propagates into XvfbPartialStart.cleanupConfirmed instead
of being hardcoded to true. stopXvfb verifies the group-leader identity
rather than signalling a bare pid.

Tests

Adversarial coverage: escape via setsid/double fork (marker and cgroup),
unrelated and foreign-token processes left alone, prefix-token match refused,
self/ancestor exclusion proven from a separate process that carries the token
(marker and, from inside the cgroup, cgroup), exited-pid, vanished-pid and
recycled-pid safety, SIGKILL escalation, supervisor TERM forwarding, false join
and unavailable/tampered cgroup paths, NODE_OPTIONS hijack, cleanup-failure
reporting, argv-array-only supervisor command, stale-cgroup pruning and
re-creation, 0700 under a permissive umask, path confinement against ../
and symlinks, late x11vnc runtime for watch/takeover/revert, and real-Xvfb
end-to-end tests where a daemonised escapee is held and killed by
session destroy, a destroy run from inside the session survives and
completes, and teardown failure keeps the record retryable.

Device pass

Isolated HOME/PICKFORGE_HOME, real Xvfb session, mechanism cgroup. A real
GTK app rendered with D-Bus pointed at non-existent sockets; /proc confirms it
had the session runtime dir, both D-Bus addresses, the token, and cgroup
membership. Synthetic click + type registered. A setsid escapee — its own
session and group leader, outside the launched group — was still a cgroup member
and was killed by session destroy, after which no escapee, no Xvfb, no :90
socket, no runtime dir, no cgroup and no token-carrying process remained.
Round 2 adds a CLI smoke where session destroy runs from inside the session:
the caller survives, everything else is gone.

🤖 Generated with Claude Code

Desktop sessions stopped the process group they started, so an app that
double-forked or called setsid survived teardown, and they inherited the
user's XDG_RUNTIME_DIR and D-Bus endpoints, so toolkits and portals could
route work back through the real user session.

Every desktop session now owns a containment scope: a private cgroup v2
directory inside the delegated cgroup the lab already runs in, or, where no
delegation exists, a per-session 256-bit token exported as
PICKFORGE_CONTAINMENT_TOKEN. Apps start through a supervisor that joins the
scope before spawning them, so a descendant cannot be forked outside it.
Neither mechanism needs sudo. Cleanup selects targets by cgroup membership or
by an exact token re-read from /proc/<pid>/environ, never by a remembered pid,
refuses a pid whose identity no longer matches, excludes the caller's own
process chain, and reports success only once the scope is confirmed empty.

Each session also gets its own XDG_RUNTIME_DIR (mode 0700, inside the session
directory) and its own D-Bus addresses pointing at sockets Pickforge never
creates, so a bus connection fails closed. The directory is removed on
teardown only after contained processes are confirmed gone, and removal is
refused for any path not confined to the session directory, symlinks included.

Xvfb teardown now shares one stopOwnedDaemonGroup with the browser supervisor:
group signal plus isProcessGroupAlive confirmation, so an exited daemon is
never reported gone while a group member survives. stopXvfb verifies the
group-leader identity instead of signalling a bare pid.

Closes #85
Closes #86
Closes #57
Refs #89
@ElbertePlinio ElbertePlinio mentioned this pull request Sep 4, 2026
56 of 58 tasks
…, isolate late VNC

Fixes for the PR #92 review (review-pr92.md blockers and P2s):

- cgroup.kill excluded nothing: `session destroy` run from inside a
  contained shell killed itself before Xvfb/VNC/runtime cleanup. Cleanup now
  moves its own process chain into the parent cgroup, confirms from
  cgroup.procs that none of it is still a member, and only then writes
  cgroup.kill; if the chain cannot be moved it refuses with an actionable
  reason instead of terminating the caller.
- A PID that exited between the /proc scan and the pre-signal token re-read
  was treated as an identity mismatch and failed the destroy. It is now
  skipped as gone; only a live PID without the exact token is refused.
- ensureSessionVnc, takeover start and takeover revert started x11vnc with
  the caller's XDG_RUNTIME_DIR and D-Bus addresses. One startSessionVnc
  helper now attaches the session runtime on every VNC start path.
- NODE_OPTIONS, NODE_PATH, NODE_REPL_EXTERNAL_MODULE and BUN_OPTIONS are
  stripped from the desktop environment so nothing runs inside the Node
  supervisor before it joins the scope; `desktop env` lists them as unset.
- The supervisor no longer believes a successful cgroup.procs write: it reads
  its membership back from /proc/self/cgroup and exits 126 without spawning
  the app otherwise. Cleanup and launch refuse any recorded cgroup path that
  is not a pickforge-* directory on a cgroup v2 filesystem, so a tampered
  record cannot aim cgroup.kill at the lab's own cgroup.
- The supervisor forwards SIGTERM/SIGINT/SIGHUP to the app instead of
  ignoring them, so a marker destroy no longer waits out the whole SIGTERM
  budget.
- Cgroup-only tests skip explicitly and the suite logs the mechanism the
  host selected. The runtime directory is removed only once contained apps,
  x11vnc and Xvfb are all confirmed gone. Non-Linux hosts report cleanup as
  unconfirmed instead of trivially empty. Header comment and SECURITY.md now
  describe the actual gate (token re-read, not ProcessIdentity).

New adversarial tests: destroy-from-inside in cgroup mode (core worker and a
real-Xvfb session worker), vanished PID between scan and re-read, live PID
reuse refused, SIGKILL escalation, supervisor TERM forwarding and destroy
timing, false join through a writable non-cgroup directory, unavailable
scope cgroup, tampered cgroup path, cgroup.kill never aimed at the lab's own
cgroup, NODE_OPTIONS hijack through launchApp, and late x11vnc (watch,
takeover start, takeover revert) receiving the session runtime.
…t is not refused

CI (no cgroup delegation) failed the new destroy-from-inside test and the MCP
desktop flow's destroy on the marker path. Under CPU load a supervised app
that had just received the forwarded SIGTERM was probed while dying: same
PID, same start time, state R, address space already released, and
/proc/<pid>/environ failing with EACCES. The probe treated that as a live
identity mismatch and refused it, leaving cleanup unconfirmed.

The scan now records each contained process's identity (PID + start time)
and the pre-signal probe compares it: a changed start time is a recycled PID
and is refused; a missing or zombie process is gone; the same process whose
token is momentarily unreadable (dying, mid-exec, wiped, setuid) is neither
killed nor refused and is decided on a later pass. An empty scan must be
confirmed by a second empty scan one poll later so a process invisible to a
single scan cannot end the sweep early.

Also: PICKFORGE_CONTAINMENT=marker forces the marker mechanism so the
fallback path can be exercised on a delegated host (this is how the race was
reproduced); the teardown AggregateError message now includes the inner
failure messages; the MCP desktop test prints the tool's errors on failure;
the destroy-from-inside test prints the worker's report on failure.

Verified with 8 x 25 supervised marker destroys under full CPU load (0
refusals, previously 1-3 per 25), the focused marker suites under load, and
full runs with and without the marker override.
# Conflicts:
#	packages/browser/src/session.ts
…identified process

Review of PR #92 found two ways cleanup could act on the wrong processes, or
report success over the right ones.

A scope cgroup was only checked for shape: normalised, under /sys/fs/cgroup,
`pickforge-*` basename. Every *other* live session's scope passes that, so a
record carrying session A's token with session B's real cgroupDir killed B's
processes and reported confirmed. A scope now carries its session id and is
bound to the directory named `pickforge-<id>` inside a parent that is not
itself a scope; create, ensure, launch and destroy all go through the same
check, and a `cgroup` mechanism without a path is now a refusal rather than a
silent uncontained launch that still reports `cgroup`. As a second, live
proof, every remaining member must be shown to carry this session's token (or
to descend from an in-scope process that does) immediately before
`cgroup.kill`; a member that cannot be decided within a bounded retry window
fails cleanup instead of being killed unverified.

The marker sweep rebuilt its target list from readable token matches on every
pass, so a process it had already identified disappeared from the result when
its /proc/<pid>/environ stayed unreadable (EACCES, empty, or readable without
the token at the same start time). Two empty scans then confirmed cleanup over
a live process. Identities are now kept until the process is seen to be gone:
they are signalled when the token returns, refused when the start time changes,
and reported as unconfirmed survivors when they never settle.

Ancestor handling is now identity-based on both paths. `cgroup.procs` takes a
bare number, so the caller's chain is pinned by start time, re-verified as
both an ancestor and a member immediately before each write, and confirmed in
the parent cgroup afterwards; a pid that no longer matches is never written.
Marker-sweep exclusions compare start times too, so a recycled ancestor pid
neither exempts a contained process nor gets signalled as one.

Reproductions that fail at the previous head: an unrelated sibling scope kill,
a scope holding another session's token, a live target with a persistently
inaccessible environ, a target that becomes tokenless at the same start time,
and an in-cgroup destroy whose ancestor start time changes mid-cleanup.
… Xvfb pid

`startVnc` threw on the identity and timeout paths without returning anything
about the process it had spawned, and ignored the result of stopping it. The
create-time state therefore had no `state.vnc`, `stopStartupVnc` answered
"nothing to stop", and rollback could delete the session runtime directory and
drop the VNC identity from the retry record while that server was still alive.

`startVnc` now spawns an owned daemon and, on every post-spawn failure, stops
the whole process group and throws a typed `VncStartError` carrying a
`VncPartialStart`: pid, start ticks when readable, port, log path, and whether
the group is confirmed empty. This mirrors `XvfbPartialStart` (#57). A failed
create keeps the partial, so `cleanupConfirmed: false` preserves the runtime
directory, records the VNC identity, and marks the record for a reaper retry.
An x11vnc that died during startup is now cleaned up by group as well, since a
dead leader can still have left a child behind.

`stopXvfb(pid)` without recorded start ticks snapshotted whatever process held
the pid and then verified that snapshot, which proves nothing about the Xvfb
the caller meant: a recycled pid belonging to an unrelated process-group leader
verified and was killed. It now refuses a live pid outright and reports success
only for a pid that is already gone. Session teardown is unaffected; it passes
the recorded ticks.
…ation

The real-cgroup tests skip wherever no cgroup is delegated, which is every CI
runner, so the new pre-kill member verification and identity-pinned chain
migration were only ever exercised on a delegated host. That also dropped
global line coverage below the 82 % gate on CI.

This simulates only the kernel interface — `statfs`, `cgroup.procs`,
`cgroup.kill`, `rmdir` and `/proc/<pid>/cgroup` — while the members, their
`/proc/<pid>/environ` and every signal stay real, so the decisions under test
run everywhere: a scope whose members all carry the token is killed; a member
whose own environ is unreadable is accepted through its in-scope parent; a
member with no token, or one whose ownership never becomes readable, refuses
the kill; the caller's own chain is moved out and confirmed before the kill;
and a failed, misdirected or unreadable move refuses instead of killing the
caller. The real-cgroup suite remains the ground truth for the same paths.
@ElbertePlinio
ElbertePlinio merged commit 4da0a33 into main Sep 5, 2026
5 checks passed
@ElbertePlinio
ElbertePlinio deleted the fix/alpha2-isolation branch September 5, 2026 00:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant