edge, console: forward box calls to the console's fleet socket; console listens on it; plan review closed (R2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+968
−32
cmd/console/fleetsocket.go+30 −0cmd/console/fleetsocket_other.go+9 −0cmd/console/fleetsocket_test.go+207 −0cmd/console/fleetsocket_unix.go+70 −0cmd/console/main.go+6 −0cmd/console/stop.go+13 −1docs/superpowers/plans/2026-11-24-hub-console-socket.md+27 −16docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R2.md+78 −0internal/edge/edge.go+13 −3internal/edge/replicaconsole.go+197 −12internal/edge/replicaconsole_socket_test.go+318 −0
diff --git a/cmd/console/fleetsocket.go b/cmd/console/fleetsocket.go| new file mode 100644 |
| index 000000000..2ad9be188 |
| --- /dev/null |
| +++ b/cmd/console/fleetsocket.go |
| @@ -0,0 +1,30 @@ |
| +package main |
| + |
| +import ( |
| + "net" |
| + "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/consolefleet" |
| +) |
| + |
| +// The console's fleet socket (hub console spec §5, |
| +// docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md): |
| +// a second listener at consolefleet.Socket, in the runtime directory root's |
| +// drop-in gives console.service, through which the hub's edge hands this |
| +// console fleet boxes' replica and seeds calls. Only root can create the |
| +// directory and only this unit's user can place a socket in it, so the edge |
| +// can send the boxes' bearer tokens there without trusting a route record. |
| + |
| +// fleetSocketOnly answers a request that arrived on a unix listener (the |
| +// fleet socket) only when it is one of the box doors, and 404s the rest: |
| +// the socket is the boxes' way in, never a second door to the console's |
| +// pages or API. |
| +func fleetSocketOnly(h http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if la, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && la.Network() == "unix" && !consolefleet.BoxDoor(r) { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + h.ServeHTTP(w, r) |
| + }) |
| +} |
diff --git a/cmd/console/fleetsocket_other.go b/cmd/console/fleetsocket_other.go| new file mode 100644 |
| index 000000000..df57642ca |
| --- /dev/null |
| +++ b/cmd/console/fleetsocket_other.go |
| @@ -0,0 +1,9 @@ |
| +//go:build !unix |
| + |
| +package main |
| + |
| +import "net" |
| + |
| +// openFleetSocket: the fleet socket is a Linux box's; elsewhere the |
| +// console serves TCP only. |
| +func openFleetSocket(dir, socket string, logf func(string, ...any)) net.Listener { return nil } |
diff --git a/cmd/console/fleetsocket_test.go b/cmd/console/fleetsocket_test.go| new file mode 100644 |
| index 000000000..f7c0c880b |
| --- /dev/null |
| +++ b/cmd/console/fleetsocket_test.go |
| @@ -0,0 +1,207 @@ |
| +//go:build unix |
| + |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestFleetSocketOnlyAnswersBoxDoors: on the unix listener only the box |
| +// doors reach the console; on TCP everything does, as before. |
| +func TestFleetSocketOnlyAnswersBoxDoors(t *testing.T) { |
| + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "console") }) |
| + h := fleetSocketOnly(inner) |
| + unix := &net.UnixAddr{Name: "/run/carlos-console/fleet.sock", Net: "unix"} |
| + tcp := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 8090} |
| + for _, tc := range []struct { |
| + local net.Addr |
| + method, path string |
| + want int |
| + }{ |
| + {unix, "POST", "/api/fleet/replicas/a/app/h/coordinator", 200}, |
| + {unix, "POST", "/api/fleet/seeds/f/b/placed", 200}, |
| + {unix, "GET", "/api/fleet/replicas/a/app/h/coordinator", 404}, |
| + {unix, "POST", "/api/cli/apps", 404}, |
| + {unix, "GET", "/", 404}, |
| + {tcp, "GET", "/", 200}, |
| + {tcp, "POST", "/api/cli/apps", 200}, |
| + } { |
| + r := httptest.NewRequest(tc.method, "http://console-fleet"+tc.path, nil) |
| + r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, tc.local)) |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if w.Code != tc.want { |
| + t.Errorf("%s %s %s: %d, want %d", tc.local.Network(), tc.method, tc.path, w.Code, tc.want) |
| + } |
| + } |
| +} |
| + |
| +// shortTempDir is a temp directory short enough for a unix socket path |
| +// (macOS caps sun_path at 104 bytes). |
| +func shortTempDir(t *testing.T) string { |
| + t.Helper() |
| + d, err := os.MkdirTemp("", "cf") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(d) }) |
| + return d |
| +} |
| + |
| +func TestOpenFleetSocketDirChecks(t *testing.T) { |
| + var logs []string |
| + logf := func(f string, a ...any) { logs = append(logs, f) } |
| + base := shortTempDir(t) |
| + if ln := openFleetSocket(filepath.Join(base, "missing"), filepath.Join(base, "missing", "s"), logf); ln != nil { |
| + t.Fatal("listened with no directory") |
| + } |
| + open := filepath.Join(base, "open") |
| + if err := os.Mkdir(open, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(open, 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ln := openFleetSocket(open, filepath.Join(open, "s"), logf); ln != nil { |
| + t.Fatal("listened in a directory others can write") |
| + } |
| + link := filepath.Join(base, "link") |
| + good := filepath.Join(base, "good") |
| + if err := os.Mkdir(good, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(good, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ln := openFleetSocket(link, filepath.Join(link, "s"), logf); ln != nil { |
| + t.Fatal("listened through a symlinked directory") |
| + } |
| + sock := filepath.Join(good, "s") |
| + if err := os.WriteFile(sock, nil, 0o600); err != nil { // a stale file |
| + t.Fatal(err) |
| + } |
| + ln := openFleetSocket(good, sock, logf) |
| + if ln == nil { |
| + t.Fatalf("no listener in a good directory: %v", logs) |
| + } |
| + defer ln.Close() |
| + fi, err := os.Lstat(sock) |
| + if err != nil || fi.Mode().Type() != os.ModeSocket || fi.Mode().Perm() != 0o666 { |
| + t.Fatalf("socket %v %v", fi, err) |
| + } |
| + if reason := fleetSocketDirRefusal(mustStat(t, good), os.Geteuid()+1); !strings.Contains(reason, "owned by uid") { |
| + t.Fatalf("foreign owner: %q", reason) |
| + } |
| +} |
| + |
| +func mustStat(t *testing.T, p string) os.FileInfo { |
| + t.Helper() |
| + fi, err := os.Lstat(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fi |
| +} |
| + |
| +// failingListener fails its first Accept, as a broken fleet socket would. |
| +type failingListener struct{ net.Listener } |
| + |
| +func (failingListener) Accept() (net.Conn, error) { return nil, errors.New("fleet socket broke") } |
| + |
| +// TestConsoleStopFleetSocketLifecycle: a fleet listener that fails is |
| +// logged and the TCP listener keeps serving; a stop closes both listeners |
| +// and drains a request in flight on the fleet socket before serve returns. |
| +func TestConsoleStopFleetSocketLifecycle(t *testing.T) { |
| + t.Run("failure is not the console's exit", func(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Minute) |
| + base := shortTempDir(t) |
| + ul, err := net.Listen("unix", filepath.Join(base, "s")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.stop.also = []net.Listener{failingListener{ul}} |
| + logged := make(chan struct{}, 1) |
| + logf := r.stop.logf |
| + r.stop.logf = func(format string, a ...any) { |
| + logf(format, a...) |
| + if strings.Contains(fmt.Sprintf(format, a...), "fleet socket broke") { |
| + select { |
| + case logged <- struct{}{}: |
| + default: |
| + } |
| + } |
| + } |
| + addr, _, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") })) |
| + guard(t, logged, "the fleet listener's failure logged") |
| + resp, err := http.Get("http://" + addr + "/") |
| + if err != nil { |
| + t.Fatalf("TCP stopped with the fleet listener: %v", err) |
| + } |
| + resp.Body.Close() |
| + select { |
| + case code := <-result: |
| + t.Fatalf("serve returned %d after a fleet listener failure", code) |
| + default: |
| + } |
| + r.sigs <- syscall.SIGTERM |
| + if code := guard(t, result, "serve returning"); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + }) |
| + t.Run("stop closes and drains both", func(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Minute) |
| + base := shortTempDir(t) |
| + sock := filepath.Join(base, "s") |
| + ul, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.stop.also = []net.Listener{ul} |
| + entered, proceed := make(chan struct{}), make(chan struct{}) |
| + _, shutdownStarted, result := r.serve(fleetSocketOnly(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + close(entered) |
| + <-proceed |
| + io.WriteString(w, "done") |
| + }))) |
| + client := &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", sock) |
| + }}} |
| + got := make(chan string, 1) |
| + go func() { |
| + resp, err := client.Post("http://console-fleet/api/fleet/replicas/a/app/h/coordinator", "application/json", strings.NewReader("{}")) |
| + if err != nil { |
| + got <- err.Error() |
| + return |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + got <- string(b) |
| + }() |
| + guard(t, entered, "the fleet request entering the handler") |
| + r.sigs <- syscall.SIGTERM |
| + guard(t, shutdownStarted, "Shutdown starting") |
| + if c, err := net.Dial("unix", sock); err == nil { |
| + c.Close() |
| + t.Fatal("the fleet socket accepted after the signal") |
| + } |
| + close(proceed) |
| + if body := guard(t, got, "the fleet reply"); body != "done" { |
| + t.Fatalf("fleet request in flight: %q", body) |
| + } |
| + if code := guard(t, result, "serve returning"); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + }) |
| +} |
diff --git a/cmd/console/fleetsocket_unix.go b/cmd/console/fleetsocket_unix.go| new file mode 100644 |
| index 000000000..b229998a3 |
| --- /dev/null |
| +++ b/cmd/console/fleetsocket_unix.go |
| @@ -0,0 +1,70 @@ |
| +//go:build unix |
| + |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "net" |
| + "os" |
| + "syscall" |
| +) |
| + |
| +// openFleetSocket listens on socket when dir is this process's own runtime |
| +// directory: a real directory (not a symlink), owned by our effective uid, |
| +// writable by nobody else. Anything else is no fleet socket, logged once, |
| +// and the console serves TCP only, as it did before the socket existed. A |
| +// socket file left behind by an earlier run of this console is removed |
| +// first; only its owner could have put one there. |
| +func openFleetSocket(dir, socket string, logf func(string, ...any)) net.Listener { |
| + fi, err := os.Lstat(dir) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + logf("console: no fleet socket: %s does not exist (root's drop-in gives console.service that runtime directory); serving TCP only", dir) |
| + return nil |
| + } |
| + if err != nil { |
| + logf("console: no fleet socket: %v; serving TCP only", err) |
| + return nil |
| + } |
| + if reason := fleetSocketDirRefusal(fi, os.Geteuid()); reason != "" { |
| + logf("console: no fleet socket: %s %s; serving TCP only", dir, reason) |
| + return nil |
| + } |
| + if err := os.Remove(socket); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + logf("console: no fleet socket: removing a stale %s: %v; serving TCP only", socket, err) |
| + return nil |
| + } |
| + ln, err := net.Listen("unix", socket) |
| + if err != nil { |
| + logf("console: no fleet socket: %v; serving TCP only", err) |
| + return nil |
| + } |
| + // Connecting is not the threat (anyone on the box can reach the TCP |
| + // listener too); placing a socket here is, and only our user can. |
| + if err := os.Chmod(socket, 0o666); err != nil { |
| + ln.Close() |
| + logf("console: no fleet socket: chmod %s: %v; serving TCP only", socket, err) |
| + return nil |
| + } |
| + logf("console: fleet socket listening on %s", socket) |
| + return ln |
| +} |
| + |
| +// fleetSocketDirRefusal is why fi cannot hold the fleet socket, or "". |
| +func fleetSocketDirRefusal(fi fs.FileInfo, euid int) string { |
| + if !fi.IsDir() { |
| + return fmt.Sprintf("is not a directory (%v)", fi.Mode()) |
| + } |
| + if fi.Mode().Perm()&0o022 != 0 { |
| + return fmt.Sprintf("is writable by others (%v)", fi.Mode()) |
| + } |
| + st, ok := fi.Sys().(*syscall.Stat_t) |
| + if !ok { |
| + return "has no owner to check" |
| + } |
| + if int(st.Uid) != euid { |
| + return fmt.Sprintf("is owned by uid %d, not this console's %d", st.Uid, euid) |
| + } |
| + return "" |
| +} |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 5fcbabbbb..45fa1f8e3 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -172,6 +172,7 @@ import ( |
| "github.com/carlosframework/platform/internal/alerting" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/consolefleet" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| "github.com/carlosframework/platform/internal/domains" |
| @@ -978,6 +979,8 @@ func serve() { |
| // No Addr: the listener above is already open and Serve takes it |
| // directly, so Addr would be a field nothing reads. |
| httpSrv := console.NewHTTPServer(srv) |
| + // The fleet socket answers only the box doors (fleetsocket.go). |
| + httpSrv.Handler = fleetSocketOnly(httpSrv.Handler) |
| // AFTER the listener is open and the store has migrated (openConsoleDB |
| // and NewServer both ran above), so readiness means what it says. With |
| // console.service declared Type=notify, a build that dies before this |
| @@ -985,6 +988,9 @@ func serve() { |
| // starts the previous version, instead of stamping a build that never |
| // served (internal/release/adopt.go). |
| stop.attach(httpSrv) |
| + if fl := openFleetSocket(consolefleet.Dir, consolefleet.Socket, log.Printf); fl != nil { |
| + stop.also = append(stop.also, fl) |
| + } |
| handOff() |
| if err := NotifyReady(); err != nil { |
| log.Printf("console: notifying systemd of readiness: %v", err) |
diff --git a/cmd/console/stop.go b/cmd/console/stop.go| index f9afb3cc8..923bab937 100644 |
| --- a/cmd/console/stop.go |
| +++ b/cmd/console/stop.go |
| @@ -2,6 +2,7 @@ package main |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "net" |
| "net/http" |
| @@ -56,7 +57,11 @@ const ( |
| // without waiting for it, but a release request already sent to the store |
| // cannot be called back, so the lease may be released anyway. |
| type consoleStop struct { |
| - srv *http.Server // nil until serving: a stop before it has no requests to drain |
| + srv *http.Server // nil until serving: a stop before it has no requests to drain |
| + // also are listeners srv serves beside the main one (the fleet socket): |
| + // one Shutdown closes and drains them all, and a failure of one is |
| + // logged, never the console's exit. |
| + also []net.Listener |
| reqs *requests |
| cancelRequests context.CancelFunc |
| @@ -131,6 +136,13 @@ func (p *consoleStop) untilServing(sigs <-chan os.Signal, exit func(int)) (handO |
| // cut something (the log names it); 1 after a second signal or when Serve |
| // itself failed. |
| func (p *consoleStop) serve(ln net.Listener, sigs <-chan os.Signal) int { |
| + for _, l := range p.also { |
| + go func() { |
| + if err := p.srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| + p.logf("console: %s stopped serving: %v; the main listener carries on", l.Addr(), err) |
| + } |
| + }() |
| + } |
| served := make(chan error, 1) |
| go func() { served <- p.srv.Serve(ln) }() |
| code := 0 |
diff --git a/docs/superpowers/plans/2026-11-24-hub-console-socket.md b/docs/superpowers/plans/2026-11-24-hub-console-socket.md| index d0fddf0d9..48138ba0c 100644 |
| --- a/docs/superpowers/plans/2026-11-24-hub-console-socket.md |
| +++ b/docs/superpowers/plans/2026-11-24-hub-console-socket.md |
| @@ -33,8 +33,7 @@ Read it first. One slice, one branch: `console-addr-from-install`. |
| - Nothing here reads a route record or the registry to decide the socket. |
| - Tests first in every task. Linux-only tests run in Docker: |
| `docker run --rm -v <worktree>:/src -v $HOME/go/pkg/mod:/go/pkg/mod -w /src golang:1.26.10 go test ...`. |
| - Leave `GOCACHE` at its default (AGENTS.md, Build & test); a session's |
| - own environment may point it elsewhere for local runs. |
| + Go environment as AGENTS.md, Build & test, says. |
| - Every Go change: `gofmt`, `go vet`, `make code-health` before pushing. |
| ## Tasks |
| @@ -69,7 +68,8 @@ Files: `internal/caps/caps.go`, `internal/caps/converge.go`, new |
| names, behind `ValidCapabilities`), `internal/consolefleet/consolefleet.go`, |
| `internal/demobuild/gvisor.go`, the three `carlos-runsc` units and |
| `infra/devbox/carlos-devbox.service`; readers |
| - `internal/caps/converge.go` and `internal/instancectl/gvisorunit.go`; |
| + `internal/caps/converge.go`, `internal/instancectl/gvisorunit.go` and |
| + `internal/host/consolefleet.go` (Task 3's step); |
| - a file not listed, or a listed file whose count changed, fails, naming |
| the file: a second writer inside an allowlisted file fails too (plan |
| review R1 P2-3); |
| @@ -142,12 +142,14 @@ Files: `internal/edge/replicaconsole.go`, new |
| - Last call: one `atomic.Pointer[ReplicaConsoleCall]` on the edge |
| (`Source`, `Result`, `At`), set after each box call from a status- |
| recording wrapper; exported `(*Edge).LastReplicaConsoleCall()`. |
| -- Production record read: `rootstate.OpenTrustedFile` + |
| - `rootstate.CheckPublicConfig` + `consolefleet.DecodeRecord`. |
| -- Production record read: `rootstate.Open(consolefleet.StatusDir, false, |
| - true)` and `Read(StatusFile)` (the store checks the chain and the file: |
| - root-owned, not group- or other-writable, regular), then |
| - `consolefleet.DecodeRecord`. |
| +- Production record read, as spec §6: `rootstate.OpenTrustedFile` on |
| + `StatusDir/StatusFile` (chain and file root-owned, not group- or |
| + other-writable, regular) plus `rootstate.CheckPublicConfig` (root:root, |
| + exactly 0644, one link), then `consolefleet.DecodeRecord`. Root's store |
| + writes public records root:root 0644. |
| +- `(*Edge).ConsoleFleetSocketReady() error` exposes the live readiness |
| + check (record, directory, socket) for the heartbeat, independent of |
| + which source served the last call. |
| - Tests (real unix listener in `t.TempDir()`): env wins over a ready |
| socket; record missing, malformed, `exclusive:false` each fall to the |
| route scan; dir symlink, dir 0777, socket a regular file each fall to |
| @@ -158,7 +160,9 @@ Files: `internal/edge/replicaconsole.go`, new |
| route upstream receives nothing; last call recorded for `ok`, `401`, |
| `500`, `502` and the route scan's `503`, with source and time; "no call |
| yet" is nil; an env call that succeeds while the record says |
| - `exclusive:false` records source `env`, result `ok`. |
| + `exclusive:false` records source `env`, result `ok`; with root's record |
| + exclusive and an env call succeeding, `ConsoleFleetSocketReady` is nil |
| + with the socket present and an error with it absent. |
| - A Linux-only test of the production reader, run as root in Docker: |
| a record owned by another uid, and one with mode 0666, are refused, so |
| the edge falls to the route scan (plan review R1 P2-5). |
| @@ -204,9 +208,13 @@ Files: `internal/status/snapshot.go`, `internal/host/agent.go` (probe), |
| before copy review (plan review R1 P2-7). |
| 2. **Copy review** of those strings and any new log lines by a Luna pass |
| (`codex exec -s read-only`), in that rendered layout, recorded in the |
| - same note. |
| -3. Build: `status.ConsoleFleet{Record *consolefleet.Record; Source, |
| - Result string; At time.Time}` on `Probes` and `BoxMetrics` |
| + same note. The presentation checks AGENTS.md asks for are done on the |
| + real output first: a narrow terminal (about 48 columns, the 390 px |
| + case) and a wide one, on a light and a dark background, colour and no |
| + colour. |
| +3. Build: `status.ConsoleFleet{Record *consolefleet.Record; SocketReady |
| + bool; SocketReason string; Source, Result string; At time.Time}` on |
| + `Probes` and `BoxMetrics` |
| (`console_fleet`, omitempty, private like `named_units`); the agent |
| fills it from root's record and `LastReplicaConsoleCall()`; the API row |
| adds `console_fleet`; the CLI decodes and prints it. Tests at each hop |
| @@ -226,7 +234,7 @@ Files: `internal/status/snapshot.go`, `internal/host/agent.go` (probe), |
| root step, edge, status, shared package); `make census-propose |
| NAME=console-addr-from-install CLAIMS=<file>`; add any new census file |
| to `scripts/gitleaks-gate/notscanned.go` if gitleaks reports digests. |
| -2. Per-task Codex reviews (Tasks 1, 3, 4) under the stopping rules, with |
| +2. Per-task Codex reviews (Tasks 1, 3, 4 and 5) under the stopping rules, with |
| briefs and findings beside this plan. |
| 3. Codex census review of the card; verdict recorded on #280. |
| 4. One whole-branch review by Fable. |
| @@ -250,5 +258,8 @@ are covered by the whole-branch review. |
| Round 1 (`CODEX-FINDINGS-hub-console-socket-plan-R1.md`): NOT READY, P1-1 |
| (the guard's allowlist omitted existing sites) and P1-2 (claimant not fail |
| -closed on a drop-in read error), with P2-3 to P2-8. All applied above; |
| -P2-8's cache line now follows AGENTS.md. |
| +closed on a drop-in read error), with P2-3 to P2-8. All applied above. |
| +Round 2 (`CODEX-FINDINGS-hub-console-socket-plan-R2.md`): READY AFTER |
| +FIXES, no P1. Its six P2s are applied above (one reader contract, a |
| +readiness field, Task 5 in Task 8's list, the presentation checks, the |
| +cache line, the reader inventory). The plan review is closed. |
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R2.md b/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R2.md| new file mode 100644 |
| index 000000000..50abfc44a |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R2.md |
| @@ -0,0 +1,78 @@ |
| +- R1 P1-1 — **Resolved:** existing readers and property-map values are accommodated. A remaining plan/code inventory mismatch is P2 below. |
| +- R1 P1-2 — **Resolved:** the plan requires a separate claimant scan that refuses every non-absence read error. |
| +- R1 P2-3 — **Resolved:** site counts, literal concatenation and scanner fixtures are specified; the remaining limitation is documented. |
| +- R1 P2-4 — **Partly resolved:** call outcomes are preserved, but the proposed heartbeat cannot represent all socket-readiness reasons. |
| +- R1 P2-5 — **Resolved:** production ownership/mode tests and zero-delivery assertions on dial failure are included. |
| +- R1 P2-6 — **Partly resolved:** lifecycle tests and the review classification are added; Task 8’s review instructions still omit Task 5. |
| +- R1 P2-7 — **Partly resolved:** rendered output precedes copy review, but the required narrow/light/dark presentation checks remain absent. |
| +- R1 P2-8 — **Partly resolved:** post-merge checks are added; the cache exception still contradicts AGENTS.md. |
| + |
| +Reviewed the plan at `db6dee85c028c0138dffa513cff94b911688331a`. The checkout’s later commit changes only the review brief. Uncommitted edge changes appeared during review and are excluded. No files edited, subagents spawned or tests run. |
| + |
| +No P1 findings. |
| + |
| +1. **P2 — Task 4: two incompatible production-reader contracts.** |
| + |
| + **Evidence:** [plan:145](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:145) specifies `OpenTrustedFile` plus `CheckPublicConfig`; line 147 instead specifies `Store.Read`. These are not equivalent: `internal/rootstate/file_linux.go:142` requires root uid **and gid**, exact mode `0644` and one link. `internal/rootstate/state_linux.go:41` and `:139` check ownership, type, writable bits and link count, without the exact group/mode requirement. Spec §6, line 190, explicitly chooses the former. |
| + |
| + **Failure scenario:** A readable root-owned record with a non-root group or mode `0444` passes the second implementation but fails the specified one. Implementers can follow the plan and produce different acceptance rules. |
| + |
| + **Fix:** Retain one production-reader instruction matching §6, and test its exact permission contract. |
| + |
| + **Fault family:** Root-record acceptance must match the approved authority contract. |
| + |
| +2. **P2 — Task 6: socket eligibility has no complete reporting path.** *Carries R1 P2-4.* |
| + |
| + **Evidence:** [plan:195](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:195) promises socket eligibility and its reason independently of the observed call. Lines 208–212 carry only root’s record and the last call’s source/result/time. Task 4’s live directory/socket checks, lines 136–141, only expose their reasons through logging. |
| + |
| + **Failure scenario:** Root records `exclusive:true`, but the directory or socket is absent. An env call succeeds. The heartbeat contains neither the live readiness failure nor its reason, so the CLI cannot produce the promised independent status. Conversely, choosing env does not establish that the socket is unready. |
| + |
| + **Fix:** Specify a readiness probe and an explicit readiness/reason field carried through heartbeat, API and CLI. Test a successful env call with both a ready socket and an absent socket while root’s record remains exclusive. |
| + |
| + **Fault family:** Report observed delivery independently of socket eligibility. |
| + |
| +3. **P2 — Task 8: the executable review list still excludes termination work.** *Carries R1 P2-6.* |
| + |
| + **Evidence:** [plan:229](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:229) schedules per-task reviews only for Tasks 1, 3 and 4. Lines 245–247 correctly classify Task 5 as requiring its own termination review. `cmd/console/stop.go:133–147` is the existing service-exit path that Task 5 changes. |
| + |
| + **Failure scenario:** Following Task 8 completes every enumerated review without the required review of listener failure and shutdown behavior. |
| + |
| + **Fix:** Include Task 5 explicitly in Task 8’s review list. |
| + |
| + **Fault family:** Console service lifetime and shutdown review coverage. |
| + |
| +4. **P2 — Task 6: the UX pass still omits required presentation conditions.** *Carries R1 P2-7.* |
| + |
| + **Evidence:** [plan:201](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:201) specifies 80/160 columns and colour/no-colour. `AGENTS.md:422–427` requires the kit pass at 390 px and desktop width, light and dark, before copy review. |
| + |
| + **Failure scenario:** Long status suffixes and indented reasons receive copy approval without checking the required narrow presentation or colour contrast on both backgrounds. |
| + |
| + **Fix:** Add those presentation checks before copy review, using the actual CLI output in the prescribed presentation. |
| + |
| + **Fault family:** Review copy in its actual presentation. |
| + |
| +5. **P2 — Global constraints: the cache prohibition still has an unauthorized exception.** *Carries R1 P2-8.* |
| + |
| + **Evidence:** [plan:36](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:36) says to retain default `GOCACHE`, then allows a session environment to point it elsewhere. `AGENTS.md:343–347` prohibits pointing it anywhere else. |
| + |
| + **Failure scenario:** An inherited override remains permitted by the plan despite violating machine policy. |
| + |
| + **Fix:** Remove the exception and retain the repository’s applicable Go environment instructions. |
| + |
| + **Fault family:** Repository execution and completion contract. |
| + |
| +6. **P2 — Task 1: the plan’s reader inventory omits its own root step.** |
| + |
| + **Evidence:** [plan:71](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:71) lists only `caps/converge.go` and `instancectl/gvisorunit.go` as readers. At the reviewed commit, `internal/host/consolefleet.go:44`, `:181` and `:184` contain matching literals; `internal/caps/runtimedir_guard_test.go:47` already correctly includes that file. |
| + |
| + **Failure scenario:** Reconstructing the allowlist from the plan removes a necessary reader entry and fails the guard. |
| + |
| + **Fix:** Synchronize the plan with the existing root-step reader entry and its scanner count. This is a documentation discrepancy, not a currently failing implementation. |
| + |
| + **Fault family:** Runtime-directory writer inventory correctness. |
| + |
| +The shared validation gate covers ship, adopt, converge and render. The adopt insertion point covers full and config-only passes. The planned shared-server shutdown and Unix `LocalAddrContextKey` discrimination are supported by the existing lifecycle and Go HTTP implementation. No missing-`--all` finding applies: systemctl explicitly prints empty properties requested through `-p`. [systemd source](https://github.com/systemd/systemd/blob/v257/src/systemctl/systemctl.c#L590-L610) |
| + |
| +This round has no P1. Apply the P2 fixes without reopening the plan review; retain the required census and changed-security/termination checks. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 155290879..9e62df533 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -119,9 +119,18 @@ type Edge struct { |
| // replicaConsole forwards fleet replica calls to the operator-configured |
| // console endpoint (replicaConsoleAddrEnv); nil uses the accountless |
| // console.service route. Set before serving. |
| - replicaConsole http.Handler |
| - haIngress atomic.Pointer[haIngressLookup] |
| - haIngressBlocked atomic.Pointer[map[string]bool] |
| + replicaConsole http.Handler |
| + // consoleFleet and consoleFleetProxy are the console's fleet socket |
| + // (hub console spec §6), used when replicaConsole is nil and root's |
| + // record says the console holds its directory alone. consoleFleetReason |
| + // is the last reason it was not used, so each is logged once; |
| + // lastReplicaCall is the last box call for the heartbeat. |
| + consoleFleet consoleFleetSource |
| + consoleFleetProxy http.Handler |
| + consoleFleetReason atomic.Pointer[string] |
| + lastReplicaCall atomic.Pointer[ReplicaConsoleCall] |
| + haIngress atomic.Pointer[haIngressLookup] |
| + haIngressBlocked atomic.Pointer[map[string]bool] |
| // ReplicaProbe is configured before the first syncReplicaProbes call. |
| // Nil uses the private box landing over the existing tunnel transport. |
| ReplicaProbe func(context.Context, string, string) (replicas.Copy, error) |
| @@ -666,6 +675,7 @@ func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, erro |
| held: newHeldSet(DefaultHeldConfig)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| + e.withConsoleFleet(productionConsoleFleet()) |
| e.guardMint = e.mintRef |
| // Generations (zero-downtime spec §7.2), before the startup Reload so |
| // its first table build already proxies through them. |
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go| index f69d88821..9c1003723 100644 |
| --- a/internal/edge/replicaconsole.go |
| +++ b/internal/edge/replicaconsole.go |
| @@ -1,15 +1,24 @@ |
| package edge |
| import ( |
| + "context" |
| + "errors" |
| "fmt" |
| + "io" |
| + "io/fs" |
| + "log" |
| "net" |
| "net/http" |
| "net/http/httputil" |
| "net/netip" |
| + "os" |
| + "path/filepath" |
| "strconv" |
| "strings" |
| "time" |
| + "github.com/carlosframework/platform/internal/consolefleet" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -61,15 +70,29 @@ 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) |
| +} |
| + |
| +// newReplicaConsoleSocketProxy is newReplicaConsoleProxy for the console's |
| +// fleet socket (consolefleet.Socket): every connection dials that one unix |
| +// path, whatever the request names. |
| +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) |
| + }) |
| +} |
| + |
| +func replicaConsoleProxy(host string, dial func(ctx context.Context, network, addr string) (net.Conn, error)) http.Handler { |
| return &httputil.ReverseProxy{ |
| Rewrite: func(pr *httputil.ProxyRequest) { |
| setForwarded(pr) |
| pr.Out.URL.Scheme = "http" |
| - pr.Out.URL.Host = addr |
| + pr.Out.URL.Host = host |
| pr.Out.Host = pr.In.Host |
| }, |
| Transport: &http.Transport{ |
| - DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, |
| + DialContext: dial, |
| MaxIdleConns: 8, |
| IdleConnTimeout: 90 * time.Second, |
| ResponseHeaderTimeout: 30 * time.Second, |
| @@ -84,19 +107,180 @@ func newReplicaConsoleProxy(addr string) http.Handler { |
| } |
| } |
| +// The edge's sources for a box call, as LastReplicaConsoleCall reports them. |
| +const ( |
| + ReplicaConsoleSourceEnv = "env" |
| + ReplicaConsoleSourceSocket = "socket" |
| + ReplicaConsoleSourceRouteScan = "route-scan" |
| +) |
| + |
| +// ReplicaConsoleCall is the last box call the edge handed on: the source it |
| +// chose, its result ("ok" for a 2xx, otherwise the status code it answered, |
| +// the console's or its own) and when. |
| +type ReplicaConsoleCall struct { |
| + Source string |
| + Result string |
| + At time.Time |
| +} |
| + |
| +// LastReplicaConsoleCall is the edge's last box call, nil before the first. |
| +func (e *Edge) LastReplicaConsoleCall() *ReplicaConsoleCall { return e.lastReplicaCall.Load() } |
| + |
| +// 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() } |
| + |
| +// 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 |
| +// §6). Production values come from productionConsoleFleet; a test sets its |
| +// own with withConsoleFleet. |
| +type consoleFleetSource struct { |
| + record func() (consolefleet.Record, error) |
| + dir string |
| + socket string |
| +} |
| + |
| +func productionConsoleFleet() consoleFleetSource { |
| + return consoleFleetSource{record: readConsoleFleetRecord, dir: consolefleet.Dir, socket: consolefleet.Socket} |
| +} |
| + |
| +// readConsoleFleetRecord reads root's record as spec §6 says: through |
| +// rootstate.OpenTrustedFile (every directory from / and the file |
| +// root-owned, not group- or other-writable, the file regular) and |
| +// rootstate.CheckPublicConfig (root:root, exactly 0644, one link), at most |
| +// consolefleet.MaxRecord. Nothing but root can write a record this accepts. |
| +func readConsoleFleetRecord() (consolefleet.Record, error) { |
| + return readConsoleFleetRecordIn(consolefleet.StatusDir) |
| +} |
| + |
| +func readConsoleFleetRecordIn(dir string) (consolefleet.Record, error) { |
| + f, err := rootstate.OpenTrustedFile(filepath.Join(dir, consolefleet.StatusFile)) |
| + if err != nil { |
| + return consolefleet.Record{}, err |
| + } |
| + defer f.Close() |
| + if err := rootstate.CheckPublicConfig(f); err != nil { |
| + return consolefleet.Record{}, err |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(f, consolefleet.MaxRecord+1)) |
| + if err != nil { |
| + return consolefleet.Record{}, err |
| + } |
| + return consolefleet.DecodeRecord(raw) |
| +} |
| + |
| +// ready is nil 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 { |
| + if c.record == nil { |
| + return errors.New("no console fleet source") |
| + } |
| + rec, err := c.record() |
| + if err != nil { |
| + return 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) |
| + } |
| + fi, err := os.Lstat(c.dir) |
| + if err != nil { |
| + return 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()) |
| + } |
| + si, err := os.Lstat(c.socket) |
| + if err != nil { |
| + return err |
| + } |
| + if si.Mode().Type() != fs.ModeSocket { |
| + return fmt.Errorf("%s is not a socket (%v)", c.socket, si.Mode()) |
| + } |
| + return nil |
| +} |
| + |
| +// withConsoleFleet sets the edge's socket source and its proxy together. |
| +func (e *Edge) withConsoleFleet(c consoleFleetSource) { |
| + e.consoleFleet = c |
| + e.consoleFleetProxy = newReplicaConsoleSocketProxy(c.socket) |
| +} |
| + |
| +// noteConsoleFleet logs why the socket was not used, once per distinct |
| +// reason, so a hub that answers from the route scan says why without a |
| +// line per call. |
| +func (e *Edge) noteConsoleFleet(err error) { |
| + reason := err.Error() |
| + if prev := e.consoleFleetReason.Swap(&reason); prev == nil || *prev != reason { |
| + log.Printf("edge: fleet replica calls do not use the console socket: %v", err) |
| + } |
| +} |
| + |
| +// replicaCallStatus records the status a box call was answered with. |
| +type replicaCallStatus struct { |
| + http.ResponseWriter |
| + code int |
| +} |
| + |
| +func (w *replicaCallStatus) WriteHeader(code int) { |
| + if w.code == 0 { |
| + w.code = code |
| + } |
| + w.ResponseWriter.WriteHeader(code) |
| +} |
| + |
| +func (w *replicaCallStatus) Write(b []byte) (int, error) { |
| + if w.code == 0 { |
| + w.code = http.StatusOK |
| + } |
| + return w.ResponseWriter.Write(b) |
| +} |
| + |
| +func (w *replicaCallStatus) result() string { |
| + code := w.code |
| + if code == 0 { |
| + code = http.StatusOK |
| + } |
| + if code >= 200 && code < 300 { |
| + return "ok" |
| + } |
| + return strconv.Itoa(code) |
| +} |
| + |
| // serveReplicaConsole hands a box's replica call to the console. Only POSTs |
| // on the reserved tunnel host enter here; other methods keep the hub's 404. |
| -// Authentication remains the console's fleetIdentityOK. |
| -// |
| -// With replicaConsoleAddrEnv set, the call goes to that endpoint and route |
| -// data plays no part. Unset, the console is the one route for app console |
| -// with unit console.service and no account (the platform console's shape), |
| -// on a loopback upstream or a socket, not an alias, regional, via a tunnel |
| -// or activator-owned, and its proxy (with its version header) is reused. |
| +// Authentication remains the console's fleetIdentityOK. It records the |
| +// source and the result for LastReplicaConsoleCall. |
| func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) { |
| + rec := &replicaCallStatus{ResponseWriter: w} |
| + source := e.routeReplicaConsole(rec, r) |
| + e.lastReplicaCall.Store(&ReplicaConsoleCall{Source: source, Result: rec.result(), At: time.Now()}) |
| +} |
| + |
| +// routeReplicaConsole picks the console, in order (hub console spec §6): |
| +// |
| +// 1. replicaConsoleAddrEnv set: that endpoint, and route data plays no |
| +// part. |
| +// 2. The console's fleet socket, when consoleFleetSource.ready: root's |
| +// record and the directory's ownership decide, never route data. |
| +// 3. The route scan (to be deleted the release after the socket ships, |
| +// Paul 2026-11-24): the one route for app console with unit |
| +// console.service and no account (the platform console's shape), on a |
| +// loopback upstream or a socket, not an alias, regional, via a tunnel |
| +// or activator-owned, and its proxy (with its version header) is |
| +// reused. |
| +func (e *Edge) routeReplicaConsole(w http.ResponseWriter, r *http.Request) string { |
| if e.replicaConsole != nil { |
| e.replicaConsole.ServeHTTP(w, e.withForwardKey(r)) |
| - return |
| + return ReplicaConsoleSourceEnv |
| + } |
| + if err := e.consoleFleet.ready(); err == nil { |
| + e.consoleFleetProxy.ServeHTTP(w, e.withForwardKey(r)) |
| + return ReplicaConsoleSourceSocket |
| + } else { |
| + e.noteConsoleFleet(err) |
| } |
| var console http.Handler |
| for host, up := range e.table().hosts { |
| @@ -119,13 +303,14 @@ func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) { |
| } |
| if console != nil { |
| UnavailableHeader(w, "replica-console-ambiguous", 2) |
| - return |
| + return ReplicaConsoleSourceRouteScan |
| } |
| console = up.proxy |
| } |
| if console == nil { |
| UnavailableHeader(w, "replica-console-missing", 2) |
| - return |
| + return ReplicaConsoleSourceRouteScan |
| } |
| console.ServeHTTP(w, e.withForwardKey(r)) |
| + return ReplicaConsoleSourceRouteScan |
| } |
diff --git a/internal/edge/replicaconsole_socket_test.go b/internal/edge/replicaconsole_socket_test.go| new file mode 100644 |
| index 000000000..2a49f68c3 |
| --- /dev/null |
| +++ b/internal/edge/replicaconsole_socket_test.go |
| @@ -0,0 +1,318 @@ |
| +package edge |
| + |
| +import ( |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/consolefleet" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// fleetSocketFixture is a console listening on a unix socket in a |
| +// directory shaped like /run/carlos-console, and the edge wired to it. |
| +type fleetSocketFixture struct { |
| + dir, socket string |
| + hits atomic.Int32 |
| + code atomic.Int32 // the console's answer; 0 = 200 |
| + record atomic.Pointer[consolefleet.Record] |
| + recordErr atomic.Pointer[error] |
| + srv *http.Server |
| + ln net.Listener |
| +} |
| + |
| +func newFleetSocketFixture(t *testing.T) *fleetSocketFixture { |
| + t.Helper() |
| + f := &fleetSocketFixture{} |
| + f.dir = filepath.Join(t.TempDir(), "carlos-console") |
| + if err := os.Mkdir(f.dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.socket = filepath.Join(f.dir, "fleet.sock") |
| + ln, err := net.Listen("unix", f.socket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Closing the server leaves the socket file, as a console that dies |
| + // without unlinking it would: the edge then dials a dead path. |
| + ln.(*net.UnixListener).SetUnlinkOnClose(false) |
| + f.ln = ln |
| + f.srv = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.hits.Add(1) |
| + if r.Header.Get("Authorization") != "Bearer fleet-token" || r.URL.Path != "/api/fleet/replicas/a/app/h/coordinator" { |
| + t.Errorf("socket console got %s %v", r.URL, r.Header) |
| + } |
| + if c := f.code.Load(); c != 0 { |
| + w.WriteHeader(int(c)) |
| + } |
| + _, _ = io.WriteString(w, "socket") |
| + })} |
| + go func() { _ = f.srv.Serve(ln) }() |
| + t.Cleanup(func() { _ = f.srv.Close() }) |
| + f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: true}) |
| + return f |
| +} |
| + |
| +func (f *fleetSocketFixture) source() consoleFleetSource { |
| + return consoleFleetSource{ |
| + record: func() (consolefleet.Record, error) { |
| + if err := f.recordErr.Load(); err != nil { |
| + return consolefleet.Record{}, *err |
| + } |
| + return *f.record.Load(), nil |
| + }, |
| + dir: f.dir, |
| + socket: f.socket, |
| + } |
| +} |
| + |
| +// socketEdge is an edge with tunnels armed, the fixture's socket wired in, |
| +// and a live system console route the route scan would pick, counting its |
| +// hits, so every test can show where a token did NOT go. |
| +func socketEdge(t *testing.T, f *fleetSocketFixture) (*Edge, *atomic.Int32) { |
| + t.Helper() |
| + var routeHits atomic.Int32 |
| + routeConsole := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + routeHits.Add(1) |
| + _, _ = io.WriteString(w, "route") |
| + })) |
| + t.Cleanup(routeConsole.Close) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "console.test", App: "console", Unit: "console.service", Kind: "instance", Addr: routeConsole.Listener.Addr().String(), Status: "ready", Version: "route-version"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.withConsoleFleet(f.source()) |
| + e.EnableTunnels(NewTunnelHub("tunnel.test", nil)) |
| + return e, &routeHits |
| +} |
| + |
| +func postBoxCall(t *testing.T, e *Edge) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest("POST", "https://tunnel.test/api/fleet/replicas/a/app/h/coordinator", strings.NewReader(`{"op":"acquire"}`)) |
| + req.Header.Set("Authorization", "Bearer fleet-token") |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, req) |
| + return w |
| +} |
| + |
| +// TestReplicaConsoleSocketSelected: with no operator endpoint, root's |
| +// exclusive record and the console's socket take the call, with the hub's |
| +// version header, and the route scan's console gets nothing. |
| +func TestReplicaConsoleSocketSelected(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, routeHits := socketEdge(t, f) |
| + if e.LastReplicaConsoleCall() != nil { |
| + t.Fatal("a call recorded before any call") |
| + } |
| + w := postBoxCall(t, e) |
| + if w.Code != 200 || w.Body.String() != "socket" || f.hits.Load() != 1 || routeHits.Load() != 0 { |
| + t.Fatalf("%d %q socket %d route %d", w.Code, w.Body.String(), f.hits.Load(), routeHits.Load()) |
| + } |
| + if v := w.Header().Get("X-Carlos-Version"); v == "" || v == "route-version" { |
| + t.Fatalf("version header %q, want the hub's build", v) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceSocket || c.Result != "ok" || c.At.IsZero() { |
| + t.Fatalf("last call %+v", c) |
| + } |
| + if err := e.ConsoleFleetSocketReady(); err != nil { |
| + t.Fatalf("ready: %v", err) |
| + } |
| +} |
| + |
| +// TestReplicaConsoleSocketRefusals: every reason the socket is not used |
| +// falls to today's route scan, and the socket gets nothing. |
| +func TestReplicaConsoleSocketRefusals(t *testing.T) { |
| + for name, mutate := range map[string]func(t *testing.T, f *fleetSocketFixture){ |
| + "record missing": func(t *testing.T, f *fleetSocketFixture) { |
| + err := error(os.ErrNotExist) |
| + f.recordErr.Store(&err) |
| + }, |
| + "record malformed": func(t *testing.T, f *fleetSocketFixture) { |
| + _, err := consolefleet.DecodeRecord([]byte(`{"schema":1,"outcome":"unchanged","exclusive":true,"addr":"x"}`)) |
| + f.recordErr.Store(&err) |
| + }, |
| + "not exclusive": func(t *testing.T, f *fleetSocketFixture) { |
| + f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Reason: "a capability drop-in for x also claims it"}) |
| + }, |
| + "directory a symlink": func(t *testing.T, f *fleetSocketFixture) { |
| + real := f.dir + "-real" |
| + if err := os.Rename(f.dir, real); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(real, f.dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "directory writable by others": func(t *testing.T, f *fleetSocketFixture) { |
| + if err := os.Chmod(f.dir, 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "socket a regular file": func(t *testing.T, f *fleetSocketFixture) { |
| + _ = f.ln.Close() |
| + _ = os.Remove(f.socket) |
| + if err := os.WriteFile(f.socket, nil, 0o666); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "no directory": func(t *testing.T, f *fleetSocketFixture) { |
| + _ = f.ln.Close() |
| + if err := os.RemoveAll(f.dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, routeHits := socketEdge(t, f) |
| + mutate(t, f) |
| + w := postBoxCall(t, e) |
| + if w.Code != 200 || w.Body.String() != "route" || f.hits.Load() != 0 || routeHits.Load() != 1 { |
| + t.Fatalf("%d %q socket %d route %d", w.Code, w.Body.String(), f.hits.Load(), routeHits.Load()) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceRouteScan || c.Result != "ok" { |
| + t.Fatalf("last call %+v", c) |
| + } |
| + if e.ConsoleFleetSocketReady() == nil { |
| + t.Fatal("ready reported nil") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestReplicaConsoleSocketDialFailure: the socket chosen, then gone before |
| +// the dial (the console stopping): 502 with no version header, which the |
| +// box reads as the console unreachable, and no other upstream stands in. |
| +func TestReplicaConsoleSocketDialFailure(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, routeHits := socketEdge(t, f) |
| + _ = f.srv.Close() // closes the listener; the socket file stays, refusing |
| + w := postBoxCall(t, e) |
| + if w.Code != http.StatusBadGateway || w.Header().Get("X-Carlos-Version") != "" || routeHits.Load() != 0 || f.hits.Load() != 0 { |
| + t.Fatalf("%d version %q route %d socket %d", w.Code, w.Header().Get("X-Carlos-Version"), routeHits.Load(), f.hits.Load()) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceSocket || c.Result != "502" { |
| + t.Fatalf("last call %+v", c) |
| + } |
| +} |
| + |
| +// TestReplicaConsoleSocketResults: the console's own refusals are recorded |
| +// as the status it answered. |
| +func TestReplicaConsoleSocketResults(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, _ := socketEdge(t, f) |
| + for _, code := range []int{401, 500} { |
| + f.code.Store(int32(code)) |
| + if w := postBoxCall(t, e); w.Code != code { |
| + t.Fatalf("answered %d, want %d", w.Code, code) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceSocket || c.Result != strconv.Itoa(code) { |
| + t.Fatalf("last call %+v, want %d", c, code) |
| + } |
| + } |
| +} |
| + |
| +// TestReplicaConsoleEnvWinsOverSocket: the operator's endpoint takes the |
| +// call even with the socket ready, and is recorded as env; a socket that is |
| +// not ready changes nothing about an env call. |
| +func TestReplicaConsoleEnvWinsOverSocket(t *testing.T) { |
| + var envHits atomic.Int32 |
| + envConsole := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + envHits.Add(1) |
| + _, _ = io.WriteString(w, "env") |
| + })) |
| + defer envConsole.Close() |
| + f := newFleetSocketFixture(t) |
| + e, routeHits := socketEdge(t, f) |
| + addr, err := parseReplicaConsoleAddr(envConsole.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + WithReplicaConsoleAddr(addr)(e) |
| + for _, exclusive := range []bool{true, false} { |
| + f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: exclusive}) |
| + w := postBoxCall(t, e) |
| + if w.Code != 200 || w.Body.String() != "env" || f.hits.Load() != 0 || routeHits.Load() != 0 { |
| + t.Fatalf("exclusive=%v: %d %q socket %d route %d", exclusive, w.Code, w.Body.String(), f.hits.Load(), routeHits.Load()) |
| + } |
| + if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceEnv || c.Result != "ok" { |
| + t.Fatalf("last call %+v", c) |
| + } |
| + } |
| + if envHits.Load() != 2 { |
| + t.Fatalf("env hits %d", envHits.Load()) |
| + } |
| +} |
| + |
| +// TestReplicaConsoleSocketIgnoresRouteRows: a record writer's rows (an |
| +// account console.service row at another upstream) change nothing while |
| +// the socket is used. |
| +func TestReplicaConsoleSocketIgnoresRouteRows(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, routeHits := socketEdge(t, f) |
| + var injectedHits atomic.Int32 |
| + injected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { injectedHits.Add(1) })) |
| + defer injected.Close() |
| + if err := e.reg.Upsert(registry.Route{Host: "injected.test", Account: "x", App: "console", Unit: "console.service", Kind: "instance", Addr: injected.Listener.Addr().String(), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := postBoxCall(t, e); w.Body.String() != "socket" || injectedHits.Load() != 0 || routeHits.Load() != 0 { |
| + t.Fatalf("%q injected %d route %d", w.Body.String(), injectedHits.Load(), routeHits.Load()) |
| + } |
| +} |
| + |
| +// TestReplicaConsoleProductionRecordReader: the edge's production reader is |
| +// rootstate's trusted public store, so a record in a directory anyone but |
| +// root could write (any test temp directory) is refused, however well |
| +// formed. rootstate's own tests cover each refusal (ownership, modes, |
| +// links); this pins that the edge does not read the record any other way. |
| +func TestReplicaConsoleProductionRecordReader(t *testing.T) { |
| + dir := t.TempDir() |
| + if err := os.WriteFile(filepath.Join(dir, consolefleet.StatusFile), []byte(`{"schema":1,"outcome":"unchanged","exclusive":true}`), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := readConsoleFleetRecordIn(dir); err == nil { |
| + t.Fatal("a record in an untrusted directory was accepted") |
| + } |
| + if _, err := readConsoleFleetRecordIn(filepath.Join(dir, "missing")); err == nil { |
| + t.Fatal("a missing store was accepted") |
| + } |
| + if src := productionConsoleFleet(); src.dir != consolefleet.Dir || src.socket != consolefleet.Socket { |
| + t.Fatalf("production source %+v", src) |
| + } |
| +} |
| + |
| +// TestConsoleFleetSocketReadyIndependentOfSource: with root's record |
| +// exclusive and an env call succeeding, readiness reports the socket as it |
| +// is, present or absent; the source that served the call says nothing |
| +// about it. |
| +func TestConsoleFleetSocketReadyIndependentOfSource(t *testing.T) { |
| + f := newFleetSocketFixture(t) |
| + e, _ := socketEdge(t, f) |
| + WithReplicaConsoleAddr("127.0.0.1:1")(e) |
| + if err := e.ConsoleFleetSocketReady(); err != nil { |
| + t.Fatalf("socket present: %v", err) |
| + } |
| + _ = f.srv.Close() |
| + if err := os.Remove(f.socket); err != nil { |
| + t.Fatal(err) |
| + } |
| + if e.ConsoleFleetSocketReady() == nil { |
| + t.Fatal("socket absent, reported ready") |
| + } |
| +} |