instance-exec: the tty role takes its terminal over stdin (rootfs plan 6)
instance-exec [--rootfs] tty %I reads launch.tty.json and launches through ttyLaunch: one recvmsg on stdin, exactly carlos-tty/1 and one SCM_RIGHTS fd that is a Unix98 pty slave answering TCGETS, else refused; it closes the handoff socket and runs the tenant under the init as a session leader with the pty as its stdio and controlling terminal. runInitChecked takes the tenant's stdio and whether to give it a controlling terminal, and closes the init's copy after the fork. instance-exit names tty in its usage (PF-9). A non-linux stub keeps the cross-builds. Census: rootfs-apps-6 overlay re-proposed (new receivePTY; prior claims carried); record-write parseExitArgs re-pinned (usage line only).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+815
−26
docs/superpowers/notes/census-proposal-rootfs-apps-6.md+3 −2internal/instanceexec/claimexec_linux.go+1 −1internal/instanceexec/claimexec_rev3_linux_test.go+1 −1internal/instanceexec/exec.go+21 −10internal/instanceexec/exit.go+1 −1internal/instanceexec/exit_test.go+29 −0internal/instanceexec/init_linux.go+28 −8internal/instanceexec/init_test.go+2 −0internal/instanceexec/tty_linux.go+186 −0internal/instanceexec/tty_linux_test.go+521 −0internal/instanceexec/tty_other.go+11 −0internal/provision/rootfs_apps_6_census_test.go+6 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv+4 −2
Intent
Attributed to this commit: 21.3 g CO₂e (2,422,138 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/docs/superpowers/notes/census-proposal-rootfs-apps-6.md b/docs/superpowers/notes/census-proposal-rootfs-apps-6.md| index b7fbb186c..5a4ca08ba 100644 |
| --- a/docs/superpowers/notes/census-proposal-rootfs-apps-6.md |
| +++ b/docs/superpowers/notes/census-proposal-rootfs-apps-6.md |
| @@ -1,6 +1,6 @@ |
| # Census approval: rootfs-apps-6 |
| -Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| @@ -49,7 +49,8 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/host/units/carlos-instance-rootfs-tty@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/host/units/carlos-instance-tty@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/instancectl/cmd.go:Server.oneShotStatus`: reads +file:Query ×3; written legacy, accepted-legacy, frozen |
| +- new `internal/instanceexec/tty_linux.go:receivePTY`: reads +file:Fstat; written legacy, accepted-legacy, frozen |
| -Seal: `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7` → `b611b6ff7f86bc5b046a41d3d89ababf673ebd13e6e4c2593d7d2de4112729e1`. |
| +Seal: `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7` → `44581c3700aa3a72c593ef0493663ee42b2c9425231efbfbb6d67abd3a6fced8`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/instanceexec/claimexec_linux.go b/internal/instanceexec/claimexec_linux.go| index aa4156245..9e77894a1 100644 |
| --- a/internal/instanceexec/claimexec_linux.go |
| +++ b/internal/instanceexec/claimexec_linux.go |
| @@ -16,7 +16,7 @@ import ( |
| ) |
| func scopedClaimInit(argv0 string, argv, env []string, snapshot string) error { |
| - return runInitChecked(argv0, argv, env, func() error { |
| + return runInitChecked(argv0, argv, env, nil, false, func() error { |
| if err := ScopeAbstractUnix(); err != nil { |
| return err |
| } |
diff --git a/internal/instanceexec/claimexec_rev3_linux_test.go b/internal/instanceexec/claimexec_rev3_linux_test.go| index ccfa16cd5..324260b71 100644 |
| --- a/internal/instanceexec/claimexec_rev3_linux_test.go |
| +++ b/internal/instanceexec/claimexec_rev3_linux_test.go |
| @@ -22,7 +22,7 @@ func TestRev3ExecBoundaryHelper(t *testing.T) { |
| // Simulate setup consuming the lease. This uses runInit's production fork |
| // path and a real socket; only the host clock and namespace scope are faked. |
| clock := int64(100) |
| - err := runInitChecked("/bin/sh", []string{"sh", "-c", "echo tenant > \"$1\"", "sh", filepath.Join(dir, "tenant")}, os.Environ(), func() error { clock = 200; return nil }, func() error { |
| + err := runInitChecked("/bin/sh", []string{"sh", "-c", "echo tenant > \"$1\"", "sh", filepath.Join(dir, "tenant")}, os.Environ(), nil, false, func() error { clock = 200; return nil }, func() error { |
| return checkClaimExec(filepath.Join(dir, "permit"), filepath.Join(dir, "gate"), uint32(os.Geteuid()), func() (string, int64, error) { return "boot", clock, nil }) |
| }) |
| if err == nil { |
diff --git a/internal/instanceexec/exec.go b/internal/instanceexec/exec.go| index fd67acab0..93a5071a0 100644 |
| --- a/internal/instanceexec/exec.go |
| +++ b/internal/instanceexec/exec.go |
| @@ -38,7 +38,8 @@ func dataDir() string { |
| return "/data" |
| } |
| -// RunExec is `carlos instance-exec [--rootfs] <role> <iid>`. |
| +// RunExec is `carlos instance-exec [--rootfs] <role> <iid>`; the tty role |
| +// takes its terminal over stdin (tty_linux.go). |
| func RunExec(args []string) { |
| c, err := parseExecArgs(args) |
| if errors.Is(err, errUsage) { |
| @@ -47,16 +48,10 @@ func RunExec(args []string) { |
| if err != nil { |
| log.Fatal(err) |
| } |
| - // The tenant is scoped (#178, see ScopeAbstractUnix) and runs under |
| - // the trampoline as its init (#126, see init_linux.go). |
| if c.rootfs { |
| - err = execRootfsLaunch(dataDir(), instancectl.RootfsLaunchPath, c.role, c.inst, scopedInit) |
| + err = execRootfsLaunch(dataDir(), instancectl.RootfsLaunchPath, c.role, c.inst, c.launcher()) |
| } else { |
| - launch := scopedInit |
| - if c.claim != "" { |
| - launch = func(argv0 string, argv, env []string) error { return scopedClaimInit(argv0, argv, env, c.claim) } |
| - } |
| - err = execLaunch(dataDir(), c.role, c.inst, launch) |
| + err = execLaunch(dataDir(), c.role, c.inst, c.launcher()) |
| } |
| if err != nil { |
| log.Fatalf("instance-exec: %v", err) |
| @@ -74,13 +69,29 @@ type execCommand struct { |
| claim string // --claim-reservation: the binary run's claim launch |
| } |
| +// launcher is the command line's launch. The tenant is scoped (#178, see |
| +// ScopeAbstractUnix) and runs under the trampoline as its init (#126, see |
| +// init_linux.go). A tty takes its terminal from the agent first |
| +// (tty_linux.go); a binary run with a claim reservation is checked at the |
| +// claim boundary first (claimexec_linux.go). parseExecArgs refuses the |
| +// claim launch for anything but a binary run. |
| +func (c execCommand) launcher() func(argv0 string, argv, env []string) error { |
| + switch { |
| + case c.role == instancectl.RoleTTY: |
| + return ttyLaunch |
| + case c.claim != "": |
| + return func(argv0 string, argv, env []string) error { return scopedClaimInit(argv0, argv, env, c.claim) } |
| + } |
| + return scopedInit |
| +} |
| + |
| // parseExecArgs is RunExec's flag and role parsing; its refusals carry |
| // the program's name. worker is taken only with --rootfs (rootfs apps |
| // preflight 1.1), and --rootfs never with --claim-reservation: a rootfs |
| // unit's command is root's launch file and nothing else. |
| func parseExecArgs(args []string) (execCommand, error) { |
| fs := flag.NewFlagSet("instance-exec", flag.ExitOnError) |
| - fs.Usage = cliflag.Usage(fs, "usage: carlos instance-exec [--rootfs] <run|seed|sidecar|cmd|worker> <instance-id>") |
| + fs.Usage = cliflag.Usage(fs, "usage: carlos instance-exec [--rootfs] <run|seed|sidecar|cmd|worker|tty> <instance-id>") |
| claim := fs.String("claim-reservation", "", "root launch reservation") |
| rootfs := fs.Bool("rootfs", false, "rootfs launch: root's launch file names the command") |
| _ = fs.Parse(args) |
diff --git a/internal/instanceexec/exit.go b/internal/instanceexec/exit.go| index 7f5ab3f92..daf19e57b 100644 |
| --- a/internal/instanceexec/exit.go |
| +++ b/internal/instanceexec/exit.go |
| @@ -57,7 +57,7 @@ func parseExitArgs(args []string) (exitCommand, error) { |
| fs := flag.NewFlagSet("instance-exit", flag.ExitOnError) |
| runDir := fs.String("run-dir", provision.SocketDir, "run directory holding instances/<id>") |
| rootfs := fs.Bool("rootfs", false, "the unit is a rootfs template") |
| - fs.Usage = cliflag.Usage(fs, "usage: carlos instance-exit [--rootfs] <run|seed|sidecar|cmd|worker> <instance-id>") |
| + fs.Usage = cliflag.Usage(fs, "usage: carlos instance-exit [--rootfs] <run|seed|sidecar|cmd|worker|tty> <instance-id>") |
| _ = fs.Parse(args) |
| if fs.NArg() != 2 { |
| fs.Usage() |
diff --git a/internal/instanceexec/exit_test.go b/internal/instanceexec/exit_test.go| index 217f62bfe..573fde66f 100644 |
| --- a/internal/instanceexec/exit_test.go |
| +++ b/internal/instanceexec/exit_test.go |
| @@ -104,3 +104,32 @@ func TestWriteExitRecordKeysAGenerationRecordByGeneration(t *testing.T) { |
| t.Error("a sidecar generation was accepted") |
| } |
| } |
| + |
| +// PF-9: every tty unit's ExecStopPost= runs `instance-exit [--rootfs] tty |
| +// %I`, so instance-exit takes tty as it takes cmd, and its record is the |
| +// tty's own. |
| +func TestExitAcceptsTheTTYRole(t *testing.T) { |
| + for _, args := range [][]string{{"tty", "x"}, {"--rootfs", "tty", "x"}} { |
| + c, err := parseExitArgs(args) |
| + if err != nil || c.role != instancectl.RoleTTY || c.inst != "x" { |
| + t.Errorf("parseExitArgs(%v) = %+v, %v", args, c, err) |
| + } |
| + } |
| + _, err := parseExitArgs([]string{"bogus", "x"}) |
| + if err == nil || err.Error() != `instance-exit: role "bogus" is not run, seed, sidecar or cmd` { |
| + t.Errorf("unknown role: %v", err) |
| + } |
| + |
| + run := t.TempDir() |
| + host := "shop.example.com" |
| + if err := os.MkdirAll(filepath.Join(run, "instances", host), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + inv := "0123456789abcdef0123456789abcdef" |
| + if err := writeExitRecord(run, instancectl.RoleTTY, host, envOf(map[string]string{"INVOCATION_ID": inv, "SERVICE_RESULT": "success"}), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(filepath.Join(run, "instances", host, "exit.tty."+inv+".json")); err != nil { |
| + t.Errorf("the tty's exit record: %v", err) |
| + } |
| +} |
diff --git a/internal/instanceexec/init_linux.go b/internal/instanceexec/init_linux.go| index bcb9fc689..eb5717c9f 100644 |
| --- a/internal/instanceexec/init_linux.go |
| +++ b/internal/instanceexec/init_linux.go |
| @@ -3,6 +3,7 @@ |
| package instanceexec |
| import ( |
| + "errors" |
| "fmt" |
| "os" |
| "os/signal" |
| @@ -62,10 +63,25 @@ func scopedInit(argv0 string, argv, env []string) error { |
| } |
| func runInit(argv0 string, argv, env []string, scope func() error) error { |
| - return runInitChecked(argv0, argv, env, scope, nil) |
| + return runInitChecked(argv0, argv, env, nil, false, scope, nil) |
| } |
| -func runInitChecked(argv0 string, argv, env []string, scope, check func() error) error { |
| +// runInitChecked is the init. stdio is the tenant's fds 0, 1 and 2: nil |
| +// keeps the init's own, as the exec this replaces did; three files are |
| +// given to the tenant and the init closes its copies after the fork, so |
| +// the tenant's are the only ones. ctty makes the tenant's fd 0 its |
| +// controlling terminal (the tty role); it needs stdio. |
| +func runInitChecked(argv0 string, argv, env []string, stdio []*os.File, ctty bool, scope, check func() error) error { |
| + files := []uintptr{0, 1, 2} |
| + switch { |
| + case stdio != nil && len(stdio) != 3: |
| + return fmt.Errorf("the tenant's stdio is three files, not %d", len(stdio)) |
| + case stdio != nil: |
| + files = []uintptr{stdio[0].Fd(), stdio[1].Fd(), stdio[2].Fd()} |
| + case ctty: |
| + return errors.New("a controlling terminal needs the tenant's stdio") |
| + } |
| + |
| // Before anything can start the tenant: a stop that arrives early is |
| // queued and forwarded, not dropped by PID 1's missing defaults. |
| sigs := make(chan os.Signal, 32) |
| @@ -83,10 +99,11 @@ func runInitChecked(argv0 string, argv, env []string, scope, check func() error) |
| if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); err != nil { |
| return fmt.Errorf("subreaper: %w", err) |
| } |
| - // Same argv, env, cwd and stdio as the exec this replaces. Fds beyond |
| - // stdio pass as they did there: anything not close-on-exec stays |
| - // open across fork and exec. Setsid gives the tenant the session of |
| - // its own that systemd gave the main process. |
| + // Same argv, env, cwd and stdio as the exec this replaces, unless |
| + // stdio was given. Fds beyond stdio pass as they did there: anything |
| + // not close-on-exec stays open across fork and exec. Setsid gives the |
| + // tenant the session of its own that systemd gave the main process; |
| + // with ctty, the child's fd 0 then becomes that session's terminal. |
| if check != nil { |
| if err := check(); err != nil { |
| return err |
| @@ -94,9 +111,12 @@ func runInitChecked(argv0 string, argv, env []string, scope, check func() error) |
| } |
| tenant, err := syscall.ForkExec(argv0, argv, &syscall.ProcAttr{ |
| Env: env, |
| - Files: []uintptr{0, 1, 2}, |
| - Sys: &syscall.SysProcAttr{Setsid: true}, |
| + Files: files, |
| + Sys: &syscall.SysProcAttr{Setsid: true, Setctty: ctty, Ctty: 0}, |
| }) |
| + for _, f := range stdio { |
| + _ = f.Close() |
| + } |
| if err != nil { |
| return err |
| } |
diff --git a/internal/instanceexec/init_test.go b/internal/instanceexec/init_test.go| index ff2f75d38..a63e5d512 100644 |
| --- a/internal/instanceexec/init_test.go |
| +++ b/internal/instanceexec/init_test.go |
| @@ -123,6 +123,8 @@ func runHelper(role string) int { |
| fmt.Println("fd3:", err) |
| } |
| return 0 |
| + case "tty-init": |
| + return ttyHelper() |
| case "dial": |
| c, err := net.Dial("unix", os.Getenv(ieArgEnv)) |
| switch { |
diff --git a/internal/instanceexec/tty_linux.go b/internal/instanceexec/tty_linux.go| new file mode 100644 |
| index 000000000..e5fdb6a95 |
| --- /dev/null |
| +++ b/internal/instanceexec/tty_linux.go |
| @@ -0,0 +1,186 @@ |
| +//go:build linux |
| + |
| +package instanceexec |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| +) |
| + |
| +// The tty role (rootfs apps design §5.10, C9). A tty unit's stdin is a |
| +// socket to the agent (StandardInput=file: on the session's socket), and |
| +// the agent sends one message on it: TTYHello with the slave side of a pty |
| +// it opened as SCM_RIGHTS. The trampoline takes that fd, closes the socket |
| +// and starts the tenant on the pty as a session leader whose controlling |
| +// terminal it is. The agent keeps the master. |
| +// |
| +// The trampoline itself is in another session, so the line discipline's |
| +// Ctrl-C (SIGINT) reaches only the tenant's foreground process group. The |
| +// tenant's process group is orphaned (its parent, the trampoline, is in |
| +// another session), so the kernel discards a terminal-generated SIGTSTP |
| +// and Ctrl-Z cannot freeze the session. A stop's SIGTERM is forwarded as |
| +// for every role (init_linux.go). |
| + |
| +var ( |
| + errNoTerminal = errors.New("instance-exec: no terminal was handed over") |
| + errNotAPTY = errors.New("instance-exec: the handed fd is not a pty") |
| +) |
| + |
| +// ttyHandoffWait is how long the trampoline waits for the agent's message. |
| +const ttyHandoffWait = 10 * time.Second |
| + |
| +// Unix98 pty slaves (/dev/pts/N) have majors 136 to 143 |
| +// (UNIX98_PTY_SLAVE_MAJOR and UNIX98_PTY_MAJOR_COUNT). The ptmx and a |
| +// master are major 5, never taken. |
| +const ( |
| + ptySlaveMajorFirst = 136 |
| + ptySlaveMajorLast = 143 |
| +) |
| + |
| +// ttyLaunch is the tty role's launch: take the terminal, close the |
| +// handoff socket, and run the tenant on the terminal under the init. |
| +func ttyLaunch(argv0 string, argv, env []string) error { |
| + return ttyLaunchScoped(argv0, argv, env, ScopeAbstractUnix) |
| +} |
| + |
| +// ttyLaunchScoped is ttyLaunch with the scope a test can replace. |
| +func ttyLaunchScoped(argv0 string, argv, env []string, scope func() error) error { |
| + pty, err := receivePTY(os.Stdin, ttyHandoffWait) |
| + if err != nil { |
| + return err |
| + } |
| + // The socket's work is done. Closing it tells the agent the handoff |
| + // is over, and nothing of it reaches the tenant. |
| + if err := os.Stdin.Close(); err != nil { |
| + pty.Close() |
| + return fmt.Errorf("closing the handoff socket: %w", err) |
| + } |
| + return runTTYInit(argv0, argv, env, pty, scope) |
| +} |
| + |
| +// receivePTY reads the agent's one message from sock: exactly TTYHello and |
| +// exactly one SCM_RIGHTS fd, else errNoTerminal. The fd must be a Unix98 |
| +// pty slave that answers TCGETS, else errNotAPTY. Nothing arriving within |
| +// wait is errNoTerminal. On a refusal every fd received is closed. The |
| +// returned file is close-on-exec; the tenant gets it as its stdio only. |
| +func receivePTY(sock *os.File, wait time.Duration) (*os.File, error) { |
| + fd := int(sock.Fd()) |
| + deadline := time.Now().Add(wait) |
| + for { |
| + left := time.Until(deadline) |
| + if left <= 0 { |
| + return nil, fmt.Errorf("%w: nothing within %v", errNoTerminal, wait) |
| + } |
| + ms := int((left + time.Millisecond - 1) / time.Millisecond) |
| + n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, ms) |
| + if err == unix.EINTR { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, fmt.Errorf("%w: %v", errNoTerminal, err) |
| + } |
| + if n > 0 { |
| + break |
| + } |
| + } |
| + |
| + buf := make([]byte, 64) |
| + oob := make([]byte, unix.CmsgSpace(4)) |
| + var ( |
| + n, oobn, flags int |
| + err error |
| + ) |
| + for { |
| + n, oobn, flags, _, err = unix.Recvmsg(fd, buf, oob, unix.MSG_CMSG_CLOEXEC|unix.MSG_DONTWAIT) |
| + if err != unix.EINTR { |
| + break |
| + } |
| + } |
| + if err != nil { |
| + return nil, fmt.Errorf("%w: %v", errNoTerminal, err) |
| + } |
| + fds, rightsErr := unixRights(oob[:oobn]) |
| + refuse := func(why string) (*os.File, error) { |
| + for _, f := range fds { |
| + unix.Close(f) |
| + } |
| + return nil, fmt.Errorf("%w: %s", errNoTerminal, why) |
| + } |
| + switch { |
| + case rightsErr != nil: |
| + return refuse(rightsErr.Error()) |
| + case flags&unix.MSG_CTRUNC != 0: |
| + return refuse("more than one fd") |
| + case len(fds) != 1: |
| + return refuse(fmt.Sprintf("%d fds, not one", len(fds))) |
| + case string(buf[:n]) != instancectl.TTYHello: |
| + return refuse(fmt.Sprintf("the message %q is not the hello", buf[:n])) |
| + } |
| + |
| + var st unix.Stat_t |
| + statErr := unix.Fstat(fds[0], &st) |
| + if statErr != nil { |
| + unix.Close(fds[0]) |
| + return nil, fmt.Errorf("%w: %v", errNotAPTY, statErr) |
| + } |
| + _, tcgetsErr := unix.IoctlGetTermios(fds[0], unix.TCGETS) |
| + if err := ptyCheck(&st, tcgetsErr); err != nil { |
| + unix.Close(fds[0]) |
| + return nil, err |
| + } |
| + return os.NewFile(uintptr(fds[0]), "pty"), nil |
| +} |
| + |
| +// unixRights is every fd in the control messages. Anything that is not |
| +// SCM_RIGHTS is an error; the fds already parsed are still returned, so |
| +// the caller can close them. |
| +func unixRights(oob []byte) ([]int, error) { |
| + if len(oob) == 0 { |
| + return nil, nil |
| + } |
| + msgs, err := unix.ParseSocketControlMessage(oob) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var fds []int |
| + for _, m := range msgs { |
| + got, err := unix.ParseUnixRights(&m) |
| + if err != nil { |
| + return fds, err |
| + } |
| + fds = append(fds, got...) |
| + } |
| + return fds, nil |
| +} |
| + |
| +// ptyCheck is receivePTY's verdict on the fd's fstat and its TCGETS |
| +// answer: a character device of a Unix98 pty slave major that is a |
| +// terminal, else errNotAPTY. |
| +func ptyCheck(st *unix.Stat_t, tcgetsErr error) error { |
| + if st.Mode&unix.S_IFMT != unix.S_IFCHR { |
| + return fmt.Errorf("%w: not a character device (mode %#o)", errNotAPTY, st.Mode) |
| + } |
| + if major := unix.Major(uint64(st.Rdev)); major < ptySlaveMajorFirst || major > ptySlaveMajorLast { |
| + return fmt.Errorf("%w: device major %d is not a pty slave's", errNotAPTY, major) |
| + } |
| + if tcgetsErr != nil { |
| + return fmt.Errorf("%w: TCGETS: %v", errNotAPTY, tcgetsErr) |
| + } |
| + return nil |
| +} |
| + |
| +// runTTYInit runs the tenant under the init with the pty as its stdin, |
| +// stdout and stderr and as its controlling terminal (Setsid, then |
| +// TIOCSCTTY on its fd 0). runInitChecked closes the init's own copy of the |
| +// pty after the fork, so the agent's master reads EIO once the tenant's |
| +// side is gone. It returns only if the tenant could not be started. |
| +func runTTYInit(argv0 string, argv, env []string, pty *os.File, scope func() error) error { |
| + defer pty.Close() |
| + return runInitChecked(argv0, argv, env, []*os.File{pty, pty, pty}, true, scope, nil) |
| +} |
diff --git a/internal/instanceexec/tty_linux_test.go b/internal/instanceexec/tty_linux_test.go| new file mode 100644 |
| index 000000000..3f3529972 |
| --- /dev/null |
| +++ b/internal/instanceexec/tty_linux_test.go |
| @@ -0,0 +1,521 @@ |
| +//go:build linux |
| + |
| +package instanceexec |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| +) |
| + |
| +// openPTY is a fresh Unix98 pty pair, both ends opened without becoming |
| +// the test's controlling terminal, as the agent opens one. |
| +func openPTY(t *testing.T) (master, slave *os.File) { |
| + t.Helper() |
| + master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY, 0) |
| + if err != nil { |
| + t.Fatalf("open /dev/ptmx: %v", err) |
| + } |
| + t.Cleanup(func() { master.Close() }) |
| + // Through SyscallConn, not Fd, which would put the master in blocking |
| + // mode and make every read deadline below a no-op. |
| + rc, err := master.SyscallConn() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var n int |
| + var ioctlErr error |
| + if err := rc.Control(func(fd uintptr) { |
| + if ioctlErr = unix.IoctlSetPointerInt(int(fd), unix.TIOCSPTLCK, 0); ioctlErr == nil { |
| + n, ioctlErr = unix.IoctlGetInt(int(fd), unix.TIOCGPTN) |
| + } |
| + }); err != nil || ioctlErr != nil { |
| + t.Fatalf("unlockpt/ptsname: %v %v", err, ioctlErr) |
| + } |
| + slave, err = os.OpenFile("/dev/pts/"+strconv.Itoa(n), os.O_RDWR|unix.O_NOCTTY, 0) |
| + if err != nil { |
| + t.Fatalf("open the slave: %v", err) |
| + } |
| + t.Cleanup(func() { slave.Close() }) |
| + return master, slave |
| +} |
| + |
| +// socketPair is the stdin socket of a tty unit: the agent's end and the |
| +// trampoline's. |
| +func socketPair(t *testing.T) (agent, trampoline *os.File) { |
| + t.Helper() |
| + fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + agent, trampoline = os.NewFile(uintptr(fds[0]), "agent"), os.NewFile(uintptr(fds[1]), "trampoline") |
| + t.Cleanup(func() { agent.Close(); trampoline.Close() }) |
| + return agent, trampoline |
| +} |
| + |
| +// send is one sendmsg of payload with files as SCM_RIGHTS. |
| +func send(t *testing.T, sock *os.File, payload string, files ...*os.File) { |
| + t.Helper() |
| + var oob []byte |
| + if len(files) > 0 { |
| + fds := make([]int, len(files)) |
| + for i, f := range files { |
| + fds[i] = int(f.Fd()) |
| + } |
| + oob = unix.UnixRights(fds...) |
| + } |
| + if err := unix.Sendmsg(int(sock.Fd()), []byte(payload), oob, nil, 0); err != nil { |
| + t.Fatalf("sendmsg: %v", err) |
| + } |
| +} |
| + |
| +// openFDs is how many fds this process has open. |
| +func openFDs(t *testing.T) int { |
| + t.Helper() |
| + ents, err := os.ReadDir("/proc/self/fd") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return len(ents) |
| +} |
| + |
| +func rdevOf(t *testing.T, f *os.File) uint64 { |
| + t.Helper() |
| + var st unix.Stat_t |
| + if err := unix.Fstat(int(f.Fd()), &st); err != nil { |
| + t.Fatal(err) |
| + } |
| + return uint64(st.Rdev) |
| +} |
| + |
| +func TestReceivePTYTakesExactlyOnePTY(t *testing.T) { |
| + master, slave := openPTY(t) |
| + agent, tramp := socketPair(t) |
| + send(t, agent, instancectl.TTYHello, slave) |
| + got, err := receivePTY(tramp, time.Second) |
| + if err != nil { |
| + t.Fatalf("receivePTY: %v", err) |
| + } |
| + defer got.Close() |
| + if rdevOf(t, got) != rdevOf(t, slave) { |
| + t.Errorf("received fd is not the slave that was sent") |
| + } |
| + if _, err := unix.IoctlGetTermios(int(got.Fd()), unix.TCGETS); err != nil { |
| + t.Errorf("received fd is not a tty: %v", err) |
| + } |
| + if flags, err := unix.FcntlInt(got.Fd(), unix.F_GETFD, 0); err != nil || flags&unix.FD_CLOEXEC == 0 { |
| + t.Errorf("received fd is not close-on-exec (flags %d, %v): it would leak into the tenant beside its stdio", flags, err) |
| + } |
| + // The received fd writes to the same terminal the agent reads. |
| + if _, err := got.Write([]byte("hi\n")); err != nil { |
| + t.Fatal(err) |
| + } |
| + master.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| + buf := make([]byte, 16) |
| + n, err := master.Read(buf) |
| + if err != nil || !strings.HasPrefix(string(buf[:n]), "hi") { |
| + t.Errorf("master read %q, %v", buf[:n], err) |
| + } |
| +} |
| + |
| +func TestReceivePTYRefusesAPlainFile(t *testing.T) { |
| + plain, err := os.Create(filepath.Join(t.TempDir(), "plain")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer plain.Close() |
| + devNull, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer devNull.Close() |
| + master, _ := openPTY(t) |
| + r, w, err := os.Pipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer r.Close() |
| + defer w.Close() |
| + for name, f := range map[string]*os.File{ |
| + "a regular file": plain, |
| + "/dev/null (a char device, not a tty)": devNull, |
| + "the pty master (a tty, not a slave)": master, |
| + "a pipe": r, |
| + } { |
| + agent, tramp := socketPair(t) |
| + send(t, agent, instancectl.TTYHello, f) |
| + before := openFDs(t) |
| + got, err := receivePTY(tramp, time.Second) |
| + if !errors.Is(err, errNotAPTY) { |
| + t.Errorf("%s: got %v, %v; want errNotAPTY", name, got, err) |
| + } |
| + if after := openFDs(t); err != nil && after != before { |
| + t.Errorf("%s: %d fds open after the refusal, %d before: the received fd leaked", name, after, before) |
| + } |
| + if got != nil { |
| + got.Close() |
| + } |
| + } |
| +} |
| + |
| +func TestReceivePTYRefusesNoFdAndWrongHello(t *testing.T) { |
| + _, slave := openPTY(t) |
| + cases := map[string]func(agent *os.File){ |
| + "the hello with no fd": func(a *os.File) { send(t, a, instancectl.TTYHello) }, |
| + "a wrong hello": func(a *os.File) { send(t, a, "hello", slave) }, |
| + "the hello and two fds": func(a *os.File) { send(t, a, instancectl.TTYHello, slave, slave) }, |
| + "the hello and three fds": func(a *os.File) { send(t, a, instancectl.TTYHello, slave, slave, slave) }, |
| + "a longer hello": func(a *os.File) { send(t, a, instancectl.TTYHello+"x", slave) }, |
| + "a hello cut short": func(a *os.File) { send(t, a, instancectl.TTYHello[:len(instancectl.TTYHello)-1], slave) }, |
| + "the agent hangs up": func(a *os.File) { a.Close() }, |
| + } |
| + for name, do := range cases { |
| + agent, tramp := socketPair(t) |
| + do(agent) |
| + before := openFDs(t) |
| + got, err := receivePTY(tramp, time.Second) |
| + if !errors.Is(err, errNoTerminal) { |
| + t.Errorf("%s: got %v, %v; want errNoTerminal", name, got, err) |
| + } |
| + if after := openFDs(t); err != nil && after != before { |
| + t.Errorf("%s: %d fds open after the refusal, %d before: a received fd leaked", name, after, before) |
| + } |
| + if got != nil { |
| + got.Close() |
| + } |
| + } |
| + |
| + // Nothing within wait. |
| + _, tramp := socketPair(t) |
| + start := time.Now() |
| + got, err := receivePTY(tramp, 200*time.Millisecond) |
| + if !errors.Is(err, errNoTerminal) { |
| + t.Errorf("nothing sent: got %v, %v; want errNoTerminal", got, err) |
| + } |
| + if d := time.Since(start); d < 200*time.Millisecond || d > 5*time.Second { |
| + t.Errorf("nothing sent: returned after %v, want the wait (200ms)", d) |
| + } |
| +} |
| + |
| +// ptyCheck is receivePTY's verdict on what fstat and TCGETS said, apart |
| +// so the shapes no unprivileged test can open are covered too. |
| +func TestPTYCheckTakesOnlyAUnix98Slave(t *testing.T) { |
| + chr := func(major uint32) *unix.Stat_t { |
| + return &unix.Stat_t{Mode: unix.S_IFCHR | 0o620, Rdev: unix.Mkdev(major, 3)} |
| + } |
| + for _, major := range []uint32{136, 140, 143} { |
| + if err := ptyCheck(chr(major), nil); err != nil { |
| + t.Errorf("major %d slave refused: %v", major, err) |
| + } |
| + } |
| + bad := map[string]struct { |
| + st *unix.Stat_t |
| + tty error |
| + }{ |
| + "major 135": {chr(135), nil}, |
| + "major 144": {chr(144), nil}, |
| + "the ptmx (5)": {chr(5), nil}, |
| + "a block device at major 136": {&unix.Stat_t{Mode: unix.S_IFBLK | 0o660, Rdev: unix.Mkdev(136, 3)}, nil}, |
| + "a regular file": {&unix.Stat_t{Mode: unix.S_IFREG | 0o600}, nil}, |
| + "a slave that refuses TCGETS": {chr(136), syscall.ENOTTY}, |
| + } |
| + for name, c := range bad { |
| + if err := ptyCheck(c.st, c.tty); !errors.Is(err, errNotAPTY) { |
| + t.Errorf("%s: %v, want errNotAPTY", name, err) |
| + } |
| + } |
| +} |
| + |
| +// PF-9: instance-exec takes tty and --rootfs tty, and launches it through |
| +// ttyLaunch; every other role keeps its launch. |
| +func TestExecDispatchesTheTTYRoleToTTYLaunch(t *testing.T) { |
| + ptr := func(f func(string, []string, []string) error) uintptr { return reflect.ValueOf(f).Pointer() } |
| + for _, args := range [][]string{{"tty", "shop.example.com"}, {"--rootfs", "tty", "shop.example.com"}} { |
| + c, err := parseExecArgs(args) |
| + if err != nil || c.role != instancectl.RoleTTY || c.inst != "shop.example.com" || c.rootfs != (args[0] == "--rootfs") { |
| + t.Fatalf("parseExecArgs(%v) = %+v, %v", args, c, err) |
| + } |
| + if ptr(c.launcher()) != ptr(ttyLaunch) { |
| + t.Errorf("%v does not launch through ttyLaunch", args) |
| + } |
| + } |
| + for _, args := range [][]string{{"run", "shop.example.com"}, {"cmd", "shop.example.com"}, {"--rootfs", "cmd", "shop.example.com"}, {"--rootfs", "worker", "shop.example.com:jobs"}} { |
| + c, err := parseExecArgs(args) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ptr(c.launcher()) != ptr(scopedInit) { |
| + t.Errorf("%v does not launch through scopedInit", args) |
| + } |
| + } |
| + c, err := parseExecArgs([]string{"--claim-reservation", instancectl.ClaimExecSnapshot, "run", "shop.example.com"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if p := ptr(c.launcher()); p == ptr(scopedInit) || p == ptr(ttyLaunch) { |
| + t.Error("the claim launch lost its reservation") |
| + } |
| + // tty has no claim launch and no generation. |
| + if _, err := parseExecArgs([]string{"--claim-reservation", instancectl.ClaimExecSnapshot, "tty", "shop.example.com"}); err == nil { |
| + t.Error("instance-exec took a claim reservation for a tty") |
| + } |
| + if _, _, err := launchTarget(instancectl.RoleTTY, "shop.example.com:3"); err == nil { |
| + t.Error("a tty unit took a generation instance") |
| + } |
| +} |
| + |
| +// Both launches read the tty's own file, launch.tty.json. |
| +func TestTTYLaunchReadsTheTTYLaunchFile(t *testing.T) { |
| + data := t.TempDir() |
| + host := "shop.example.com" |
| + dir := filepath.Join(data, "instances", host) |
| + writeLaunch(t, dir, instancectl.RoleTTY, instancectl.Launch{ |
| + Schema: 1, Host: host, Argv: []string{"/opt/carlos/live/" + host, "console"}, |
| + }) |
| + var c captured |
| + if err := execLaunch(data, instancectl.RoleTTY, host, c.exec); err != nil { |
| + t.Fatalf("binary tty: %v", err) |
| + } |
| + if c.calls != 1 || !reflect.DeepEqual(c.argv, []string{"/opt/carlos/live/" + host, "console"}) { |
| + t.Errorf("binary tty exec = %+v", c) |
| + } |
| + if _, err := os.Stat(filepath.Join(dir, "launch.tty.json")); err != nil { |
| + t.Fatalf("launch file name: %v", err) |
| + } |
| + |
| + f := newRootfsExecFixture(t) |
| + f.tenant.Process = "console" |
| + writeLaunch(t, filepath.Join(f.dataDir, "instances", f.iid), instancectl.RoleTTY, f.tenant) |
| + root := goodRootLaunch(f) |
| + root.Process = "console" |
| + f.writeRoot(t, root) |
| + var r captured |
| + if err := execRootfsLaunch(f.dataDir, f.rootLaunch, instancectl.RoleTTY, f.iid, r.exec); err != nil { |
| + t.Fatalf("rootfs tty: %v", err) |
| + } |
| + if r.calls != 1 || r.argv0 != f.imagePath("app/serve") { |
| + t.Errorf("rootfs tty exec = %+v", r) |
| + } |
| +} |
| + |
| +// ttyHelper is the "tty-init" helper role (init_test.go's runHelper): the |
| +// trampoline's tty launch, with the tenant's script in ieArgEnv and the |
| +// handoff socket on stdin, unscoped (the scope has its own test). |
| +func ttyHelper() int { |
| + err := ttyLaunchScoped("/bin/sh", []string{"sh", "-c", os.Getenv(ieArgEnv)}, os.Environ(), func() error { return nil }) |
| + fmt.Println("tty-init:", err) |
| + return 71 |
| +} |
| + |
| +// startTTYInit runs the tty trampoline in a child process (this test |
| +// binary), hands it a fresh pty's slave over its stdin socket as the agent |
| +// does, and returns the child, the master and the child's stdout. |
| +func startTTYInit(t *testing.T, script string) (*exec.Cmd, *os.File, <-chan struct{}) { |
| + t.Helper() |
| + cmd, master, _, done := startTTYInitAgent(t, script) |
| + return cmd, master, done |
| +} |
| + |
| +// startTTYInitAgent is startTTYInit that also returns the agent's end of |
| +// the handoff socket, still open. |
| +func startTTYInitAgent(t *testing.T, script string) (*exec.Cmd, *os.File, *os.File, <-chan struct{}) { |
| + t.Helper() |
| + master, slave := openPTY(t) |
| + agent, tramp := socketPair(t) |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command(self) |
| + cmd.Env = append(withRole("tty-init"), ieArgEnv+"="+script) |
| + cmd.Stdin = tramp |
| + cmd.Stdout = os.Stderr |
| + cmd.Stderr = os.Stderr |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + // done closes once the child is reaped, so the test and the cleanup |
| + // can both wait on it. |
| + done := make(chan struct{}) |
| + go func() { _ = cmd.Wait(); close(done) }() |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Signal(syscall.SIGTERM) |
| + select { |
| + case <-done: |
| + case <-time.After(2 * time.Second): |
| + _ = cmd.Process.Kill() |
| + <-done |
| + } |
| + }) |
| + tramp.Close() |
| + send(t, agent, instancectl.TTYHello, slave) |
| + // The agent keeps only the master, as it will. |
| + slave.Close() |
| + return cmd, master, agent, done |
| +} |
| + |
| +// readUntil reads the master until want appears or d passes. |
| +func readUntil(t *testing.T, master *os.File, want string, d time.Duration) string { |
| + t.Helper() |
| + master.SetReadDeadline(time.Now().Add(d)) |
| + var b strings.Builder |
| + buf := make([]byte, 256) |
| + for !strings.Contains(b.String(), want) { |
| + n, err := master.Read(buf) |
| + b.Write(buf[:n]) |
| + if err != nil { |
| + t.Fatalf("reading the master for %q: %v (read %q)", want, err, b.String()) |
| + } |
| + } |
| + return b.String() |
| +} |
| + |
| +func exitCodeWithin(t *testing.T, cmd *exec.Cmd, done <-chan struct{}, d time.Duration) int { |
| + t.Helper() |
| + select { |
| + case <-done: |
| + case <-time.After(d): |
| + t.Fatalf("the trampoline is still running after %v", d) |
| + } |
| + ws := cmd.ProcessState.Sys().(syscall.WaitStatus) |
| + if ws.Signaled() { |
| + t.Fatalf("the trampoline died by %v", ws.Signal()) |
| + } |
| + return ws.ExitStatus() |
| +} |
| + |
| +func TestTTYTenantOwnsTheTerminal(t *testing.T) { |
| + t.Run("session leader with the pty as its terminal", func(t *testing.T) { |
| + cmd, master, done := startTTYInit(t, `tty -s && ps -o pid= -o sid= -o pgid= -o tpgid= -p $$ && echo done`) |
| + out := readUntil(t, master, "done", 10*time.Second) |
| + var nums []int |
| + for _, line := range strings.Split(out, "\n") { |
| + f := strings.Fields(line) |
| + if len(f) != 4 { |
| + continue |
| + } |
| + nums = nums[:0] |
| + for _, s := range f { |
| + n, err := strconv.Atoi(s) |
| + if err != nil { |
| + break |
| + } |
| + nums = append(nums, n) |
| + } |
| + if len(nums) == 4 { |
| + break |
| + } |
| + } |
| + if len(nums) != 4 { |
| + t.Fatalf("no pid/sid/pgid/tpgid line in %q", out) |
| + } |
| + pid, sid, pgid, tpgid := nums[0], nums[1], nums[2], nums[3] |
| + if sid != pid { |
| + t.Errorf("tenant sid %d, pid %d: not a session leader", sid, pid) |
| + } |
| + if tpgid != pgid { |
| + t.Errorf("terminal's foreground group %d, tenant's group %d: the pty is not the tenant's terminal", tpgid, pgid) |
| + } |
| + if code := exitCodeWithin(t, cmd, done, 10*time.Second); code != 0 { |
| + t.Errorf("trampoline exit %d, want the tenant's 0", code) |
| + } |
| + }) |
| + |
| + t.Run("Ctrl-C ends the tenant and Ctrl-Z cannot freeze it", func(t *testing.T) { |
| + cmd, master, done := startTTYInit(t, `echo ready; exec sleep 30`) |
| + readUntil(t, master, "ready", 10*time.Second) |
| + time.Sleep(200 * time.Millisecond) // past the exec of sleep |
| + // Ctrl-Z first: a stopped sleep would never see the Ctrl-C. |
| + if _, err := master.Write([]byte{0x1a}); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + if _, err := master.Write([]byte{0x03}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code := exitCodeWithin(t, cmd, done, 10*time.Second); code != 130 { |
| + t.Errorf("trampoline exit %d, want 130 (the tenant's SIGINT)", code) |
| + } |
| + }) |
| +} |
| + |
| +// The trampoline keeps no copy of the pty: once the tenant has closed its |
| +// side, the agent's master reads EIO while the trampoline still runs. |
| +func TestTTYInitKeepsNoCopyOfThePTY(t *testing.T) { |
| + _, master, done := startTTYInit(t, `exec sleep 30 0<&- 1>&- 2>&-`) |
| + master.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| + buf := make([]byte, 64) |
| + var err error |
| + for err == nil { |
| + _, err = master.Read(buf) |
| + } |
| + if !errors.Is(err, syscall.EIO) { |
| + t.Fatalf("master read: %v, want EIO once the tenant's side is gone", err) |
| + } |
| + select { |
| + case <-done: |
| + t.Fatal("the trampoline exited: the EIO proves nothing about its copy") |
| + default: |
| + } |
| +} |
| + |
| +// The trampoline closes the handoff socket once it has the terminal: the |
| +// agent reads EOF on it while the tenant still runs. |
| +func TestTTYLaunchClosesTheHandoffSocket(t *testing.T) { |
| + _, master, agent, done := startTTYInitAgent(t, `echo ready; exec sleep 30`) |
| + readUntil(t, master, "ready", 10*time.Second) |
| + fds := []unix.PollFd{{Fd: int32(agent.Fd()), Events: unix.POLLIN}} |
| + n, err := unix.Poll(fds, 5000) |
| + for err == unix.EINTR { |
| + n, err = unix.Poll(fds, 5000) |
| + } |
| + if err != nil || n != 1 { |
| + t.Fatalf("the handoff socket is still open with the tenant running (poll %d, %v)", n, err) |
| + } |
| + buf := make([]byte, 8) |
| + if got, err := unix.Read(int(agent.Fd()), buf); got != 0 || err != nil { |
| + t.Errorf("agent read %d, %v; want EOF", got, err) |
| + } |
| + select { |
| + case <-done: |
| + t.Fatal("the trampoline exited: the EOF proves nothing about the handoff") |
| + default: |
| + } |
| +} |
| + |
| +// A controlling terminal needs stdio, and stdio is three files: refused |
| +// before anything is set up (scope is never reached). |
| +func TestRunInitCheckedRefusesABadStdio(t *testing.T) { |
| + devNull, err := os.Open(os.DevNull) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer devNull.Close() |
| + errScope := errors.New("scope reached") |
| + for name, c := range map[string]struct { |
| + stdio []*os.File |
| + ctty bool |
| + }{ |
| + "ctty with the init's own stdio": {nil, true}, |
| + "one file": {[]*os.File{devNull}, false}, |
| + "four files": {[]*os.File{devNull, devNull, devNull, devNull}, true}, |
| + } { |
| + reached := false |
| + err := runInitChecked("/bin/true", []string{"true"}, nil, c.stdio, c.ctty, func() error { reached = true; return errScope }, nil) |
| + if err == nil || errors.Is(err, errScope) || reached { |
| + t.Errorf("%s: %v (scope reached %t)", name, err, reached) |
| + } |
| + } |
| +} |
diff --git a/internal/instanceexec/tty_other.go b/internal/instanceexec/tty_other.go| new file mode 100644 |
| index 000000000..94327764d |
| --- /dev/null |
| +++ b/internal/instanceexec/tty_other.go |
| @@ -0,0 +1,11 @@ |
| +//go:build !linux |
| + |
| +package instanceexec |
| + |
| +import "errors" |
| + |
| +// ttyLaunch: the tty role takes its terminal over a unix socket with |
| +// SCM_RIGHTS and starts the tenant under the linux init. |
| +func ttyLaunch(string, []string, []string) error { |
| + return errors.New("instance-exec: tty sessions need linux") |
| +} |
diff --git a/internal/provision/rootfs_apps_6_census_test.go b/internal/provision/rootfs_apps_6_census_test.go| index 17363b7c2..275aba425 100644 |
| --- a/internal/provision/rootfs_apps_6_census_test.go |
| +++ b/internal/provision/rootfs_apps_6_census_test.go |
| @@ -17,11 +17,17 @@ package provision |
| // interactive setting's CAS write of the app's config.json |
| // (apps/<acct>/<app>/config.json), claimRawSetSwapPolicy's shape: not a |
| // record, nonrecord. |
| +// - Task 7: instance-exit's parseExitArgs names tty in its usage line |
| +// (<run|seed|sidecar|cmd|worker|tty>), since every tty unit's |
| +// ExecStopPost= runs it (PF-9); the role parsing, its refusals and the |
| +// -run-dir usage text naming instances/<id> are unchanged, nothing |
| +// written. |
| func rootfsApps6WriteCensusInventory() []censusEntry { |
| entries := append([]censusEntry(nil), fleetPublicRoutesWriteCensusInventory()...) |
| replacements := []censusEntry{ |
| {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "be1b699f14a2f8d6935d959dee168bdf6fb556cd78da458f5ba8a1c0e8512a17"}, |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "93f090dcda4e5364f3cff993cebfc1385550039316a59aacaba72ba933ba14b3"}, |
| + {"internal/instanceexec/exit.go", "parseExitArgs", "key-site", "lit:instances", "be3a7828e292b4977c42f21d8283fc9d185505ced9ffdf2543267a88bc8033a9"}, |
| } |
| for _, r := range replacements { |
| found := false |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 71ac85829..b6feb521d 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -43,4 +43,4 @@ plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2 |
| plan14-root-reads-managed-fleets-1c-451.tsv af326671321edda76c7e6217a47892605a9e3b886fa880ad6d049c2f28f63873 |
| plan14-root-reads-fleet-public-routes.tsv bca6ef741a96b72767b1747789cd01b3111d61b68548cbe368258c31f3d53a2e |
| plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7 |
| -plan14-root-reads-rootfs-apps-6.tsv b611b6ff7f86bc5b046a41d3d89ababf673ebd13e6e4c2593d7d2de4112729e1 |
| +plan14-root-reads-rootfs-apps-6.tsv 44581c3700aa3a72c593ef0493663ee42b2c9425231efbfbb6d67abd3a6fced8 |
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv| index bac884585..4d6e83973 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv |
| @@ -1,7 +1,7 @@ |
| # Census overlay rootfs-apps-6, written by census-propose (#369). census-ruling-rootfs-apps-6, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-apps-6.md. |
| # 12 body, 0 sites, 7 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| # 1 removed: each unit's declaration, or each envelope's directory, is absent from the scanned tree, so its row goes, a frozen declaration is retired as absent, and an envelope is retired. |
| -# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +# 4 new dispositions: 0 reads re-frozen at their disposition with the claim, 4 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy ee96c9cf9e4e6b0dea8325a3eaf0053773b3a20d3940afe881a0db8aa71b2d23 internal/host/units/carlos-instance-cmd@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the cmd unit template (applied by PID 1 as root; its process runs as carlos): extends the J4 seed pattern to the run role. The template equals the seed template outside named lines, and the template-equality test pins that. Root lays out a staged executable validated by the same refuseStagedExe the seed and generation paths use, then starts this unit, which runs as carlos with the instance's own reach. No new trust of registry, /data or agent-asserted content beyond the seed path;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 925113f4c51c091f0da65c2c67c5902aa35ab37abbe6491ca935820517e8149d |
| @legacy c986824bab7acb9d785c21f3a48d18f8e678d9252eaea80839ec869f52787a5e internal/host/units/carlos-instance-gen@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 0bd25fefd9306449d55e235e9bd8986466bc4cd68ad56b5614d32596ce39c262 |
| @legacy 4cb19ff14f607602d752f0e329036d5c52eb64f4b1547b2116918b77cb5f4af1 internal/host/units/carlos-instance-probe.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-2;basis=one more BindReadOnlyPaths= line, so PID 1 opens one more bind source: /run/carlos-control/exe/_probe/box-addrs, bound to /opt/carlos/box-addrs, root's list of the box's own addresses, which RunProbe writes before every run (#367) in the root-only directory the unit already binds from; no tenant, app or agent input names or writes it;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service, so the probe proves what the tenants get (its new pts-private line); fix round 1 (Astra P2, roll order): one line outside the namespace block, Environment=CARLOS_PROBE_PTS_PRIVATE=1, a constant the unit sets for its own process (the probe, as carlos, in the namespace); it names no path, adds no bind source or Exec line, and root reads nothing new file:external@0 a803c8e83ffd95ceca691e0c47e623acfa50e88dcddd3166e6660473aa86695b |
| @@ -17,6 +17,7 @@ |
| @legacy 14cec7be2873b15f373f40e319f5c6c61d441f521121499f2a04b331bd3453f3 internal/host/units/carlos-instance-rootfs-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the rootfs tty template, carlos-instance-rootfs-cmd@.service outside named lines held by TestRootfsTTYTemplateEqualsRootfsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit --rootfs tty %I, StandardInput=file:/run/carlos/logs/%I.tty.sock with StandardOutput/StandardError=journal, and RootImage plus the two BindReadOnlyPaths sources under /run/carlos-control/exe/%I/rootfs/tty/ (root-only exe layout) instead of rootfs/cmd/. The rootfs namespace block byte for byte (TestRootfsTemplatesShareOneNamespace), runs as carlos, binds only the instance own and root paths (TestRootfsTemplatesBindOnlyTheInstancesOwnAndRoots). Task 6: POST /tty runtime=rootfs (startRootfsCmd with RoleTTY) starts it through Plan 2's rootfs one-shot path (preflight, validateStagedImage, ensureRootfsExe under rootfs/tty/, jit drop-in and owed reload, post-start MemoryDenyWriteExecute check); its files go only through removeRootfsUnitFiles (stopRootfs and cleanCmdExe with RoleTTY, the sweep) file:external@0 d57f6d6fbe553e5ba5a5762ab2bd72586835ce1db748b67044edd1bf90af6953 |
| @legacy b18625dfcfcaa6d4e0ae128e2b77ad7fb53d0a4206458b43ef4125d248e6ef58 internal/host/units/carlos-instance-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the binary tty template, carlos-instance-cmd@.service outside six named lines held by TestTTYTemplateEqualsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit tty %I (the same root binary as every template), StandardInput=file:/run/carlos/logs/%I.tty.sock replacing the cmd StandardOutput socket (PID 1 opens it as root on the nosymfollow logs mount, as the cmd streams), StandardOutput=journal, StandardError=journal, and BindReadOnlyPaths sources tty-app/tty-live under /run/carlos-control/exe/%I (root-only exe layout, as cmd-app/cmd-live). Same namespace block byte for byte, runs as carlos. Task 6: POST /tty (handleOneShot(RoleTTY), claimAwareLegacy) starts it, after the role lock, the loaded-state refusal and refuseStagedExe; the tty-app/tty-live sources are laid out by ensureCmdExeAt(RoleTTY) and removed by removeCmdExe(RoleTTY) at /stop role=tty and /sweep file:external@0 060295d0956afad52db77dba1988c508cf4289f9b5a18242a206a315145b8e0d |
| @legacy 9491fe16a762f2bfb2e6b288428f67b157b813d01c226917ec4c3366ebffb305 internal/instancectl/cmd.go Server.oneShotStatus legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: handleCmdStatus's body moved whole and made role-aware (it serves GET /cmd/{host} and GET /tty/{host} through handleOneShotStatus(role), both claimAwareLegacy): the same three file:Query sites (the URL query read for the invocation, for parseQuery and for the role check); the role check now refuses any role field but the route's own (role=tty on /cmd and role=cmd on /tty are 400, before any show); the unit shown is UnitName(role, host) or RootfsUnitName(role, host) for runtime=rootfs, a name root builds from a validated host and a route constant; read-only systemctl show, starts and stops nothing; no file read added file:Query@1090,file:Query@384,file:Query@759 9ea847d9a1e6b0e0929f27b27a9ade5c783c0de1ba0d997523c939be8293e701 |
| +@legacy 8e00efef4ecab3057d44b14e01fba5aa93e5359ba841c4fea91b57487481202f internal/instanceexec/tty_linux.go receivePTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7 (PF-9), new: the trampoline's tty role, run by instance-exec [--rootfs] tty %I as carlos inside the instance's namespace (never root): one recvmsg on its own stdin (the tty unit's StandardInput= socket to the agent), exactly the hello carlos-tty/1 and exactly one SCM_RIGHTS fd (received close-on-exec), else refused with every received fd closed; the one Fstat is of that received fd, which must be a character device of a Unix98 pty slave major (136-143) that answers TCGETS, else refused and closed; it opens, runs and follows no path; the fd becomes only the tenant's stdio and controlling terminal (runTTYInit through runInitChecked, which closes the init's copy after the fork); no root process reads anything new file:Fstat@1454 1099af8a1dc0732b74afbe42bc45ccce6df3db9662ff7dc41f278e2bd4a274ce |
| internal/host/units/carlos-instance-cmd@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the cmd unit template (applied by PID 1 as root; its process runs as carlos): extends the J4 seed pattern to the run role. The template equals the seed template outside named lines, and the template-equality test pins that. Root lays out a staged executable validated by the same refuseStagedExe the seed and generation paths use, then starts this unit, which runs as carlos with the instance's own reach. No new trust of registry, /data or agent-asserted content beyond the seed path;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 925113f4c51c091f0da65c2c67c5902aa35ab37abbe6491ca935820517e8149d |
| internal/host/units/carlos-instance-gen@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 0bd25fefd9306449d55e235e9bd8986466bc4cd68ad56b5614d32596ce39c262 |
| internal/host/units/carlos-instance-probe.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-2;basis=one more BindReadOnlyPaths= line, so PID 1 opens one more bind source: /run/carlos-control/exe/_probe/box-addrs, bound to /opt/carlos/box-addrs, root's list of the box's own addresses, which RunProbe writes before every run (#367) in the root-only directory the unit already binds from; no tenant, app or agent input names or writes it;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service, so the probe proves what the tenants get (its new pts-private line); fix round 1 (Astra P2, roll order): one line outside the namespace block, Environment=CARLOS_PROBE_PTS_PRIVATE=1, a constant the unit sets for its own process (the probe, as carlos, in the namespace); it names no path, adds no bind source or Exec line, and root reads nothing new file:external@0 a803c8e83ffd95ceca691e0c47e623acfa50e88dcddd3166e6660473aa86695b |
| @@ -32,12 +33,13 @@ internal/provision/reconcile.go Reconcile legacy accepted-legacy accepted-legacy |
| internal/host/units/carlos-instance-rootfs-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the rootfs tty template, carlos-instance-rootfs-cmd@.service outside named lines held by TestRootfsTTYTemplateEqualsRootfsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit --rootfs tty %I, StandardInput=file:/run/carlos/logs/%I.tty.sock with StandardOutput/StandardError=journal, and RootImage plus the two BindReadOnlyPaths sources under /run/carlos-control/exe/%I/rootfs/tty/ (root-only exe layout) instead of rootfs/cmd/. The rootfs namespace block byte for byte (TestRootfsTemplatesShareOneNamespace), runs as carlos, binds only the instance own and root paths (TestRootfsTemplatesBindOnlyTheInstancesOwnAndRoots). Task 6: POST /tty runtime=rootfs (startRootfsCmd with RoleTTY) starts it through Plan 2's rootfs one-shot path (preflight, validateStagedImage, ensureRootfsExe under rootfs/tty/, jit drop-in and owed reload, post-start MemoryDenyWriteExecute check); its files go only through removeRootfsUnitFiles (stopRootfs and cleanCmdExe with RoleTTY, the sweep) file:external@0 d57f6d6fbe553e5ba5a5762ab2bd72586835ce1db748b67044edd1bf90af6953 |
| internal/host/units/carlos-instance-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the binary tty template, carlos-instance-cmd@.service outside six named lines held by TestTTYTemplateEqualsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit tty %I (the same root binary as every template), StandardInput=file:/run/carlos/logs/%I.tty.sock replacing the cmd StandardOutput socket (PID 1 opens it as root on the nosymfollow logs mount, as the cmd streams), StandardOutput=journal, StandardError=journal, and BindReadOnlyPaths sources tty-app/tty-live under /run/carlos-control/exe/%I (root-only exe layout, as cmd-app/cmd-live). Same namespace block byte for byte, runs as carlos. Task 6: POST /tty (handleOneShot(RoleTTY), claimAwareLegacy) starts it, after the role lock, the loaded-state refusal and refuseStagedExe; the tty-app/tty-live sources are laid out by ensureCmdExeAt(RoleTTY) and removed by removeCmdExe(RoleTTY) at /stop role=tty and /sweep file:external@0 060295d0956afad52db77dba1988c508cf4289f9b5a18242a206a315145b8e0d |
| internal/instancectl/cmd.go Server.oneShotStatus legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: handleCmdStatus's body moved whole and made role-aware (it serves GET /cmd/{host} and GET /tty/{host} through handleOneShotStatus(role), both claimAwareLegacy): the same three file:Query sites (the URL query read for the invocation, for parseQuery and for the role check); the role check now refuses any role field but the route's own (role=tty on /cmd and role=cmd on /tty are 400, before any show); the unit shown is UnitName(role, host) or RootfsUnitName(role, host) for runtime=rootfs, a name root builds from a validated host and a route constant; read-only systemctl show, starts and stops nothing; no file read added file:Query@1090,file:Query@384,file:Query@759 9ea847d9a1e6b0e0929f27b27a9ade5c783c0de1ba0d997523c939be8293e701 |
| +internal/instanceexec/tty_linux.go receivePTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7 (PF-9), new: the trampoline's tty role, run by instance-exec [--rootfs] tty %I as carlos inside the instance's namespace (never root): one recvmsg on its own stdin (the tty unit's StandardInput= socket to the agent), exactly the hello carlos-tty/1 and exactly one SCM_RIGHTS fd (received close-on-exec), else refused with every received fd closed; the one Fstat is of that received fd, which must be a character device of a Unix98 pty slave major (136-143) that answers TCGETS, else refused and closed; it opens, runs and follows no path; the fd becomes only the tenant's stdio and controlling terminal (runTTYInit through runInitChecked, which closes the init's copy after the fork); no root process reads anything new file:Fstat@1454 1099af8a1dc0732b74afbe42bc45ccce6df3db9662ff7dc41f278e2bd4a274ce |
| @remove internal/instancectl/cmd.go Server.handleCmdStatus |
| @removed internal/instancectl/cmd.go Server.handleCmdStatus H3 census-ruling-rootfs-apps-6;absent;basis=rootfs Plan 6 Task 6: moved whole to Server.oneShotStatus (role-aware; see its claim), not deleted: no check, refusal or validation is lost |
| @coverage . fbc28f10f89cd03cac31bae0d798ae7f707eb7671284a6115abd8c1c214369b6 |
| @coverage internal/appconfig cac8d8ef7538a456d034801c95ce6508a4983e5516b3bbbd302bec0fbafdd479 |
| @coverage internal/host/units c3cc4f3b917fdb938f20d406b1704ec54e24553851c298e312056d397d10b0e1 |
| @coverage internal/instancectl ee755f7827ba8ab62cfe3d67c29a6ce9cc88c276ab995fb58a5fb5a36f18b51a |
| -@coverage internal/instanceexec 16221b476a2d996eb5325ce97a683329639679144b4dcc136b2a018b7abdd9df |
| +@coverage internal/instanceexec 65f6db1c6bf469f1d19615ec989f54c20de3b73c3c03ae2d677cffbcc60470fd |
| @coverage internal/layout 1527c3b31d87743798002b1ebefcd2cb0dc422a8642f72a3ff8dbefbd2c84d9b |
| @coverage internal/provision e1ecfdc3d169773ac6dd9dc09a6d0feea768ceb1b80195199c5ef74b2f0e6f5c |