carlos / platform Public

witness: an interactive session is inside its instance (rootfs plan 6)

Task 15 steps 1 and 2: three root-runner witnesses (linux && rootrunner),
run as root under real systemd on the arm64 root runner, all PASS.

- TestInteractiveSessionIsInsideTheInstance: two nested binary instances;
  the agent half as carlos starts sessions through the real
  ExecBackend.StartCmd against the real control service and templates.
  Slice and unit, namespace, pts-private, fd 0 is the agent's pty, a's pty
  unreachable from b (ENOENT) and from the host (EBUSY), a same-uid connect
  before PID 1 gets nothing; beyond the brief, ExecStopPost=instance-exit
  runs after the stop (exit record written, unit not failed) and the
  handoff socket goes at the settle.
- TestInteractiveSessionRefusedWhenTheAppDisallows: the session worker over
  the real activator ends refused "off" and no tty unit is ever started.
- TestRootfsRunIsInsideTheInstance: carlos run through the real rootfs cmd
  unit on a box whose probes pass for real; the command runs in the unit's
  cgroup under the host's slice and its / is the image's.

activator.StartCmdServing (rootrunner tag only, never in the platform
binary) hands StartCmd the staged build and launch environment RunCmd sets
from the awake entry, which the runner cannot have without the lease
bucket.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6ace84d6a9dba65d668ce25db1da41e85256c8b2 parent 6bbe8cd
2 files changed, +1,378 −0
  • internal/activator/witness_rootrunner_linux.go +51 −0
  • internal/host/interactive_rootrunner_linux_test.go +1,327 −0

Intent

Human

<task-notification> <task-id>aebb31b964a387a07</task-id> <tool-use-id>toolu_01TJNobQHcuYZPbVuvCULGaU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/aebb31b964a387a07.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 13: CLI run -it, console" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Fix round 2 is done, and the restore-failure line now uses Paul's approved RFS-6-C75 text. Another change landed between my two commits: 571046c5 (console: audit refused attempts), from other work, which I left alone. **Commits** - 04b06443: fix round 2. - **Reader can't hang:** stdin is non-blocking for the session, with its flags restored at cleanup. A read that finds nothing goes back to the stop-aware wait, and cleanup tells the reader to stop before it restores the terminal. - **Change beyond the brief:** stdin and stdout usually share one terminal handle, so non-blocking stdin makes stdout non-blocking too. - A large burst of output could then have failed and ended the session with exit 1. stdout and stderr now wait and retry instead. - I also changed the terminal code to fetch each descriptor only once: Go's `os.File.Fd()` switches the handle back to blocking, which would have undone the fix on every window resize. - **Census:** overlay re-proposed with two claims extended (`openSession` and `fdInput.Read`). Seal moves from 977d75ba to 3e6d53be, and the record-write census re-pins `openSession`. - 6bbe8cd1: RFS-6-C75. - **Records:** the approved text replaces `restoreFailedMsg` byte for byte. Its deck row (with the 2026-10-31 approval note) and its `copy-approved.json`, `rootfsCopyIDs` and `rootfsCopyBuilt` entries are added. - **Census:** root envelope re-pinned; the seal stays 3e6d53be. **Tests:** run once, all pass (`-race` once on the CLI tests). A new test on a real terminal (`/dev/ptmx`) reproduces Astra's case: input arrives, the terminal goes back to normal mode and is flushed, then the reader is stopped. The reader returns within 1 s and the descriptor's flags come back unchanged. All 4 mutations were caught; copy, census and cross-builds are clean. **Known limit:** if carlos is killed with SIGKILL mid-session, the terminal stays non-blocking until bash clears it or the user runs `reset`. The fix report is appended to `task-13-report.md`.</result> <usage><subagent_tokens>405556</subagent_tokens><tool_uses>20</tool_uses><duration_ms>546489</duration_ms></usage> </task-notification>

Attributed to this commit: 9.22 g CO₂e (1,177,236 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/activator/witness_rootrunner_linux.go b/internal/activator/witness_rootrunner_linux.go
new file mode 100644
index 000000000..a11a61886
--- /dev/null
+++ b/internal/activator/witness_rootrunner_linux.go
@@ -0,0 +1,51 @@
+//go:build linux && rootrunner
+
+package activator
+
+// The root runner's seam into a command's start (rootfs apps Plan 6 Task
+// 15). Built only with the rootrunner tag, so never into the platform
+// binary.
+//
+// StartCmd runs only what RunCmd admitted: the serving generation's staged
+// build and the environment it launched with come from the awake entry.
+// A witness on the runner cannot have an awake entry, because a wake needs
+// the hibernate bucket's lease and the runner reaches no bucket. So the
+// witness hands StartCmd those two values, set exactly as RunCmd sets
+// them, and everything after that is StartCmd's own path.
+
+import (
+ "context"
+ "fmt"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/instancekey"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// StartCmdServing is StartCmd with serving and genEnv as RunCmd sets them
+// from the generation it admitted the command against.
+func (b *ExecBackend) StartCmdServing(ctx context.Context, rt registry.Route, spec CmdSpec, serving *instancectl.StagedExe, genEnv map[string]string) (CmdUnit, error) {
+ spec.serving, spec.genEnv, spec.genKeyLayer = serving, genEnv, instancekey.LayerNone
+ return b.StartCmd(ctx, rt, spec)
+}
+
+// TerminalPTN is a session terminal's pty number: TIOCGPTN on the master
+// the agent kept.
+func TerminalPTN(t Terminal) (int, error) {
+ pt, ok := t.(*ptyTerminal)
+ if !ok || pt == nil {
+ return 0, fmt.Errorf("terminal %T is not a pty", t)
+ }
+ raw, err := pt.master.SyscallConn()
+ if err != nil {
+ return 0, err
+ }
+ var n int
+ var ioctlErr error
+ if err := raw.Control(func(fd uintptr) { n, ioctlErr = unix.IoctlGetInt(int(fd), unix.TIOCGPTN) }); err != nil {
+ return 0, err
+ }
+ return n, ioctlErr
+}
diff --git a/internal/host/interactive_rootrunner_linux_test.go b/internal/host/interactive_rootrunner_linux_test.go
new file mode 100644
index 000000000..b8924a462
--- /dev/null
+++ b/internal/host/interactive_rootrunner_linux_test.go
@@ -0,0 +1,1327 @@
+//go:build linux && rootrunner
+
+package host
+
+// Production-wired witnesses for interactive sessions (rootfs apps spec
+// §5.10/C9, Plan 6 Task 15), run as root under real systemd on the root
+// runner. The box is the pre-claim box of the egress witnesses
+// (egress_fixtures_rootrunner_linux_test.go): the instance templates from
+// unitsFS in /run/systemd/system with their edge and mount dependencies
+// dropped and everything else verbatim, the real control service
+// (instancectl.Server with the production pre-claim fields) on the real
+// control socket, the registry the agent writes, and this test binary at
+// /opt/carlos/carlos (the trampoline and the exit record, instance-exec and
+// instance-exit) and as the staged build behind each host's live link.
+// The rootfs witness's box adds what a rootfs start's gates ask for: the
+// three bind mount units verbatim, both probes run for real by the control
+// service (which needs the edge's delegated cgroup, so a transient
+// carlos-edge.service with the edge's user, slice and delegation stands in
+// for it), and a squashfs image staged with its manifest.
+//
+// The agent half runs as carlos in a child process (TestIxrAgentHalf), as
+// the agent does: its sessions' handoff sockets are carlos's, as on a box,
+// so a same-uid connect is the real threat the root-peer check stands
+// against. It starts each session through the real ExecBackend.StartCmd,
+// handed the staged build and launch environment RunCmd would set
+// (activator.StartCmdServing; a wake needs the lease bucket, which the
+// runner does not reach).
+
+import (
+ "archive/tar"
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootfsimage"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+const (
+ ixrHostA = "a.example.com"
+ ixrHostB = "b.example.com"
+ // ixrHostR is the rootfs witness's host, a rootfs-v1 row.
+ ixrHostR = "r.example.com"
+ // ixrPayloadArg is the payload's argv[1]: this binary, run as the
+ // session's command inside the tty unit.
+ ixrPayloadArg = "session-payload"
+ // ixrReportPrefix marks the payload's one report line on the pty;
+ // ixrByePrefix the line it prints once it has read a line of input.
+ ixrReportPrefix = "SESSION-REPORT "
+ ixrByePrefix = "SESSION-BYE "
+ // ixrAgentPrefix marks the agent half's report on its stdout.
+ ixrAgentPrefix = "IXR-AGENT "
+ ixrVersion = "v1"
+)
+
+// ixrApps is each host's app, all bah's.
+var ixrApps = map[string]string{ixrHostA: "shop", ixrHostB: "blog", ixrHostR: "tool"}
+
+// ixrImageMarker is /etc/witness-image in the rootfs witness's image: a
+// file the box does not have, so reading it says / is the image's.
+const ixrImageMarker = "carlos rootfs witness image"
+
+// ixrBoxOpts says which box a witness gets: the session witnesses' two
+// binary hosts, or the rootfs witness's one rootfs host, which also needs
+// the three bind mounts and both probes passed (the rootfs gates).
+type ixrBoxOpts struct {
+ rootfs bool
+}
+
+func (o ixrBoxOpts) hosts() []string {
+ if o.rootfs {
+ return []string{ixrHostR}
+ }
+ return []string{ixrHostA, ixrHostB}
+}
+
+// templates are the unit templates the witness starts.
+func (o ixrBoxOpts) templates() []string {
+ if o.rootfs {
+ return []string{"carlos-instance-rootfs-cmd@.service", instancectl.RootfsProbeUnit}
+ }
+ return []string{"carlos-instance-tty@.service"}
+}
+
+// units are the units the witness may start.
+func (o ixrBoxOpts) units() []string {
+ if o.rootfs {
+ return []string{instancectl.RootfsUnitName(instancectl.RoleCmd, ixrHostR), instancectl.RootfsProbeUnit}
+ }
+ return []string{instancectl.UnitName(instancectl.RoleTTY, ixrHostA), instancectl.UnitName(instancectl.RoleTTY, ixrHostB)}
+}
+
+// The payload: the session's command (modes "report" and "pts"), or the
+// rootfs run's (mode "rootfs", as /bin/witness in the image). It reports
+// what it sees from inside its unit on its stdout, the pty for a session,
+// and in "report" mode then waits for one line of input.
+func init() {
+ if len(os.Args) >= 3 && os.Args[1] == ixrPayloadArg {
+ ixrPayload(os.Args[2:])
+ os.Exit(0)
+ }
+}
+
+// ixrPayloadReport is what a session's command saw.
+type ixrPayloadReport struct {
+ Cgroup string `json:"cgroup"`
+ DataInstances []string `json:"data_instances"`
+ DataInstancesErr string `json:"data_instances_err,omitempty"`
+ OptLive []string `json:"opt_live"`
+ OptLiveErr string `json:"opt_live_err,omitempty"`
+ DevPts []string `json:"dev_pts"`
+ DevPtsErr string `json:"dev_pts_err,omitempty"`
+ PtmxErr string `json:"ptmx_err"`
+ TTYS string `json:"tty_s"` // "" when tty -s succeeded
+ Fd0Major uint32 `json:"fd0_major"`
+ Fd0Minor uint32 `json:"fd0_minor"`
+ Fd0Err string `json:"fd0_err,omitempty"`
+ Fd0TCGETS string `json:"fd0_tcgets"` // "" when fd 0 answered TCGETS
+ PtsOpen string `json:"pts_open,omitempty"`
+ PtsOpenErrno int `json:"pts_open_errno,omitempty"`
+ // The rootfs mode's: / and the image's marker, and the box's own file.
+ Root []string `json:"root,omitempty"`
+ RootMarker string `json:"root_marker,omitempty"`
+ BoxFileErr string `json:"box_file_err,omitempty"`
+}
+
+func ixrErr(err error) string {
+ if err == nil {
+ return ""
+ }
+ return err.Error()
+}
+
+func ixrNames(dir string) ([]string, string) {
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, err.Error()
+ }
+ names := []string{}
+ for _, e := range ents {
+ names = append(names, e.Name())
+ }
+ return names, ""
+}
+
+func ixrPayload(args []string) {
+ var r ixrPayloadReport
+ if cg, err := os.ReadFile("/proc/self/cgroup"); err == nil {
+ r.Cgroup = strings.TrimSpace(string(cg))
+ } else {
+ r.Cgroup = "error: " + err.Error()
+ }
+ r.DataInstances, r.DataInstancesErr = ixrNames("/data/instances")
+ r.OptLive, r.OptLiveErr = ixrNames("/opt/carlos/live")
+ r.DevPts, r.DevPtsErr = ixrNames("/dev/pts")
+ mode := args[0]
+ if mode == "rootfs" {
+ // A run's command in the rootfs cmd unit: no terminal; where it
+ // runs and what its / is.
+ r.Root, _ = ixrNames("/")
+ if b, err := os.ReadFile("/etc/witness-image"); err == nil {
+ r.RootMarker = strings.TrimSpace(string(b))
+ } else {
+ r.RootMarker = "error: " + err.Error()
+ }
+ _, err := os.Stat("/etc/debian_version")
+ r.BoxFileErr = ixrErr(err)
+ raw, _ := json.Marshal(r)
+ fmt.Printf("%s%s\n", ixrReportPrefix, raw)
+ // Leave the agent time to find this process in the unit's cgroup
+ // from outside.
+ time.Sleep(3 * time.Second)
+ return
+ }
+ if fd, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0); err != nil {
+ r.PtmxErr = err.Error()
+ } else {
+ unix.Close(fd)
+ }
+ tty := exec.Command("/usr/bin/tty", "-s")
+ tty.Stdin = os.Stdin
+ r.TTYS = ixrErr(tty.Run())
+ var st unix.Stat_t
+ if err := unix.Fstat(0, &st); err != nil {
+ r.Fd0Err = err.Error()
+ } else {
+ r.Fd0Major, r.Fd0Minor = unix.Major(st.Rdev), unix.Minor(st.Rdev)
+ }
+ _, err := unix.IoctlGetTermios(0, unix.TCGETS)
+ r.Fd0TCGETS = ixrErr(err)
+ if mode == "pts" && len(args) == 2 {
+ fd, err := unix.Open("/dev/pts/"+args[1], unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err == nil {
+ unix.Close(fd)
+ r.PtsOpen = "opened"
+ } else {
+ r.PtsOpen = err.Error()
+ var errno syscall.Errno
+ if errors.As(err, &errno) {
+ r.PtsOpenErrno = int(errno)
+ }
+ }
+ }
+ raw, _ := json.Marshal(r)
+ fmt.Printf("%s%s\n", ixrReportPrefix, raw)
+ if mode == "report" {
+ line, _ := bufio.NewReader(os.Stdin).ReadString('\n')
+ fmt.Printf("%s%s\n", ixrByePrefix, strings.TrimSpace(line))
+ }
+ // Leave the agent time to read the last line before the slave closes.
+ time.Sleep(300 * time.Millisecond)
+}
+
+// ixrBox is the pre-claim box with two nested hosts, a and b.
+type ixrBox struct {
+ uid, gid int
+ reg *registry.Registry
+ staged map[string]instancectl.StagedExe
+ srv *instancectl.Server
+
+ mu sync.Mutex
+ starts []string // every unit the control service asked systemd to start
+}
+
+func (b *ixrBox) started() []string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return append([]string(nil), b.starts...)
+}
+
+// ixrRow is host's nested row, provisioned and activator-managed.
+func ixrRow(host string) registry.Route {
+ rt := registry.Route{Host: host, Kind: "instance", Account: ixAcct, App: ixrApps[host], Channel: "stable", Hibernate: true,
+ Status: "ready", Provisioned: true, DBPath: provision.NestedDBPath("/data", host), Socket: provision.NestedSocket(host)}
+ if host == ixrHostR {
+ rt.Runtime = registry.RuntimeRootfsV1
+ }
+ return rt
+}
+
+// ixrInstallTemplate installs name from unitsFS into /run/systemd/system as
+// the egress witnesses do: the edge and mount dependencies dropped (the
+// runner has neither), everything else verbatim. Removed on cleanup.
+func ixrInstallTemplate(t *testing.T, name string) {
+ t.Helper()
+ for _, dir := range []string{"/run/systemd/system", "/etc/systemd/system"} {
+ if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal("template already installed", dir, name, err)
+ }
+ }
+ raw, err := unitsFS.ReadFile("units/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lines []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") {
+ continue
+ }
+ lines = append(lines, line)
+ }
+ path := filepath.Join("/run/systemd/system", name)
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, werr := f.WriteString(strings.Join(lines, "\n"))
+ if err := errors.Join(werr, f.Close()); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.Remove(path); err != nil {
+ t.Error(err)
+ }
+ if out, err := egressCtl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ })
+}
+
+func newIxrBox(t *testing.T, o ixrBoxOpts) *ixrBox {
+ t.Helper()
+ egressRootPrereqs(t)
+ uid, gid := generationRunnerRegistryUser(t)
+ b := &ixrBox{uid: uid, gid: gid, staged: map[string]instancectl.StagedExe{}}
+ t.Setenv("CARLOS_DATA_DIR", "/data") // instanceRegistryHostApp reads dataDir()
+ hosts, units := o.hosts(), o.units()
+ for _, u := range units {
+ if state := egressShow(t, u, "LoadState"); state != "not-found" {
+ t.Fatal("unit already present", u, state)
+ }
+ }
+
+ // Fixture roots: refused if present, removed last.
+ for _, p := range []string{"/data", "/opt/carlos", "/run/carlos", controlsock.Dir, "/etc/carlos"} {
+ if err := os.Mkdir(p, 0o755); err != nil {
+ t.Fatal("fixture root already exists", p, err)
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(p); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+
+ // The build: this binary as the platform binary and as each host's
+ // staged build, behind its live link.
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ image, err := os.ReadFile(exe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(instancectl.SystemBinary, image, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(image)
+ if err := os.MkdirAll(filepath.Dir(release.LiveLink("/opt/carlos", ixrHostA)), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ for _, h := range hosts {
+ staged := release.VersionPath("/opt/carlos", ixAcct, ixrVersion, ixrApps[h])
+ if err := os.MkdirAll(filepath.Dir(staged), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if h == ixrHostR {
+ b.staged[h] = ixrStageImage(t, staged, image)
+ continue
+ }
+ if err := os.WriteFile(staged, image, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(staged, release.LiveLink("/opt/carlos", h)); err != nil {
+ t.Fatal(err)
+ }
+ b.staged[h] = instancectl.StagedExe{Path: staged, Version: ixrVersion, Digest: hex.EncodeToString(sum[:])}
+ }
+
+ // The instances' directories and the logs directory, the carlos user's:
+ // the agent half makes its sessions' handoff sockets there.
+ if err := os.Chown("/data", uid, gid); err != nil {
+ t.Fatal(err)
+ }
+ if o.rootfs {
+ // The rootfs gates ask the nested gate, which wants the three
+ // bind mounts (nosymfollow) and a passed probe: the real mount
+ // units, verbatim.
+ ixrMounts(t, uid, gid)
+ }
+ type dir struct {
+ path string
+ mode fs.FileMode
+ }
+ dirs := []dir{{filepath.Join(provision.SocketDir, "logs"), 0o700}}
+ for _, h := range hosts {
+ dirs = append(dirs, dir{provision.InstanceDir("/data", h), 0o700}, dir{provision.InstanceRunDir(h), 0o750 | fs.ModeSetgid})
+ }
+ for _, d := range dirs {
+ if err := os.MkdirAll(d.path, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := errors.Join(os.Chown(d.path, uid, gid), os.Chmod(d.path, d.mode)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for _, name := range o.templates() {
+ ixrInstallTemplate(t, name)
+ }
+ if o.rootfs {
+ // The binary probe's unit and fixtures (the egress witnesses'):
+ // the rootfs readiness needs both probes passed.
+ egressProbeFixture(t, uid, gid)
+ }
+ egressMustCtl(t, "daemon-reload")
+ for _, h := range hosts {
+ egressSliceProperties(t, instancectl.SliceName(h))
+ }
+ if o.rootfs {
+ ixrEdgeStandIn(t)
+ }
+ t.Cleanup(func() {
+ for _, u := range units {
+ if out, _ := egressCtl("show", "-p", "LoadState", "--value", u); out != "not-found" {
+ if out, err := egressCtl("stop", u); err != nil {
+ t.Errorf("stop %s: %v: %s", u, err, out)
+ }
+ }
+ egressCtl("reset-failed", u)
+ if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", u+".d")); err != nil {
+ t.Error(err)
+ }
+ }
+ })
+
+ // The registry, written as the agent writes it.
+ reg, err := openServiceRegistry("/data/registry.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ for _, h := range hosts {
+ if err := reg.Upsert(ixrRow(h)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ b.reg = reg
+
+ // The control service as runWithClaim builds it on a pre-claim box,
+ // minus the socket activation, the probe loop and the disk floors, on
+ // the real socket path, which only the carlos user may connect to.
+ srv := &instancectl.Server{
+ Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ if len(args) > 0 && args[0] == "start" {
+ b.mu.Lock()
+ b.starts = append(b.starts, args[len(args)-1])
+ b.mu.Unlock()
+ }
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ },
+ CgroupRoot: "/sys/fs/cgroup",
+ Logf: t.Logf,
+ ExeRoot: filepath.Join(controlsock.Dir, "exe"),
+ OptDir: "/opt/carlos",
+ HostApp: instanceRegistryHostApp(nil),
+ HostRuntime: instanceRegistryHostRuntime,
+ DropInDir: "/run/systemd/system",
+ LocalAddrs: instancectl.LocalAddresses,
+ DataRoot: "/data/instances",
+ Egress: newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data")),
+ // The agent's client checks the service runs its own build.
+ Build: version.Build,
+ }
+ if o.rootfs {
+ // The probe's production fields (runWithClaim's).
+ srv.ProbeOut = egressProbeOut
+ srv.FixtureOK = instancectl.ProbeFixturesOK
+ srv.ResolvConf = "/etc/resolv.conf"
+ srv.ResolvedConf = instancectl.ResolvedConf
+ srv.ProbeImage = instancectl.BuildProbeImage
+ srv.ProbeImageFile = instancectl.ProbeImagePath
+ srv.RootfsProbeOut = filepath.Join(controlsock.Dir, "rootfs-probe.out")
+ }
+ // The production check wants the edge unit's main process; here the
+ // agent half is the carlos user's child, so its uid is the check.
+ srv.PeerOK = func(c net.Conn) error {
+ uc, ok := c.(*net.UnixConn)
+ if !ok {
+ return fmt.Errorf("peer %T is not a unix connection", c)
+ }
+ raw, err := uc.SyscallConn()
+ if err != nil {
+ return err
+ }
+ var cred *unix.Ucred
+ var credErr error
+ if err := raw.Control(func(fd uintptr) { cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) }); err != nil {
+ return err
+ }
+ if credErr != nil {
+ return credErr
+ }
+ if int(cred.Uid) != uid {
+ return fmt.Errorf("peer uid %d is not carlos (%d)", cred.Uid, uid)
+ }
+ return nil
+ }
+ ln, err := net.Listen("unix", controlsock.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := errors.Join(os.Chown(controlsock.Path, uid, gid), os.Chmod(controlsock.Path, 0o600)); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- srv.Serve(ctx, ln) }()
+ t.Cleanup(func() {
+ cancel()
+ if err := <-done; err != nil {
+ t.Error("control service:", err)
+ }
+ })
+ b.srv = srv
+ if o.rootfs {
+ // The probe loop's first pass, as the service runs it at start.
+ pctx, pcancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ srv.RunProbe(pctx)
+ pcancel()
+ bin, nested := srv.Ready()
+ for _, l := range bin.Lines {
+ t.Logf("probe: %s %s %s", l.Check, l.Verdict, l.Detail)
+ }
+ rf, ready := srv.ReadyRootfs()
+ for _, l := range rf.Lines {
+ t.Logf("rootfs probe: %s %s %s", l.Check, l.Verdict, l.Detail)
+ }
+ t.Logf("probe: nested %v, rootfs ready %v", nested, ready)
+ if !ready {
+ t.Fatalf("the rootfs probe did not pass on the runner (nested %v)\n%s\n%s", nested, ixrJournal(egressProbeUnit), ixrJournal(instancectl.RootfsProbeUnit))
+ }
+ }
+ return b
+}
+
+// ixrEdgeStandIn runs a transient carlos-edge.service with the edge's
+// user, slice and delegation (carlos-edge.service's User=, Slice= and
+// Delegate=), running nothing but a sleep. The probe's cgroup-ro check
+// tests a write to the edge's delegated cgroup.procs, so it needs the edge
+// loaded; the runner has no edge of its own. Stopped on cleanup.
+func ixrEdgeStandIn(t *testing.T) {
+ t.Helper()
+ const edge = "carlos-edge.service"
+ if state := egressShow(t, edge, "LoadState"); state != "not-found" {
+ t.Fatal("unit already present", edge, state)
+ }
+ if out, err := exec.Command("systemd-run", "--unit="+edge, "--slice=carlos.slice", "--property=User=carlos", "--property=Group=carlos",
+ "--property=Delegate=cpu memory io pids", "--description=witness stand-in for the edge", "/bin/sleep", "infinity").CombinedOutput(); err != nil {
+ t.Fatalf("systemd-run %s: %v: %s", edge, err, out)
+ }
+ t.Cleanup(func() {
+ if out, err := egressCtl("stop", edge); err != nil {
+ t.Errorf("stop %s: %v: %s", edge, err, out)
+ }
+ egressCtl("reset-failed", edge)
+ })
+}
+
+// ixrMounts installs and starts the three bind mounts from unitsFS,
+// verbatim, over directories of the carlos user's. Stopped on cleanup,
+// before the fixture roots go.
+func ixrMounts(t *testing.T, uid, gid int) {
+ t.Helper()
+ mounts := []struct{ unit, what, where string }{
+ {"data-instances.mount", "/data/.instances", "/data/instances"},
+ {"run-carlos-instances.mount", "/run/carlos/.instances", "/run/carlos/instances"},
+ {"run-carlos-logs.mount", "/run/carlos/.logs", "/run/carlos/logs"},
+ }
+ for _, m := range mounts {
+ if state := egressShow(t, m.unit, "LoadState"); state != "not-found" {
+ t.Fatal("unit already present", m.unit, state)
+ }
+ mode := fs.FileMode(0o755)
+ if m.unit == "run-carlos-logs.mount" {
+ mode = 0o700
+ }
+ for _, d := range []string{m.what, m.where} {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := errors.Join(os.Chown(d, uid, gid), os.Chmod(d, mode)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ raw, err := unitsFS.ReadFile("units/" + m.unit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "\nWhat="+m.what+"\n") || !strings.Contains(string(raw), "\nWhere="+m.where+"\n") {
+ t.Fatalf("%s is not %s on %s", m.unit, m.what, m.where)
+ }
+ path := filepath.Join("/run/systemd/system", m.unit)
+ if err := os.WriteFile(path, raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.Remove(path); err != nil {
+ t.Error(err)
+ }
+ if out, err := egressCtl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ })
+ }
+ egressMustCtl(t, "daemon-reload")
+ for _, m := range mounts {
+ egressMustCtl(t, "start", m.unit)
+ t.Cleanup(func() {
+ if out, err := egressCtl("stop", m.unit); err != nil {
+ t.Errorf("stop %s: %v: %s", m.unit, err, out)
+ }
+ })
+ }
+}
+
+// ixrStageImage stages the rootfs witness's image at staged, as root's
+// stage pass leaves it: a squashfs of this binary as /bin/witness and the
+// marker file, with the mount points every image needs, and the manifest
+// beside it naming it for this box's platform, with a web process. It
+// returns the identity the agent names it by.
+func ixrStageImage(t *testing.T, staged string, binary []byte) instancectl.StagedExe {
+ t.Helper()
+ var layer bytes.Buffer
+ tw := tar.NewWriter(&layer)
+ epoch := time.Unix(1, 0).UTC()
+ for _, e := range []struct {
+ name string
+ mode int64
+ body []byte
+ }{
+ {"bin/", 0o755, nil},
+ {"bin/witness", 0o755, binary},
+ {"etc/", 0o755, nil},
+ {"etc/witness-image", 0o644, []byte(ixrImageMarker + "\n")},
+ } {
+ h := &tar.Header{Name: e.name, Mode: e.mode, ModTime: epoch, Typeflag: tar.TypeReg, Size: int64(len(e.body))}
+ if strings.HasSuffix(e.name, "/") {
+ h.Typeflag, h.Size = tar.TypeDir, 0
+ }
+ if err := tw.WriteHeader(h); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(e.body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ tree := rootfsimage.NewTree(t.TempDir())
+ if err := tree.ApplyLayer(&layer); err != nil {
+ t.Fatal(err)
+ }
+ if err := rootfsimage.AddMountPoints(tree); err != nil {
+ t.Fatal(err)
+ }
+ out, err := os.OpenFile(staged, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := rootfsimage.WriteSquashfs(tree, out); err != nil {
+ out.Close()
+ t.Fatal(err)
+ }
+ if err := out.Close(); err != nil {
+ t.Fatal(err)
+ }
+ f, err := os.Open(staged)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := sha256.New()
+ size, err := io.Copy(h, f)
+ f.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ digest := hex.EncodeToString(h.Sum(nil))
+ m := release.Manifest{Schema: 1, App: ixrApps[ixrHostR], Version: ixrVersion, Kind: release.KindRootfs,
+ Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile, SHA256: digest, Size: size}},
+ Processes: map[string]release.Process{release.ProcessWeb: {Command: []string{"/bin/witness", "serve"}, Env: map[string]string{"PATH": "/bin"}, WorkingDir: "/"}}}
+ raw, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(release.StagedManifestPath("/opt/carlos", ixAcct, ixrVersion, ixrApps[ixrHostR]), raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return instancectl.StagedExe{Path: staged, Version: ixrVersion, Digest: digest}
+}
+
+// ixrAgentReport is the agent half's report.
+type ixrAgentReport struct {
+ A, B ixrSession
+ // R is the rootfs witness's run, with its two streams.
+ R ixrSession
+ RStdout, RErrs string
+ // RCgroup is the run unit's cgroup as the box sees it, and the command
+ // lines of the processes it held while the command ran.
+ RCgroup string
+ RCmdline []string
+ // PTN is session a's pty number, TIOCGPTN on the master.
+ PTN int
+ PTNErr string
+ // HostOpen is the agent's (carlos, outside every namespace) open of
+ // a's /dev/pts/<PTN>.
+ HostOpen string
+ HostOpenErrno int
+ Intruder ixrIntrusion
+ Err string
+}
+
+type ixrSession struct {
+ Invocation string
+ Report ixrPayloadReport
+ Bye string
+ Final instancectl.CmdStatus
+ SettleErr string
+ // SocketGone: the handoff socket's path was gone after the settle.
+ SocketGone bool
+ SocketErr string
+}
+
+// ixrIntrusion is a non-root connect to a's handoff socket made before
+// PID 1's: what it received.
+type ixrIntrusion struct {
+ Ran bool
+ Bytes int
+ OOB int
+ ReadErr string
+ DialErr string
+ EOF bool
+ BeforePOS bool // made before POST /tty was sent
+}
+
+// agent runs the agent half as carlos and returns its report.
+func (b *ixrBox) agent(t *testing.T, scenario string) ixrAgentReport {
+ t.Helper()
+ // The copy at /opt/carlos/carlos: carlos cannot enter the runner's
+ // own directory.
+ cmd := exec.Command(instancectl.SystemBinary, "-test.run", "^TestIxrAgentHalf$", "-test.v", "-test.timeout", "5m")
+ cmd.Dir = "/"
+ cmd.Env = append(os.Environ(), "IXR_AGENT="+scenario, "CARLOS_DATA_DIR=/data")
+ cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(b.uid), Gid: uint32(b.gid)}}
+ var out, errs bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &out, &errs
+ runErr := cmd.Run()
+ t.Logf("agent half (%s) stderr:\n%s", scenario, errs.String())
+ t.Logf("agent half (%s) stdout:\n%s", scenario, out.String())
+ sc := bufio.NewScanner(&out)
+ sc.Buffer(make([]byte, 1<<20), 1<<20)
+ for sc.Scan() {
+ if line, ok := strings.CutPrefix(sc.Text(), ixrAgentPrefix); ok {
+ var rep ixrAgentReport
+ if err := json.Unmarshal([]byte(line), &rep); err != nil {
+ t.Fatalf("agent half: unreadable report %q: %v", line, err)
+ }
+ if runErr != nil || rep.Err != "" {
+ t.Fatalf("agent half failed: %v: %s", runErr, rep.Err)
+ }
+ return rep
+ }
+ }
+ t.Fatalf("agent half gave no report: %v", runErr)
+ return ixrAgentReport{}
+}
+
+// ixrJournal is unit's journal, every invocation.
+func ixrJournal(unit string) string {
+ out, _ := exec.Command("journalctl", "--no-pager", "-o", "short-precise", "-u", unit).CombinedOutput()
+ return string(out)
+}
+
+// TestInteractiveSessionIsInsideTheInstance: two nested instances, a and
+// b, on the real templates and the real control service; the agent half
+// as carlos starts sessions through the real ExecBackend.
+func TestInteractiveSessionIsInsideTheInstance(t *testing.T) {
+ b := newIxrBox(t, ixrBoxOpts{})
+ rep := b.agent(t, "sessions")
+ a, bb := rep.A.Report, rep.B.Report
+ ttyA := instancectl.UnitName(instancectl.RoleTTY, ixrHostA)
+ ttyB := instancectl.UnitName(instancectl.RoleTTY, ixrHostB)
+ t.Logf("session a: invocation %s, report %+v", rep.A.Invocation, a)
+ t.Logf("session b: invocation %s, report %+v", rep.B.Invocation, bb)
+ t.Logf("pty %d; host open %q (errno %d); intruder %+v", rep.PTN, rep.HostOpen, rep.HostOpenErrno, rep.Intruder)
+
+ // 1. The payload ran on the pty and reported.
+ if a.Cgroup == "" || rep.A.Invocation == "" {
+ t.Fatalf("1: session a gave no report: %+v", rep.A)
+ }
+ t.Logf("WITNESS 1 ok: session a started (%s) and reported", rep.A.Invocation)
+
+ // 2. The slice and the unit (C5/C9).
+ wantCG := instancectl.SliceName(ixrHostA) + "/" + ttyA
+ if !strings.HasSuffix(a.Cgroup, wantCG) || strings.Count(a.Cgroup, "\n") != 0 {
+ t.Errorf("2: /proc/self/cgroup %q, want one line ending in %s", a.Cgroup, wantCG)
+ } else {
+ t.Logf("WITNESS 2 ok: /proc/self/cgroup %s", a.Cgroup)
+ }
+
+ // 3. The namespace: a's own instance directory and live link alone.
+ if a.DataInstancesErr != "" || !slices.Equal(a.DataInstances, []string{provision.InstanceID(ixrHostA)}) {
+ t.Errorf("3: /data/instances lists %q (%s), want only %s", a.DataInstances, a.DataInstancesErr, provision.InstanceID(ixrHostA))
+ } else {
+ t.Logf("WITNESS 3a ok: /data/instances lists %q", a.DataInstances)
+ }
+ if a.OptLiveErr != "" || !slices.Equal(a.OptLive, []string{ixrHostA}) {
+ t.Errorf("3: /opt/carlos/live holds %q (%s), want only %s", a.OptLive, a.OptLiveErr, ixrHostA)
+ } else {
+ t.Logf("WITNESS 3b ok: /opt/carlos/live holds %q", a.OptLive)
+ }
+
+ // 4. pts-private.
+ if a.DevPtsErr != "" || len(a.DevPts) != 0 || a.PtmxErr == "" {
+ t.Errorf("4: /dev/pts lists %q (%s), open(/dev/ptmx) %q: want an empty listing and a failed open", a.DevPts, a.DevPtsErr, a.PtmxErr)
+ } else {
+ t.Logf("WITNESS 4 ok: /dev/pts empty; open(/dev/ptmx): %s", a.PtmxErr)
+ }
+
+ // 5. fd 0 is a terminal, and it is the agent's pty.
+ ptn := -1
+ if a.Fd0Major >= 136 && a.Fd0Major <= 143 {
+ ptn = int(a.Fd0Major-136)<<8 | int(a.Fd0Minor)
+ }
+ if a.TTYS != "" || a.Fd0TCGETS != "" || rep.PTNErr != "" || ptn != rep.PTN {
+ t.Errorf("5: tty -s %q, TCGETS %q, fd 0 is %d:%d (pty %d), the master's TIOCGPTN %d (%s)", a.TTYS, a.Fd0TCGETS, a.Fd0Major, a.Fd0Minor, ptn, rep.PTN, rep.PTNErr)
+ } else {
+ t.Logf("WITNESS 5 ok: tty -s succeeded; fd 0 is %d:%d, pty %d, the master's TIOCGPTN %d", a.Fd0Major, a.Fd0Minor, ptn, rep.PTN)
+ }
+
+ // 6. a's pty from b's session, and from the host as carlos.
+ if bb.Cgroup == "" || bb.PtsOpenErrno != int(syscall.ENOENT) {
+ t.Errorf("6: from b's session open(/dev/pts/%d) = %q (errno %d), want ENOENT", rep.PTN, bb.PtsOpen, bb.PtsOpenErrno)
+ } else {
+ t.Logf("WITNESS 6a ok: from b's session (%s) open(/dev/pts/%d): %s", bb.Cgroup, rep.PTN, bb.PtsOpen)
+ }
+ if rep.HostOpenErrno != int(syscall.EBUSY) {
+ t.Errorf("6: from the host as carlos open(/dev/pts/%d) = %q (errno %d), want EBUSY", rep.PTN, rep.HostOpen, rep.HostOpenErrno)
+ } else {
+ t.Logf("WITNESS 6b ok: from the host as carlos open(/dev/pts/%d): %s", rep.PTN, rep.HostOpen)
+ }
+
+ // 7. A same-uid connect before PID 1's gets nothing; the unit still
+ // takes its terminal (1, 5).
+ if in := rep.Intruder; !in.Ran || !in.BeforePOS || in.DialErr != "" || in.Bytes != 0 || in.OOB != 0 || !in.EOF {
+ t.Errorf("7: the non-root connect: %+v, want a connection closed with no byte and no fd, before the start", in)
+ } else {
+ t.Logf("WITNESS 7 ok: a carlos connect before PID 1 read EOF with 0 bytes and 0 control bytes; the unit still started")
+ }
+
+ // Input reaches the command, which then exits 0.
+ if rep.A.Bye != "bye" || rep.A.Final.State != instancectl.CmdDone || rep.A.Final.Status != "0" {
+ t.Errorf("session a's end: bye %q, final %+v, want bye and done with status 0", rep.A.Bye, rep.A.Final)
+ } else {
+ t.Logf("WITNESS input ok: the command read %q and exited %s (%s)", rep.A.Bye, rep.A.Final.Status, rep.A.Final.Result)
+ }
+
+ // Beyond the brief: the stop's ExecStopPost (instance-exit) ran and
+ // succeeded for both sessions. Its exit record is written, the unit
+ // did not fail (a failed post command leaves it failed, result
+ // exit-code, EXIT_STDIN when the socket is gone), and the handoff
+ // socket went only at the settle.
+ for _, s := range []struct {
+ name, host, unit string
+ sess ixrSession
+ }{{"a", ixrHostA, ttyA, rep.A}, {"b", ixrHostB, ttyB, rep.B}} {
+ journal := ixrJournal(s.unit)
+ t.Logf("journal of %s:\n%s", s.unit, journal)
+ if s.sess.SettleErr != "" {
+ t.Errorf("session %s: StopAndSettle: %s", s.name, s.sess.SettleErr)
+ }
+ record := filepath.Join(provision.InstanceRunDir(s.host), instancectl.ExitRecordName(instancectl.RoleTTY, s.sess.Invocation))
+ raw, err := os.ReadFile(record)
+ var rec instancectl.ExitRecord
+ if err == nil {
+ err = json.Unmarshal(raw, &rec)
+ }
+ if err != nil || rec.Invocation != s.sess.Invocation {
+ t.Errorf("session %s: exit record %s: %v %s", s.name, record, err, raw)
+ } else {
+ t.Logf("WITNESS post-%s ok: instance-exit wrote %s: %s", s.name, record, raw)
+ }
+ state, result := egressShow(t, s.unit, "ActiveState"), egressShow(t, s.unit, "Result")
+ if state == "failed" || (result != "" && result != "success") || strings.Contains(journal, "STDIN") || strings.Contains(journal, "Failed with result") {
+ t.Errorf("session %s: %s is %s, result %q after the stop; the journal must show no failed post command", s.name, s.unit, state, result)
+ } else {
+ t.Logf("WITNESS post-%s ok: %s is %s, result %q, no failure in its journal", s.name, s.unit, state, result)
+ }
+ if !s.sess.SocketGone {
+ t.Errorf("session %s: the handoff socket is still there after the settle: %s", s.name, s.sess.SocketErr)
+ }
+ }
+ for _, u := range b.started() {
+ if strings.HasPrefix(u, instancectl.UnitPrefixTTY) && u != ttyA && u != ttyB {
+ t.Errorf("the control service started %s", u)
+ }
+ }
+}
+
+// TestInteractiveSessionRefusedWhenTheAppDisallows: the box's session
+// worker, with the real activator behind it, against an app whose setting
+// is off. The End is refused "off", and no tty unit was ever started: the
+// control service was asked to start nothing, systemd has no
+// carlos-instance-tty@ unit loaded, and its journal names none (C9).
+func TestInteractiveSessionRefusedWhenTheAppDisallows(t *testing.T) {
+ b := newIxrBox(t, ixrBoxOpts{})
+ since := time.Now().Add(-time.Second)
+ wd := newIxWorld(t)
+ if _, err := appconfig.SetInteractive(context.Background(), wd.store.Store, ixAcct, ixrApps[ixrHostA], false); err != nil {
+ t.Fatal(err)
+ }
+ eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: instancectl.NewClient(controlsock.Path)}
+ svc := activator.New(activator.Config{}, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{OptDir: "/opt/carlos"}}, b.reg)
+ wd.w = newInteractiveWorker(wd.store, b.reg.Get, svc, wd.pub, "runner")
+ wd.w.events = wd.events
+ rec := ixRecord(ixID(t), time.Now().Add(time.Minute))
+ rec.Host = ixrHostA
+ wd.grant(rec, nil, nil)
+ wd.w.note(rec)
+ wd.w.pass(context.Background())
+ e := wd.door.wantEnd(t)
+ wd.wait()
+ if e.Reason != interactive.EndRefused || e.Refused != interactive.RefusedOff {
+ t.Errorf("end %+v, want refused %q", e, interactive.RefusedOff)
+ } else {
+ t.Logf("WITNESS off ok: End %+v", e)
+ }
+ if got := b.started(); len(got) != 0 {
+ t.Errorf("the control service started %q", got)
+ }
+ out, err := exec.Command("systemctl", "list-units", "--all", "--plain", "--no-legend", instancectl.UnitPrefixTTY+"*").CombinedOutput()
+ if err != nil || strings.TrimSpace(string(out)) != "" {
+ t.Errorf("systemctl list-units %s*: %v %q, want none", instancectl.UnitPrefixTTY, err, out)
+ }
+ jr, err := exec.Command("journalctl", "--no-pager", "-q", "-o", "cat", "--since", "@"+strconv.FormatInt(since.Unix(), 10), "-u", instancectl.UnitPrefixTTY+"*").CombinedOutput()
+ if err != nil || strings.TrimSpace(string(jr)) != "" {
+ t.Errorf("journal of %s* since the session: %v %q, want nothing", instancectl.UnitPrefixTTY, err, jr)
+ }
+ if !t.Failed() {
+ t.Logf("WITNESS off ok: no start asked of the control service; list-units %q; journal %q", out, jr)
+ }
+}
+
+// ixrIntruderControl is the control client with one same-uid connect to
+// host's handoff socket made right before POST /tty is sent, after the
+// agent listens and before PID 1 can connect.
+type ixrIntruderControl struct {
+ *instancectl.Client
+ host string
+ got *ixrIntrusion
+}
+
+func (c *ixrIntruderControl) intrude(host string) {
+ if host != c.host || c.got.Ran {
+ return
+ }
+ c.got.Ran, c.got.BeforePOS = true, true
+ conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: provision.LogSocket(host, activator.TTYSocketName), Net: "unix"})
+ if err != nil {
+ c.got.DialErr = err.Error()
+ return
+ }
+ defer conn.Close()
+ _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
+ buf, oob := make([]byte, 64), make([]byte, 64)
+ n, oobn, _, _, err := conn.ReadMsgUnix(buf, oob)
+ c.got.Bytes, c.got.OOB = n, oobn
+ c.got.EOF = errors.Is(err, io.EOF)
+ if err != nil && !c.got.EOF {
+ c.got.ReadErr = err.Error()
+ }
+}
+
+func (c *ixrIntruderControl) TTY(ctx context.Context, host string, memoryMax int64) (string, error) {
+ c.intrude(host)
+ return c.Client.TTY(ctx, host, memoryMax)
+}
+
+func (c *ixrIntruderControl) TTYExe(ctx context.Context, host string, memoryMax int64, x instancectl.StagedExe) (string, error) {
+ c.intrude(host)
+ return c.Client.TTYExe(ctx, host, memoryMax, x)
+}
+
+// ixrTermReader collects a terminal's output until it ends.
+type ixrTermReader struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+ done chan struct{}
+}
+
+func ixrReadTerm(term activator.Terminal) *ixrTermReader {
+ r := &ixrTermReader{done: make(chan struct{})}
+ go func() {
+ defer close(r.done)
+ p := make([]byte, 4096)
+ for {
+ n, err := term.Read(p)
+ r.mu.Lock()
+ r.buf.Write(p[:n])
+ r.mu.Unlock()
+ if err != nil {
+ return
+ }
+ }
+ }()
+ return r
+}
+
+// line waits for the line that starts with prefix and returns its rest.
+func (r *ixrTermReader) line(prefix string, limit time.Duration) (string, error) {
+ deadline := time.Now().Add(limit)
+ for {
+ r.mu.Lock()
+ s := r.buf.String()
+ r.mu.Unlock()
+ if i := strings.Index(s, prefix); i >= 0 {
+ rest := s[i+len(prefix):]
+ if j := strings.IndexAny(rest, "\r\n"); j >= 0 {
+ return rest[:j], nil
+ }
+ }
+ select {
+ case <-r.done:
+ return "", fmt.Errorf("the terminal ended before %q: %q", prefix, s)
+ default:
+ }
+ if time.Now().After(deadline) {
+ return "", fmt.Errorf("no %q within %s: %q", prefix, limit, s)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// ixrUntilDone polls u until its invocation is no longer running.
+func ixrUntilDone(ctx context.Context, u activator.CmdUnit) (instancectl.CmdStatus, error) {
+ for {
+ st, err := u.Poll(ctx)
+ if err != nil {
+ return st, err
+ }
+ if st.State != instancectl.CmdRunning {
+ return st, nil
+ }
+ if ctx.Err() != nil {
+ return st, ctx.Err()
+ }
+ }
+}
+
+// ixrSettle stops and settles u, and checks its handoff socket is gone.
+func ixrSettle(ctx context.Context, u activator.CmdUnit, host string, s *ixrSession) {
+ s.SettleErr = ixrErr(u.StopAndSettle(ctx))
+ _, err := os.Lstat(provision.LogSocket(host, activator.TTYSocketName))
+ s.SocketGone = errors.Is(err, fs.ErrNotExist)
+ s.SocketErr = ixrErr(err)
+}
+
+// TestIxrAgentHalf is the agent half, run as carlos by ixrBox.agent;
+// never run it by name.
+func TestIxrAgentHalf(t *testing.T) {
+ scenario := os.Getenv("IXR_AGENT")
+ if scenario == "" {
+ t.Skip("run by the interactive root-runner witnesses as their carlos child")
+ }
+ var rep ixrAgentReport
+ defer func() {
+ raw, _ := json.Marshal(rep)
+ fmt.Printf("%s%s\n", ixrAgentPrefix, raw)
+ }()
+ fail := func(format string, args ...any) {
+ rep.Err = fmt.Sprintf(format, args...)
+ }
+ switch scenario {
+ case "sessions":
+ ixrSessions(&rep, fail)
+ case "rootfs":
+ ixrRootfsRun(&rep, fail)
+ default:
+ fail("unknown scenario %q", scenario)
+ }
+}
+
+func ixrSessions(rep *ixrAgentReport, fail func(string, ...any)) {
+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
+ defer cancel()
+ ctl := &ixrIntruderControl{Client: instancectl.NewClient(controlsock.Path), host: ixrHostA, got: &rep.Intruder}
+ eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: ctl}
+ staged := func(h string) *instancectl.StagedExe {
+ sum := sha256.New()
+ f, err := os.Open(release.VersionPath("/opt/carlos", ixAcct, ixrVersion, ixrApps[h]))
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+ io.Copy(sum, f)
+ return &instancectl.StagedExe{Path: f.Name(), Version: ixrVersion, Digest: hex.EncodeToString(sum.Sum(nil))}
+ }
+ env := map[string]string{"IXR_WITNESS": "1"}
+ tty := &activator.TTYSpec{Term: "xterm-256color", Cols: 100, Rows: 30}
+
+ // Session a: the report, then a line of input.
+ ua, err := eb.StartCmdServing(ctx, ixrRow(ixrHostA), activator.CmdSpec{RunID: "ixr-a", Args: []string{ixrPayloadArg, "report"}, TTY: tty}, staged(ixrHostA), env)
+ if err != nil {
+ if ua != nil {
+ ixrSettle(ctx, ua, ixrHostA, &rep.A)
+ }
+ fail("start session a: %v", err)
+ return
+ }
+ rep.A.Invocation = ua.Invocation()
+ ra := ixrReadTerm(ua.Terminal())
+ line, err := ra.line(ixrReportPrefix, time.Minute)
+ if err == nil {
+ err = json.Unmarshal([]byte(line), &rep.A.Report)
+ }
+ if err != nil {
+ ixrSettle(ctx, ua, ixrHostA, &rep.A)
+ fail("session a's report: %v", err)
+ return
+ }
+ rep.PTN, err = activator.TerminalPTN(ua.Terminal())
+ rep.PTNErr = ixrErr(err)
+
+ // a's pty from the host, as carlos, outside every namespace.
+ if fd, err := unix.Open("/dev/pts/"+strconv.Itoa(rep.PTN), unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0); err == nil {
+ unix.Close(fd)
+ rep.HostOpen = "opened"
+ } else {
+ rep.HostOpen = err.Error()
+ var errno syscall.Errno
+ if errors.As(err, &errno) {
+ rep.HostOpenErrno = int(errno)
+ }
+ }
+
+ // Session b, while a is open: a's pty from b's namespace.
+ ub, err := eb.StartCmdServing(ctx, ixrRow(ixrHostB), activator.CmdSpec{RunID: "ixr-b", Args: []string{ixrPayloadArg, "pts", strconv.Itoa(rep.PTN)}, TTY: tty}, staged(ixrHostB), env)
+ if err != nil {
+ if ub != nil {
+ ixrSettle(ctx, ub, ixrHostB, &rep.B)
+ }
+ ixrSettle(ctx, ua, ixrHostA, &rep.A)
+ fail("start session b: %v", err)
+ return
+ }
+ rep.B.Invocation = ub.Invocation()
+ rb := ixrReadTerm(ub.Terminal())
+ if line, err := rb.line(ixrReportPrefix, time.Minute); err != nil {
+ fail("session b's report: %v", err)
+ } else if err := json.Unmarshal([]byte(line), &rep.B.Report); err != nil {
+ fail("session b's report: %v", err)
+ }
+ if rep.B.Final, err = ixrUntilDone(ctx, ub); err != nil {
+ fail("session b's poll: %v", err)
+ }
+ ixrSettle(ctx, ub, ixrHostB, &rep.B)
+
+ // a reads a line and exits 0; its unit is stopped and settled.
+ if _, err := ua.Terminal().Write([]byte("bye\n")); err != nil {
+ fail("write to session a: %v", err)
+ }
+ if rep.A.Bye, err = ra.line(ixrByePrefix, time.Minute); err != nil {
+ fail("session a's bye: %v", err)
+ }
+ if rep.A.Final, err = ixrUntilDone(ctx, ua); err != nil {
+ fail("session a's poll: %v", err)
+ }
+ ixrSettle(ctx, ua, ixrHostA, &rep.A)
+}
+
+// ixrLockedBuffer is a stream's sink, written from the drain's goroutine.
+type ixrLockedBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *ixrLockedBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+
+func (b *ixrLockedBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.String()
+}
+
+// ixrRootfsRun is carlos run on the rootfs row: the agent's production
+// rootfs wiring (the nested gate, the probe's verdict and the placement
+// rules, agentRootfs.arm, on a single-tenant box), then StartCmd with the
+// run's directory and streams, the poll to its end, and the settle.
+func ixrRootfsRun(rep *ixrAgentReport, fail func(string, ...any)) {
+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
+ defer cancel()
+ ctl := instancectl.NewClient(controlsock.Path)
+ eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: ctl}
+ eb.NestedOK = nestedGate(func() error { return instancefs.SelfCheck("/data") }, instancefs.MountNoSymfollow, ctl.Ready)
+ // A dev box: single tenant here, and overlap deploys on (CARLOS_SWAP=overlap).
+ rf := &agentRootfs{nested: eb.NestedOK, control: ctl, single: true, overlap: true}
+ rf.arm(eb)
+ row := ixrRow(ixrHostR)
+ f, err := os.Open(release.VersionPath("/opt/carlos", ixAcct, ixrVersion, ixrApps[ixrHostR]))
+ if err != nil {
+ fail("the staged image: %v", err)
+ return
+ }
+ sum := sha256.New()
+ io.Copy(sum, f)
+ f.Close()
+ serving := &instancectl.StagedExe{Path: f.Name(), Version: ixrVersion, Digest: hex.EncodeToString(sum.Sum(nil))}
+ runDir := filepath.Join(provision.InstanceDir("/data", ixrHostR), activator.CmdRunDirName, "ixr-r")
+ if err := os.MkdirAll(runDir, 0o700); err != nil {
+ fail("run directory: %v", err)
+ return
+ }
+ var out, errs ixrLockedBuffer
+ spec := activator.CmdSpec{RunID: "ixr-r", Args: []string{"/bin/witness", ixrPayloadArg, "rootfs"}, RunDir: runDir, Stdout: &out, Stderr: &errs}
+ u, err := eb.StartCmdServing(ctx, row, spec, serving, map[string]string{"IXR_WITNESS": "1"})
+ if err != nil {
+ if u != nil {
+ rep.R.SettleErr = ixrErr(u.StopAndSettle(ctx))
+ }
+ fail("start the rootfs run: %v", err)
+ return
+ }
+ rep.R.Invocation = u.Invocation()
+ // The unit's cgroup from outside, as systemd placed it: the rootfs
+ // template runs its command in a private cgroup namespace
+ // (ProtectControlGroups=strict), where /proc/self/cgroup reads 0::/.
+ rep.RCgroup = filepath.Join("/sys/fs/cgroup/carlos.slice", instancectl.InstancesSlice, instancectl.SliceName(ixrHostR), instancectl.RootfsUnitName(instancectl.RoleCmd, ixrHostR))
+ for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline) && !slices.ContainsFunc(rep.RCmdline, func(c string) bool { return strings.Contains(c, ixrPayloadArg) }); time.Sleep(100 * time.Millisecond) {
+ rep.RCmdline = nil
+ raw, _ := os.ReadFile(filepath.Join(rep.RCgroup, "cgroup.procs"))
+ for _, pid := range strings.Fields(string(raw)) {
+ cl, _ := os.ReadFile(filepath.Join("/proc", pid, "cmdline"))
+ rep.RCmdline = append(rep.RCmdline, strings.TrimSpace(strings.ReplaceAll(string(cl), "\x00", " ")))
+ }
+ }
+ if rep.R.Final, err = ixrUntilDone(ctx, u); err != nil {
+ fail("the rootfs run's poll: %v", err)
+ }
+ rep.R.SettleErr = ixrErr(u.StopAndSettle(ctx))
+ rep.RStdout, rep.RErrs = out.String(), errs.String()
+ for _, line := range strings.Split(rep.RStdout, "\n") {
+ if rest, ok := strings.CutPrefix(line, ixrReportPrefix); ok {
+ if err := json.Unmarshal([]byte(rest), &rep.R.Report); err != nil {
+ fail("the rootfs run's report: %v", err)
+ }
+ return
+ }
+ }
+ fail("the rootfs run printed no report: stdout %q stderr %q", rep.RStdout, rep.RErrs)
+}
+
+// TestRootfsRunIsInsideTheInstance: carlos run on a rootfs row, through the
+// real rootfs cmd unit and the real control service's rootfs start, on a
+// box whose probes passed for real. The command runs in the instance's
+// slice and unit, and its / is the image's (C5).
+func TestRootfsRunIsInsideTheInstance(t *testing.T) {
+ b := newIxrBox(t, ixrBoxOpts{rootfs: true})
+ rep := b.agent(t, "rootfs")
+ r := rep.R.Report
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, ixrHostR)
+ t.Logf("rootfs run: invocation %s, final %+v, report %+v", rep.R.Invocation, rep.R.Final, r)
+ t.Logf("rootfs run stdout %q stderr %q", rep.RStdout, rep.RErrs)
+ journal := ixrJournal(unit)
+ t.Logf("journal of %s:\n%s", unit, journal)
+
+ // The brief's check reads /proc/self/cgroup inside. The rootfs
+ // template's ProtectControlGroups=strict gives the unit a private
+ // cgroup namespace (Plan 2; the rootfs probe's cgroup-strict line), so
+ // inside it reads the namespace's root, 0::/. Where the command runs is
+ // then the box's view: the unit's own cgroup under the host's slice
+ // held the command's processes while it ran.
+ wantCG := instancectl.SliceName(ixrHostR) + "/" + unit
+ tmpl, err := unitsFS.ReadFile("units/carlos-instance-rootfs-cmd@.service")
+ if err != nil {
+ t.Fatal(err)
+ }
+ inside := wantCG
+ if strings.Contains(string(tmpl), "\nProtectControlGroups=strict\n") {
+ inside = "0::/"
+ }
+ if r.Cgroup != inside && !strings.HasSuffix(r.Cgroup, inside) {
+ t.Errorf("inside, /proc/self/cgroup is %q, want %q", r.Cgroup, inside)
+ } else {
+ t.Logf("WITNESS rootfs-cgroup-inside ok: /proc/self/cgroup %q", r.Cgroup)
+ }
+ if !strings.HasSuffix(rep.RCgroup, wantCG) || !slices.ContainsFunc(rep.RCmdline, func(c string) bool { return strings.Contains(c, ixrPayloadArg+" rootfs") }) {
+ t.Errorf("outside, %s held %q, want the command", rep.RCgroup, rep.RCmdline)
+ } else {
+ t.Logf("WITNESS rootfs-cgroup ok: %s held %q while the command ran", rep.RCgroup, rep.RCmdline)
+ }
+ if r.RootMarker != ixrImageMarker || !errors.Is(ixrErrno(r.BoxFileErr), syscall.ENOENT) || !slices.Contains(r.Root, "bin") {
+ t.Errorf("/ is %q, marker %q, the box's /etc/debian_version %q: want the image's root", r.Root, r.RootMarker, r.BoxFileErr)
+ } else {
+ t.Logf("WITNESS rootfs-root ok: / is %q, /etc/witness-image %q, the box's /etc/debian_version: %s", r.Root, r.RootMarker, r.BoxFileErr)
+ }
+ if rep.R.Final.State != instancectl.CmdDone || rep.R.Final.Status != "0" || rep.R.SettleErr != "" {
+ t.Errorf("the run ended %+v, settle %q: want done, status 0, settled", rep.R.Final, rep.R.SettleErr)
+ } else {
+ t.Logf("WITNESS rootfs-end ok: done, status %s (%s), settled", rep.R.Final.Status, rep.R.Final.Result)
+ }
+ record := filepath.Join(provision.InstanceRunDir(ixrHostR), instancectl.ExitRecordName(instancectl.RoleCmd, rep.R.Invocation))
+ raw, err := os.ReadFile(record)
+ var rec instancectl.ExitRecord
+ if err == nil {
+ err = json.Unmarshal(raw, &rec)
+ }
+ state, result := egressShow(t, unit, "ActiveState"), egressShow(t, unit, "Result")
+ if err != nil || rec.Invocation != rep.R.Invocation || state == "failed" || (result != "" && result != "success") || strings.Contains(journal, "Failed with result") {
+ t.Errorf("the post command: exit record %s: %v %s; %s is %s, result %q", record, err, raw, unit, state, result)
+ } else {
+ t.Logf("WITNESS rootfs-post ok: instance-exit wrote %s; %s is %s, result %q", record, unit, state, result)
+ }
+}
+
+// ixrErrno is the errno an error string from the payload names.
+func ixrErrno(s string) error {
+ if strings.HasSuffix(s, syscall.ENOENT.Error()) {
+ return syscall.ENOENT
+ }
+ return errors.New(s)
+}