edge, host: cut 3, prove the console socket's listener with SO_PEERCRED; task 3 R2 P2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+362
−42
docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md+7 −1internal/edge/replicaconsole.go+68 −20internal/edge/replicaconsole_peer_linux.go+33 −0internal/edge/replicaconsole_peer_other.go+14 −0internal/edge/replicaconsole_peer_rootrunner_linux_test.go+43 −0internal/edge/replicaconsole_socket_test.go+46 −0internal/host/consolefleet.go+53 −21internal/host/consolefleet_dropin_rootrunner_linux_test.go+71 −0internal/host/consolefleet_test.go+27 −0
diff --git a/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md b/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md| index a96a89fdf..d24df7194 100644 |
| --- a/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md |
| +++ b/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md |
| @@ -193,7 +193,9 @@ The order is **env > socket > the old route scan**: |
| group- or other-writable) and `fleet.sock` (a socket). |
| Present: forward through one cached reverse proxy whose transport dials |
| that unix path, with the same rewrite, version header and 502 error |
| - handler as `newReplicaConsoleProxy` (`replicaconsole.go:64-89`). A failed |
| + handler as `newReplicaConsoleProxy`. The dial proves with |
| + `SO_PEERCRED` that the listening process runs as the console's recorded |
| + uid before anything is written, on every call (cut 3, §15). A failed |
| dial (the console stopping between the check and the dial) is a 502 with |
| no request written, which the box reads as the console unreachable. |
| 3. Absent or failing the checks: today's route scan, which on the flagship |
| @@ -373,3 +375,7 @@ Round 2's P2s are applied in rev 3 (§15). |
| | R2 | P2-2 failed reloads have no recovery | Applied: the `reload-pending` marker (§4 steps 2-4) | |
| | R2 | P2-3 preservation and mode not established | Applied: the drop-in sets neither; `exclusive` requires `Preserve=no` and mode 0755 (§4 step 5) | |
| | R2 | P2-4 rollout not verifiable remotely | Applied: last call's source, result and time; "no call yet"; API and CLI tests; UX pass before copy (§8) | |
| +| Task 3 R1 | P1 a legacy app-owned directory certified exclusive | Root records the console's uid; the directory must be that uid's (§4, §6) | |
| +| Task 3 R1 | P2-2, P2-3 marker; trusted drop-in read | Edge refuses a record while the marker stands; drop-in read through rootstate | |
| +| Task 3 R2 | P1 systemd re-chowns a directory holding a foreign listener (same family as R1: socket identity) | Stopping rule 2. **Paul chose cut 3, 2026-11-24: check the peer.** One dial function, `dialConsoleFleet` (`internal/edge/replicaconsole.go`), proves with `SO_PEERCRED` that the listener's uid is root's recorded console uid before a byte is written; no connection reuse, so every call is proved; regression test with a foreign listener under a re-chowned directory (`replicaconsole_peer_rootrunner_linux_test.go`) | |
| +| Task 3 R2 | P2-2 symlinked drop-in not repaired; P2-3 inactive-console directory check dropped; P2-4 numeric `User=` | Applied (`readConsoleFleetDropInAt`, `exclusive`, `consoleUnitUID`) | |
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go| index eeebbcf83..a463ebc19 100644 |
| --- a/internal/edge/replicaconsole.go |
| +++ b/internal/edge/replicaconsole.go |
| @@ -75,20 +75,59 @@ func parseReplicaConsoleAddr(raw string) (string, error) { |
| // build. A failed dial answers 502 with no version, which the box reads as |
| // the console unreachable. |
| func newReplicaConsoleProxy(addr string) http.Handler { |
| - return replicaConsoleProxy(addr, (&net.Dialer{Timeout: 5 * time.Second}).DialContext) |
| + return replicaConsoleProxy(addr, (&net.Dialer{Timeout: 5 * time.Second}).DialContext, false) |
| } |
| // newReplicaConsoleSocketProxy is newReplicaConsoleProxy for the console's |
| // fleet socket (consolefleet.Socket): every connection dials that one unix |
| -// path, whatever the request names. |
| +// path, whatever the request names, through dialConsoleFleet, which proves |
| +// the listener is the console's user before the proxy writes a byte. No |
| +// connection is kept for reuse, so every call is a fresh dial and a fresh |
| +// proof: a console that restarts, or a recorded user that changes, never |
| +// meets a connection proved against the old one. |
| func newReplicaConsoleSocketProxy(socket string) http.Handler { |
| - d := &net.Dialer{Timeout: 5 * time.Second} |
| return replicaConsoleProxy("console-fleet", func(ctx context.Context, _, _ string) (net.Conn, error) { |
| - return d.DialContext(ctx, "unix", socket) |
| - }) |
| + uid, ok := ctx.Value(consoleFleetUIDKey{}).(int) |
| + if !ok { |
| + return nil, errors.New("console fleet socket: no recorded console user for this call") |
| + } |
| + return dialConsoleFleet(ctx, socket, uid) |
| + }, true) |
| } |
| -func replicaConsoleProxy(host string, dial func(ctx context.Context, network, addr string) (net.Conn, error)) http.Handler { |
| +// consoleFleetUIDKey carries, in a box call's context, the console user |
| +// root recorded when the edge chose the socket for it. |
| +type consoleFleetUIDKey struct{} |
| + |
| +// dialConsoleFleet is the one place the edge connects to the console's |
| +// fleet socket, and the one check that the process listening there is the |
| +// console (Paul's cut 3, 2026-11-24, after task 3 review R2 P1): the |
| +// kernel's credentials for the listening end (SO_PEERCRED, the uid that |
| +// created the listener) must be uid, root's recorded console user. The |
| +// directory's owner is not enough: systemd re-chowns an existing runtime |
| +// directory, and whatever it holds, to the console's user at start, so a |
| +// socket another process bound there before keeps listening under the |
| +// console's ownership. A mismatch closes the connection before anything |
| +// is written, and the proxy answers 502. |
| +func dialConsoleFleet(ctx context.Context, socket string, uid int) (net.Conn, error) { |
| + d := &net.Dialer{Timeout: 5 * time.Second} |
| + c, err := d.DialContext(ctx, "unix", socket) |
| + if err != nil { |
| + return nil, err |
| + } |
| + peer, err := unixPeerUID(c) |
| + if err != nil { |
| + c.Close() |
| + return nil, fmt.Errorf("console fleet socket: reading the listener's credentials: %w", err) |
| + } |
| + if peer != uid { |
| + c.Close() |
| + return nil, fmt.Errorf("console fleet socket: the listener runs as uid %d, not the console's (uid %d)", peer, uid) |
| + } |
| + return c, nil |
| +} |
| + |
| +func replicaConsoleProxy(host string, dial func(ctx context.Context, network, addr string) (net.Conn, error), noReuse bool) http.Handler { |
| return &httputil.ReverseProxy{ |
| Rewrite: func(pr *httputil.ProxyRequest) { |
| setForwarded(pr) |
| @@ -98,6 +137,7 @@ func replicaConsoleProxy(host string, dial func(ctx context.Context, network, ad |
| }, |
| Transport: &http.Transport{ |
| DialContext: dial, |
| + DisableKeepAlives: noReuse, |
| MaxIdleConns: 8, |
| IdleConnTimeout: 90 * time.Second, |
| ResponseHeaderTimeout: 30 * time.Second, |
| @@ -106,7 +146,10 @@ func replicaConsoleProxy(host string, dial func(ctx context.Context, network, ad |
| resp.Header.Set("X-Carlos-Version", version.Build) |
| return nil |
| }, |
| - ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { |
| + ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) { |
| + if noReuse { |
| + log.Printf("edge: fleet replica call to the console socket failed: %v", err) |
| + } |
| w.WriteHeader(http.StatusBadGateway) |
| }, |
| } |
| @@ -133,7 +176,10 @@ func (e *Edge) LastReplicaConsoleCall() *ReplicaConsoleCall { return e.lastRepli |
| // ConsoleFleetSocketReady is whether a box call would go to the console's |
| // fleet socket now, were the operator's endpoint unset: nil, or why not. |
| -func (e *Edge) ConsoleFleetSocketReady() error { return e.consoleFleet.ready() } |
| +func (e *Edge) ConsoleFleetSocketReady() error { |
| + _, err := e.consoleFleet.ready() |
| + return err |
| +} |
| // consoleFleetSource is where the edge finds the console's fleet socket and |
| // root's word that the console holds its directory alone (hub console spec |
| @@ -188,43 +234,43 @@ func readConsoleFleetRecordIn(dir string) (consolefleet.Record, error) { |
| return rec, nil |
| } |
| -// ready is nil when a box call may go to the socket: root's record says |
| +// ready is the console's recorded uid when a box call may go to the socket: root's record says |
| // the console holds its runtime directory alone, the directory is a real |
| // directory only its owner can write, and the socket is a socket. Only root |
| // can create /run/carlos-console and only its owner can place a socket in |
| // it, so what passes here was put there by console.service. |
| -func (c consoleFleetSource) ready() error { |
| +func (c consoleFleetSource) ready() (int, error) { |
| if c.record == nil { |
| - return errors.New("no console fleet source") |
| + return 0, errors.New("no console fleet source") |
| } |
| rec, err := c.record() |
| if err != nil { |
| - return fmt.Errorf("root's console fleet record: %w", err) |
| + return 0, fmt.Errorf("root's console fleet record: %w", err) |
| } |
| if !rec.Exclusive { |
| - return fmt.Errorf("root's console fleet record is not exclusive: %s", rec.Reason) |
| + return 0, fmt.Errorf("root's console fleet record is not exclusive: %s", rec.Reason) |
| } |
| fi, err := os.Lstat(c.dir) |
| if err != nil { |
| - return err |
| + return 0, err |
| } |
| if !fi.IsDir() || fi.Mode().Perm()&0o022 != 0 { |
| - return fmt.Errorf("%s is not a directory only its owner can write (%v)", c.dir, fi.Mode()) |
| + return 0, fmt.Errorf("%s is not a directory only its owner can write (%v)", c.dir, fi.Mode()) |
| } |
| // The directory must still be the console's: root recorded its user, |
| // and a process that held the directory before root looked would own |
| // it under another uid (task 3 review R1 P1). |
| if owner, ok := fileOwner(fi); !ok || owner != rec.ConsoleUID { |
| - return fmt.Errorf("%s belongs to uid %d, not the console's (uid %d)", c.dir, owner, rec.ConsoleUID) |
| + return 0, fmt.Errorf("%s belongs to uid %d, not the console's (uid %d)", c.dir, owner, rec.ConsoleUID) |
| } |
| si, err := os.Lstat(c.socket) |
| if err != nil { |
| - return err |
| + return 0, err |
| } |
| if si.Mode().Type() != fs.ModeSocket { |
| - return fmt.Errorf("%s is not a socket (%v)", c.socket, si.Mode()) |
| + return 0, fmt.Errorf("%s is not a socket (%v)", c.socket, si.Mode()) |
| } |
| - return nil |
| + return rec.ConsoleUID, nil |
| } |
| // withConsoleFleet sets the edge's socket source and its proxy together. |
| @@ -309,7 +355,9 @@ func (e *Edge) routeReplicaConsole(w http.ResponseWriter, r *http.Request) strin |
| e.replicaConsole.ServeHTTP(w, e.withForwardKey(r)) |
| return ReplicaConsoleSourceEnv |
| } |
| - if err := e.consoleFleet.ready(); err == nil { |
| + if uid, err := e.consoleFleet.ready(); err == nil { |
| + // The listener's own user is proved at the dial (dialConsoleFleet). |
| + r = r.WithContext(context.WithValue(r.Context(), consoleFleetUIDKey{}, uid)) |
| e.consoleFleetProxy.ServeHTTP(w, e.withForwardKey(r)) |
| return ReplicaConsoleSourceSocket |
| } else { |
diff --git a/internal/edge/replicaconsole_peer_linux.go b/internal/edge/replicaconsole_peer_linux.go| new file mode 100644 |
| index 000000000..05bd73dab |
| --- /dev/null |
| +++ b/internal/edge/replicaconsole_peer_linux.go |
| @@ -0,0 +1,33 @@ |
| +//go:build linux |
| + |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// unixPeerUID is the uid the kernel recorded for the other end of a unix |
| +// stream connection: for a connection the edge dialled, the process that |
| +// created the listening socket (SO_PEERCRED). |
| +func unixPeerUID(c net.Conn) (int, error) { |
| + uc, ok := c.(*net.UnixConn) |
| + if !ok { |
| + return 0, errors.New("not a unix connection") |
| + } |
| + raw, err := uc.SyscallConn() |
| + if err != nil { |
| + return 0, 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 0, err |
| + } |
| + if credErr != nil { |
| + return 0, credErr |
| + } |
| + return int(cred.Uid), nil |
| +} |
diff --git a/internal/edge/replicaconsole_peer_other.go b/internal/edge/replicaconsole_peer_other.go| new file mode 100644 |
| index 000000000..978417537 |
| --- /dev/null |
| +++ b/internal/edge/replicaconsole_peer_other.go |
| @@ -0,0 +1,14 @@ |
| +//go:build !linux |
| + |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "net" |
| +) |
| + |
| +// unixPeerUID: SO_PEERCRED is Linux's, and so is the console's fleet |
| +// socket; elsewhere no listener is proved, so the socket is never used. |
| +func unixPeerUID(net.Conn) (int, error) { |
| + return 0, errors.New("listener credentials are not available on this platform") |
| +} |
diff --git a/internal/edge/replicaconsole_peer_rootrunner_linux_test.go b/internal/edge/replicaconsole_peer_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..2f2943428 |
| --- /dev/null |
| +++ b/internal/edge/replicaconsole_peer_rootrunner_linux_test.go |
| @@ -0,0 +1,43 @@ |
| +//go:build linux && rootrunner |
| + |
| +package edge |
| + |
| +import ( |
| + "net/http" |
| + "os" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/consolefleet" |
| +) |
| + |
| +// TestReplicaConsoleForeignListenerSurvivesChown is task 3 review R2 P1's |
| +// case: a process binds fleet.sock in the directory, then systemd starts |
| +// the console and re-chowns the directory and everything in it to the |
| +// console's user. Root's record and the directory's owner both say |
| +// "console" now; the listener is still the other process's. The peer |
| +// check refuses it: 502, nothing reaches the listener. Root only: it needs |
| +// a listener under one uid and a directory under another. |
| +func TestReplicaConsoleForeignListenerSurvivesChown(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Skip("needs root") |
| + } |
| + const consoleUID = 1000 |
| + f := newFleetSocketFixture(t) // the listener: created by this process, uid 0 |
| + for _, p := range []string{f.dir, f.socket} { |
| + if err := os.Chown(p, consoleUID, consoleUID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: true, ConsoleUID: consoleUID}) |
| + e, routeHits := socketEdge(t, f) |
| + if err := e.ConsoleFleetSocketReady(); err != nil { |
| + t.Fatalf("the directory checks should pass here, so only the peer check stands between: %v", err) |
| + } |
| + w := postBoxCall(t, e) |
| + if w.Code != http.StatusBadGateway || w.Header().Get("X-Carlos-Version") != "" || f.hits.Load() != 0 || routeHits.Load() != 0 { |
| + t.Fatalf("%d version %q listener hits %d route hits %d", w.Code, w.Header().Get("X-Carlos-Version"), f.hits.Load(), routeHits.Load()) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceSocket || c.Result != "502" { |
| + t.Fatalf("last call %+v", c) |
| + } |
| +} |
diff --git a/internal/edge/replicaconsole_socket_test.go b/internal/edge/replicaconsole_socket_test.go| index 9f1066269..62fe807e6 100644 |
| --- a/internal/edge/replicaconsole_socket_test.go |
| +++ b/internal/edge/replicaconsole_socket_test.go |
| @@ -352,3 +352,49 @@ func TestReplicaCallStatusUnwraps(t *testing.T) { |
| t.Fatalf("101 result %q", w.result()) |
| } |
| } |
| + |
| +// TestDialConsoleFleetRefusesAForeignListener: the one dial to the fleet |
| +// socket proves the listener's uid (SO_PEERCRED) before anything is |
| +// written; a listener under any other uid is closed on with not a byte |
| +// sent (Paul's cut 3, 2026-11-24). |
| +func TestDialConsoleFleetRefusesAForeignListener(t *testing.T) { |
| + dir, err := os.MkdirTemp("", "cfp") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + sock := filepath.Join(dir, "s") |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + got := make(chan int, 4) |
| + go func() { |
| + for { |
| + c, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + b, _ := io.ReadAll(c) |
| + c.Close() |
| + got <- len(b) |
| + } |
| + }() |
| + c, err := dialConsoleFleet(t.Context(), sock, os.Getuid()+1) |
| + if err == nil { |
| + c.Close() |
| + t.Fatal("a listener under another uid was accepted") |
| + } |
| + if !strings.Contains(err.Error(), "not the console's") { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if n := <-got; n != 0 { |
| + t.Fatalf("%d bytes reached the foreign listener", n) |
| + } |
| + c, err = dialConsoleFleet(t.Context(), sock, os.Getuid()) |
| + if err != nil { |
| + t.Fatalf("own listener refused: %v", err) |
| + } |
| + c.Close() |
| +} |
diff --git a/internal/host/consolefleet.go b/internal/host/consolefleet.go| index e422bab10..37a75bdcd 100644 |
| --- a/internal/host/consolefleet.go |
| +++ b/internal/host/consolefleet.go |
| @@ -208,12 +208,9 @@ func (s consoleFleetStep) exclusive(p consoleUnitProps) (bool, int, string) { |
| if host, claimed := s.claimant(); claimed { |
| return no("a capability drop-in for %s also claims %s", host, consolefleet.Dir) |
| } |
| - uid := 0 |
| - if p.User != "" { |
| - var err error |
| - if uid, err = s.lookupUID(p.User); err != nil { |
| - return no("%s runs as %s, whose uid cannot be found: %v", consolefleet.Unit, p.User, err) |
| - } |
| + uid, err := consoleUnitUID(p.User, s.lookupUID) |
| + if err != nil { |
| + return no("%s runs as %s, whose uid cannot be found: %v", consolefleet.Unit, p.User, err) |
| } |
| owner, exists, err := s.runDirOwner() |
| if err != nil { |
| @@ -222,9 +219,34 @@ func (s consoleFleetStep) exclusive(p consoleUnitProps) (bool, int, string) { |
| if exists && owner != uid { |
| return no("%s belongs to uid %d, not %s's user (uid %d)", consolefleet.Dir, owner, consolefleet.Unit, uid) |
| } |
| + switch p.ActiveState { |
| + case "active", "activating", "reloading", "deactivating": |
| + default: |
| + // systemd removes the directory when the unit stops, so one there |
| + // while the console is not running was not left by it (task 3 |
| + // review R2 P2-3). |
| + if exists { |
| + return no("%s exists while %s is %s, so something else made it", consolefleet.Dir, consolefleet.Unit, p.ActiveState) |
| + } |
| + } |
| return true, uid, "" |
| } |
| +// consoleUnitUID is systemd's reading of User=: empty is root, a number is |
| +// that uid (task 3 review R2 P2-4), anything else a user name to look up. |
| +func consoleUnitUID(user string, lookup func(string) (int, error)) (int, error) { |
| + if user == "" { |
| + return 0, nil |
| + } |
| + if n, err := strconv.Atoi(user); err == nil { |
| + if n < 0 { |
| + return 0, fmt.Errorf("uid %d", n) |
| + } |
| + return n, nil |
| + } |
| + return lookup(user) |
| +} |
| + |
| // persist writes rec unless the stored record differs only in its time, so |
| // an idle hourly pass does not churn the file; At is when this state began. |
| func (s consoleFleetStep) persist(rec consolefleet.Record) { |
| @@ -318,28 +340,38 @@ func productionConsoleFleetStep(ctx context.Context) consoleFleetStep { |
| } |
| } |
| -// readConsoleFleetDropIn reads root's drop-in through rootstate's trusted |
| -// open (task 3 review R1 P2-3): absent is (nil, false); a file that exists |
| -// but fails the trust checks (a symlink, not root's, writable by others) is |
| -// reported present with no bytes, so the step replaces it with its own |
| -// root-owned file; a directory chain that fails them is an error, since |
| -// writing into it would not make the file root's. |
| +// readConsoleFleetDropIn reads root's drop-in. The directory it lives in |
| +// must pass rootstate's trust walk (root-owned all the way from /), or the |
| +// step stops: writing into it would not make the file root's. In that |
| +// trusted directory, an entry that is absent is (nil, false); one that is |
| +// not a plain root-owned file only root can write, with one link (a |
| +// symlink, a hard link, another owner, a directory) is reported present |
| +// with no bytes, so the step replaces it with its own file by rename (task |
| +// 3 review R1 P2-3 and R2 P2-2). |
| func readConsoleFleetDropIn() ([]byte, bool, error) { |
| - f, err := rootstate.OpenTrustedFile(consolefleet.DropInPath) |
| + return readConsoleFleetDropInAt(consolefleet.DropInPath) |
| +} |
| + |
| +func readConsoleFleetDropInAt(path string) ([]byte, bool, error) { |
| + dirPath := filepath.Dir(path) |
| + d, err := rootstate.OpenTrustedDir(dirPath) |
| if errors.Is(err, fs.ErrNotExist) { |
| return nil, false, nil |
| } |
| - if errors.Is(err, fs.ErrPermission) { |
| - d, derr := rootstate.OpenTrustedDir(filepath.Dir(consolefleet.DropInPath)) |
| - if derr != nil { |
| - return nil, false, fmt.Errorf("%s is not a root-owned directory: %w", filepath.Dir(consolefleet.DropInPath), derr) |
| - } |
| - d.Close() |
| - return nil, true, nil |
| - } |
| if err != nil { |
| + return nil, false, fmt.Errorf("%s is not a root-owned directory: %w", dirPath, err) |
| + } |
| + defer d.Close() |
| + name := filepath.Base(path) |
| + if _, err := os.Lstat(path); errors.Is(err, fs.ErrNotExist) { |
| + return nil, false, nil |
| + } else if err != nil { |
| return nil, false, err |
| } |
| + f, err := rootstate.OpenTrustedFileIn(d, name) |
| + if err != nil { |
| + return nil, true, nil |
| + } |
| defer f.Close() |
| b, err := io.ReadAll(io.LimitReader(f, consolefleet.MaxRecord+1)) |
| return b, true, err |
diff --git a/internal/host/consolefleet_dropin_rootrunner_linux_test.go b/internal/host/consolefleet_dropin_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..353106d40 |
| --- /dev/null |
| +++ b/internal/host/consolefleet_dropin_rootrunner_linux_test.go |
| @@ -0,0 +1,71 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +// TestReadConsoleFleetDropInRepairs: in a root-owned directory, root's own |
| +// drop-in reads back; a symlink, a hard link or a file another user owns |
| +// at the path reads as present with no bytes, so the step replaces it |
| +// (task 3 review R2 P2-2); an absent file is absent. Root only: the trust |
| +// walk needs a root-owned directory chain, which /tmp is not. |
| +func TestReadConsoleFleetDropInRepairs(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Skip("needs root") |
| + } |
| + dir, err := os.MkdirTemp("/var/lib", "carlos-console-dropin-test-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + if err := os.Chmod(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + path := filepath.Join(dir, "70-carlos-fleet-socket.conf") |
| + if b, exists, err := readConsoleFleetDropInAt(path); err != nil || exists || b != nil { |
| + t.Fatalf("absent: %q %v %v", b, exists, err) |
| + } |
| + body := []byte("[Service]\nRuntimeDirectory=carlos-console\n") |
| + if err := os.WriteFile(path, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, exists, err := readConsoleFleetDropInAt(path); err != nil || !exists || string(b) != string(body) { |
| + t.Fatalf("root's file: %q %v %v", b, exists, err) |
| + } |
| + other := filepath.Join(dir, "other") |
| + if err := os.WriteFile(other, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, setup := range map[string]func(){ |
| + "symlink": func() { |
| + os.Remove(path) |
| + if err := os.Symlink(other, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "hard link": func() { |
| + os.Remove(path) |
| + if err := os.Link(other, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "another owner": func() { |
| + os.Remove(path) |
| + if err := os.WriteFile(path, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chown(path, 1000, 1000); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + setup() |
| + if b, exists, err := readConsoleFleetDropInAt(path); err != nil || !exists || b != nil { |
| + t.Errorf("%s: %q %v %v, want present with no bytes", name, b, exists, err) |
| + } |
| + } |
| +} |
diff --git a/internal/host/consolefleet_test.go b/internal/host/consolefleet_test.go| index f91e1b3b0..76cb86dcd 100644 |
| --- a/internal/host/consolefleet_test.go |
| +++ b/internal/host/consolefleet_test.go |
| @@ -174,6 +174,12 @@ func TestConsoleFleetNotExclusive(t *testing.T) { |
| "directory not a safe directory": {func(f *fakeConsoleFleet) { |
| f.dirExists, f.dirErr = true, errors.New("/run/carlos-console is not a directory only its owner can write") |
| }, "only its owner can write"}, |
| + "console's own directory while stopped": {func(f *fakeConsoleFleet) { |
| + // Task 3 review R2 P2-3: systemd removes it at stop, so one |
| + // there while the console is not running is not the console's. |
| + f.props.ActiveState = "inactive" |
| + f.dirOwner, f.dirExists = consoleUID, true |
| + }, "exists while console.service is inactive"}, |
| "dynamic user": {func(f *fakeConsoleFleet) { f.props.DynamicUser = "yes" }, "DynamicUser=yes"}, |
| "unknown user": {func(f *fakeConsoleFleet) { f.props.User = "ghost" }, "ghost"}, |
| } { |
| @@ -302,3 +308,24 @@ func TestBuildConsoleFleetBlock(t *testing.T) { |
| t.Fatalf("no edge yet: %+v", b) |
| } |
| } |
| + |
| +// TestConsoleUnitUID: systemd's User= is empty (root), a number, or a name |
| +// (task 3 review R2 P2-4). |
| +func TestConsoleUnitUID(t *testing.T) { |
| + lookup := func(name string) (int, error) { |
| + if name == "console" { |
| + return 997, nil |
| + } |
| + return 0, errors.New("unknown user " + name) |
| + } |
| + for user, want := range map[string]int{"": 0, "0": 0, "997": 997, "console": 997} { |
| + if got, err := consoleUnitUID(user, lookup); err != nil || got != want { |
| + t.Errorf("User=%q: %d %v, want %d", user, got, err, want) |
| + } |
| + } |
| + for _, user := range []string{"ghost", "-1"} { |
| + if _, err := consoleUnitUID(user, lookup); err == nil { |
| + t.Errorf("User=%q resolved", user) |
| + } |
| + } |
| +} |