carlos / platform Public

host, edge, caps, console: task review R1 fixes (console uid ownership, pending reload, list names, 1xx, OPTIONS *)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 65e1bf21379b9904d3741666dd605cd42c3a8870 parent b5f1881
18 files changed, +548 −92
  • cmd/console/fleetsocket.go +23 −1
  • cmd/console/fleetsocket_test.go +56 −0
  • cmd/console/main.go +1 −1
  • docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T1-R1.md +15 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T3-R1.md +35 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T4-R1.md +22 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T5-R1.md +13 −0
  • internal/caps/runtimedir_guard_test.go +16 −2
  • internal/consolefleet/consolefleet.go +16 −8
  • internal/edge/replicaconsole.go +30 −2
  • internal/edge/replicaconsole_owner_other.go +8 −0
  • internal/edge/replicaconsole_owner_unix.go +17 −0
  • internal/edge/replicaconsole_record_rootrunner_linux_test.go +66 −0
  • internal/edge/replicaconsole_socket_test.go +41 −5
  • internal/host/consolefleet.go +77 −36
  • internal/host/consolefleet_owner_other.go +10 −0
  • internal/host/consolefleet_owner_unix.go +31 −0
  • internal/host/consolefleet_test.go +71 −37
diff --git a/cmd/console/fleetsocket.go b/cmd/console/fleetsocket.go
index 2ad9be188..33d5c6419 100644
--- a/cmd/console/fleetsocket.go
+++ b/cmd/console/fleetsocket.go
@@ -1,6 +1,7 @@
package main
import (
+ "io"
"net"
"net/http"
@@ -15,16 +16,37 @@ import (
// 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.
+// guardFleetSocket makes srv safe to serve the fleet socket from as well as
+// TCP: the handler answers only box doors on a unix listener
+// (fleetSocketOnly), and net/http's own answer to "OPTIONS *", which runs
+// before any handler, is turned off and given back to TCP alone (task 5
+// review R1 P2).
+func guardFleetSocket(srv *http.Server) {
+ srv.DisableGeneralOptionsHandler = true
+ srv.Handler = fleetSocketOnly(srv.Handler)
+}
+
// 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) {
+ la, _ := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
+ onSocket := la != nil && la.Network() == "unix"
+ if onSocket && !consolefleet.BoxDoor(r) {
http.NotFound(w, r)
return
}
+ if r.Method == http.MethodOptions && r.RequestURI == "*" {
+ // What net/http answers on TCP when its general OPTIONS
+ // handler is on (globalOptionsHandler): an empty 200.
+ w.Header().Set("Content-Length", "0")
+ if r.ContentLength != 0 {
+ _, _ = io.Copy(io.Discard, http.MaxBytesReader(w, r.Body, 4<<10))
+ }
+ return
+ }
h.ServeHTTP(w, r)
})
}
diff --git a/cmd/console/fleetsocket_test.go b/cmd/console/fleetsocket_test.go
index f7c0c880b..3685da242 100644
--- a/cmd/console/fleetsocket_test.go
+++ b/cmd/console/fleetsocket_test.go
@@ -3,6 +3,7 @@
package main
import (
+ "bufio"
"context"
"errors"
"fmt"
@@ -16,6 +17,8 @@ import (
"syscall"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/console"
)
// TestFleetSocketOnlyAnswersBoxDoors: on the unix listener only the box
@@ -205,3 +208,56 @@ func TestConsoleStopFleetSocketLifecycle(t *testing.T) {
}
})
}
+
+// TestFleetSocketOptionsStar: "OPTIONS *" is answered by net/http before
+// any handler unless the server turns that off; through guardFleetSocket
+// it gets 404 on the fleet socket and the same empty 200 as before on TCP
+// (task 5 review R1 P2).
+func TestFleetSocketOptionsStar(t *testing.T) {
+ srv := console.NewHTTPServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "console") }))
+ guardFleetSocket(srv)
+ base := shortTempDir(t)
+ ul, err := net.Listen("unix", filepath.Join(base, "s"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ tl, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ go srv.Serve(ul)
+ go srv.Serve(tl)
+ t.Cleanup(func() { srv.Close() })
+ ask := func(network, addr, request string) string {
+ t.Helper()
+ c, err := net.Dial(network, addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ if _, err := io.WriteString(c, request); err != nil {
+ t.Fatal(err)
+ }
+ line, err := bufio.NewReader(c).ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.TrimSpace(line)
+ }
+ const options = "OPTIONS * HTTP/1.1\r\nHost: console\r\nConnection: close\r\n\r\n"
+ if got := ask("unix", ul.Addr().String(), options); got != "HTTP/1.1 404 Not Found" {
+ t.Errorf("fleet socket OPTIONS *: %q", got)
+ }
+ if got := ask("tcp", tl.Addr().String(), options); got != "HTTP/1.1 200 OK" {
+ t.Errorf("TCP OPTIONS *: %q", got)
+ }
+ const door = "POST /api/fleet/replicas/a/app/h/coordinator HTTP/1.1\r\nHost: console\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ if got := ask("unix", ul.Addr().String(), door); got != "HTTP/1.1 200 OK" {
+ t.Errorf("fleet socket box door: %q", got)
+ }
+ const page = "GET / HTTP/1.1\r\nHost: console\r\nConnection: close\r\n\r\n"
+ if got := ask("unix", ul.Addr().String(), page); got != "HTTP/1.1 404 Not Found" {
+ t.Errorf("fleet socket page: %q", got)
+ }
+}
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 45fa1f8e3..e72105b7e 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -980,7 +980,7 @@ func serve() {
// 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)
+ guardFleetSocket(httpSrv)
// 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
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T1-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T1-R1.md
new file mode 100644
index 000000000..0f819a55e
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T1-R1.md
@@ -0,0 +1,15 @@
+No P1 findings. One P2:
+
+- **P2 — Task 1: the guard validates only the first directory in a list.** At [runtimedir_guard_test.go:242](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/caps/runtimedir_guard_test.go:242), `strings.HasPrefix(s.value, "carlos-")` checks the entire assignment. `RuntimeDirectory` is list-valued, as [render.go:169](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/caps/render.go:169) already documents. Changing an allowlisted writer’s existing assignment to `RuntimeDirectory=carlos-runsc evil` preserves its site count and passes the prefix check while assigning an unreserved directory.
+
+ **Fix:** Require a single literal directory under `carlos-`, or validate every directory in the assignment; add a mixed-list fixture. **Fault family:** guard coverage of the platform runtime-directory namespace. This is a missing regression check; the current allowlisted writers use reserved names.
+
+Other checks:
+
+- Ship, adopt, converge, and service rendering reach `ValidCapabilities`. Its only behavioral change is rejecting `carlos-*`; `scanClaims` is unchanged.
+- `RuntimeDirClaimant` propagates encountered non-absence read errors as claimed. It scans generated **service** drop-ins, matching Task 1’s scope—not all configuration systemd applies. Socket drop-ins and operator-named drop-ins are excluded; it does not establish general systemd-wide exclusivity.
+- The scanner handles the specified literal concatenations, property maps, and site counts. Its named-constant/runtime-assembly limitation is documented.
+
+The focused test command could not start because the read-only sandbox denied Go’s temporary build directory. No files were edited and no full suites were run.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T3-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T3-R1.md
new file mode 100644
index 000000000..5c72f620f
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T3-R1.md
@@ -0,0 +1,35 @@
+1. **P1 — An active console can cause a legacy app-owned directory to be certified exclusive.** Spec §3 and §4 step 5.
+
+ **Evidence:** [consolefleet.go:189](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/host/consolefleet.go:189) checks claims on disk, then skips the directory check for active/activating/reloading/deactivating consoles. [converge.go:307](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/caps/converge.go:307) changes capability files before reloading or restarting their units.
+
+ **Failure scenario:** A legacy app owns `/run/carlos-console`; the console is already running and has received its drop-in without restarting. Root initially refuses exclusivity. A subsequent capability change removes the app’s claim, but the pass crashes before reload/restart. On the next pass, the console step sees no on-disk claimant and an active console, and publishes `exclusive: true`. The legacy app still owns the directory and can chmod it to 0755 and bind `fleet.sock`, satisfying the specified edge checks and receiving fleet tokens.
+
+ **Fix:** Before granting exclusivity, establish that any existing directory belongs to the console’s effective service identity; refuse unverifiable ownership. Cover the removed-claim/live-directory case explicitly. Checking loaded claims alone is insufficient once a daemon-reload has removed the property while the old process remains alive.
+
+ **Fault family:** Live socket ownership must follow the console’s identity, not merely the absence of an on-disk claim.
+
+2. **P2 — The reload marker does not invalidate an existing affirmative record.** Spec §4 steps 2–5; brief check 1.
+
+ **Evidence:** [consolefleet.go:161](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/host/consolefleet.go:161) writes the marker and edits the drop-in without updating `status.json`. Persistence happens only after `run()` returns, at [consolefleet.go:308](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/host/consolefleet.go:308); persistence errors only log at line 219.
+
+ **Failure scenario:** Start with a published `exclusive: true` record and a drop-in needing repair. A crash after writing the replacement but before reload or persistence leaves the old affirmative record alongside `reload-pending`. A reload failure followed by a status-write failure has the same result. The specified edge reader checks the record, not the marker. Thus the marker ensures retry, but does not establish the requested publication invariant.
+
+ **Fix:** Durably invalidate the affirmative record before changing the drop-in, aborting the change if invalidation fails. Publish true only after successful reload, marker removal and exclusivity checks. Add crash-boundary tests beginning with an existing true record.
+
+ **Fault family:** Published authorization must not survive an incomplete configuration transition.
+
+3. **P2 — The production drop-in reader omits the required trust checks.** Plan Task 3.
+
+ **Evidence:** [consolefleet.go:244](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/host/consolefleet.go:244) uses `os.ReadFile`; Task 3 requires `rootstate.OpenTrustedFile`.
+
+ **Failure scenario:** A symlink or writable/non-root-owned drop-in containing the expected bytes is accepted as unchanged. The step neither rejects its provenance nor replaces it with the promised root-owned file.
+
+ **Fix:** Use `rootstate.OpenTrustedFile`, read through that descriptor and close it. Preserve the absent-file handling; add rejection cases for symlinks and unsafe ownership/modes.
+
+ **Fault family:** Root’s configuration reads must validate filesystem authority, not just pathname and contents.
+
+The call placement satisfies full/config-only inclusion and restart-only exclusion. I found no missing-unit exit-status issue: upstream systemd’s `show` returns success for the not-found property response; explicit `-p` also includes empty properties. [systemd show implementation](https://github.com/systemd/systemd/blob/v257/src/systemctl/systemctl-show.c#L2030-L2067), [property selection](https://github.com/systemd/systemd/blob/v257/src/systemctl/systemctl.c#L590-L610).
+
+Review was static against the requested commit. No files edited, subagents spawned, or test suites run.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T4-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T4-R1.md
new file mode 100644
index 000000000..84b05acc6
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T4-R1.md
@@ -0,0 +1,22 @@
+No P1 found. Three P2 findings:
+
+1. **P2 — Task 4: the status wrapper hides streaming and hijacking capabilities.**
+ Evidence: [replicaconsole.go:222](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/edge/replicaconsole.go:222) embeds only `http.ResponseWriter` and provides neither `Unwrap` nor forwarding methods. `ReverseProxy` uses `ResponseController` for flushing and hijacking; both therefore return unsupported through this wrapper. A streamed response loses explicit flushing; a protocol upgrade fails. I found no current console door requiring either, so this is P2.
+ **Fix:** expose the underlying writer through `Unwrap`, and test streaming and upgrade behavior, including accurate upgrade status recording.
+ **Fault family:** instrumentation must preserve response-writer capabilities.
+
+2. **P2 — Task 4: informational responses become the recorded final result.**
+ Evidence: [replicaconsole.go:227](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/edge/replicaconsole.go:227) records the first `WriteHeader`, including 1xx. The reverse proxy forwards informational responses through this method. For example, `100 Continue` followed by `200 OK` records `"100"` instead of `"ok"`; a subsequent failure likewise retains the informational code.
+ **Fix:** forward informational headers without recording them as the final status; handle 101 explicitly. Add tests for informational responses followed by success and failure.
+ **Fault family:** last-call telemetry must describe the final response.
+
+3. **P2 — Task 4: the required production-reader trust tests are missing.**
+ Evidence: [replicaconsole_socket_test.go:284](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/edge/replicaconsole_socket_test.go:284) tests only rejection beneath an untrusted temporary-directory chain and a missing path. It never reaches a record in a trusted directory, changes its UID or mode, or checks routing after rejection. Removing `CheckPublicConfig` could leave this test green. This does not implement Task 4’s specified Linux/root test.
+ **Fix:** add a trusted-chain positive control, then independently test another UID and mode 0666, asserting route fallback and zero socket hits. Also exercise a restriction unique to `CheckPublicConfig`, such as mode 0600.
+ **Fault family:** regression coverage for root-record provenance and public-config validation.
+
+The reviewed selection code follows env > socket > route scan. The production reader uses the specified trust checks; the Unix dial target is fixed; socket dial failure returns 502 without falling back. The wrapper itself does not edit headers.
+
+Focused tests could not start because the read-only sandbox refused Go’s temporary build directory. No files were edited; no full suites or subagents were run.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T5-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T5-R1.md
new file mode 100644
index 000000000..a08604441
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hub-console-socket-T5-R1.md
@@ -0,0 +1,13 @@
+**P2 — `OPTIONS *` bypasses the fleet socket’s 404 filter.**
+
+- **Authority:** Spec §5; Task 5’s requirement that non-box-door requests receive 404.
+- **Evidence:** [main.go:981](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/cmd/console/main.go:981) installs the restriction only as a handler wrapper. [httpserver.go:16](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/console/httpserver.go:16) leaves `DisableGeneralOptionsHandler` false. Go’s `serverHandler.ServeHTTP` intercepts `OPTIONS *` before invoking that wrapper and returns an empty 200 response.
+- **Failure scenario:** A client sends `OPTIONS * HTTP/1.1` with a valid Host header over `fleet.sock`. It receives 200, although this is not a box door. The direct-handler tests cannot detect this bypass.
+- **Fix:** Disable automatic general OPTIONS handling for this server and explicitly preserve the existing TCP behavior while rejecting it on Unix. Add a real-socket regression test covering both listeners.
+- **Fault family:** Fleet listener request restriction. This is a response-contract defect; it does not expose another console endpoint.
+
+No P1 found. The shared server closes and drains both registered listeners; fleet listener errors do not determine the exit status. Directory validation, stale-path removal, and missing-directory fallback match the design. The listen-to-chmod interval introduces no impersonation opportunity under the approved directory ownership model. TCP readiness and stop budgets remain unchanged.
+
+The focused tests could not execute because the read-only sandbox denied Go’s temporary build directory. No files were edited or full suites run.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/internal/caps/runtimedir_guard_test.go b/internal/caps/runtimedir_guard_test.go
index 2e7fa41ff..e3bca9554 100644
--- a/internal/caps/runtimedir_guard_test.go
+++ b/internal/caps/runtimedir_guard_test.go
@@ -239,8 +239,12 @@ func TestRuntimeDirectoryRenderSites(t *testing.T) {
continue
}
for _, s := range sites {
- if s.value != "" && !strings.HasPrefix(s.value, "carlos-") {
- t.Errorf("%s assigns RuntimeDirectory %q, outside the platform's carlos- prefix", file, s.value)
+ // RuntimeDirectory is a list: every name in it must be the
+ // platform's (task 1 review R1 P2).
+ for _, dir := range strings.Fields(s.value) {
+ if !strings.HasPrefix(dir, "carlos-") {
+ t.Errorf("%s assigns RuntimeDirectory %q, and %q is outside the platform's carlos- prefix", file, s.value, dir)
+ }
}
}
}
@@ -263,6 +267,7 @@ func TestRuntimeDirSitesScanner(t *testing.T) {
"prefix and a variable": {`package p; func f(x string) string { return "RuntimeDirectory=" + x }`, []string{""}},
"constant concatenation": {`package p; const n = "carlos-console"; const b = "[Service]\nRuntimeDirectory=" + n + "\n"`, []string{""}},
"mode only": {`package p; const s = "RuntimeDirectoryMode=0700"`, nil},
+ "a list": {"package p\nconst s = \"RuntimeDirectory=carlos-runsc evil\\n\"\n", []string{"carlos-runsc evil"}},
} {
sites, err := goRuntimeDirSites([]byte(tc.src))
if err != nil {
@@ -277,3 +282,12 @@ func TestRuntimeDirSitesScanner(t *testing.T) {
}
}
}
+
+// TestRuntimeDirSitesListValues: a list assignment is checked name by name,
+// so an allowlisted writer cannot add an app's directory beside its own.
+func TestRuntimeDirSitesListValues(t *testing.T) {
+ sites := unitRuntimeDirSites([]byte("[Service]\nRuntimeDirectory=carlos-runsc evil\n"))
+ if len(sites) != 1 || strings.Join(strings.Fields(sites[0].value), ",") != "carlos-runsc,evil" {
+ t.Fatalf("%+v", sites)
+ }
+}
diff --git a/internal/consolefleet/consolefleet.go b/internal/consolefleet/consolefleet.go
index e37ca9c01..d4d46c23a 100644
--- a/internal/consolefleet/consolefleet.go
+++ b/internal/consolefleet/consolefleet.go
@@ -68,15 +68,20 @@ const (
OutcomeFailed = "failed"
)
-// Record is root's last console step. Exclusive is the only field the edge
-// acts on: true when root saw the drop-in applied, the unit's runtime
-// directory settings as the design needs them, and no other claim on Dir.
+// Record is root's last console step. The edge acts on two fields:
+// Exclusive, true when root saw the drop-in applied, the unit's runtime
+// directory settings as the design needs them, no other claim on Dir and
+// Dir (if present) owned by the console's user; and ConsoleUID, that user,
+// which Dir's owner must still be when the edge forwards (task 3 review
+// R1 P1: a process that held Dir before root looked keeps it whatever the
+// claims on disk say, and the owner is what tells them apart).
type Record struct {
- Schema int `json:"schema"`
- Outcome string `json:"outcome"`
- Reason string `json:"reason,omitempty"`
- Exclusive bool `json:"exclusive"`
- At time.Time `json:"at"`
+ Schema int `json:"schema"`
+ Outcome string `json:"outcome"`
+ Reason string `json:"reason,omitempty"`
+ Exclusive bool `json:"exclusive"`
+ ConsoleUID int `json:"console_uid"`
+ At time.Time `json:"at"`
}
// DecodeRecord is the strict reading the edge and the agent share: at most
@@ -98,6 +103,9 @@ func DecodeRecord(raw []byte) (Record, error) {
if r.Schema != 1 {
return Record{}, fmt.Errorf("console fleet record: schema %d, want 1", r.Schema)
}
+ if r.ConsoleUID < 0 {
+ return Record{}, fmt.Errorf("console fleet record: console_uid %d", r.ConsoleUID)
+ }
switch r.Outcome {
case OutcomeInstalled, OutcomeUnchanged, OutcomeRemoved, OutcomeAbsent, OutcomeFailed:
default:
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
index ce2ffcaff..eeebbcf83 100644
--- a/internal/edge/replicaconsole.go
+++ b/internal/edge/replicaconsole.go
@@ -171,7 +171,21 @@ func readConsoleFleetRecordIn(dir string) (consolefleet.Record, error) {
if err != nil {
return consolefleet.Record{}, err
}
- return consolefleet.DecodeRecord(raw)
+ rec, err := consolefleet.DecodeRecord(raw)
+ if err != nil {
+ return consolefleet.Record{}, err
+ }
+ // Root writes its reload-pending marker before it touches the drop-in
+ // and removes it only after daemon-reload succeeds (task 3 review R1
+ // P2-2): while it is there, the record describes a configuration that
+ // may not be the one in effect. The directory passed the trust walk
+ // above, so only root can have made or removed it.
+ if _, err := os.Lstat(filepath.Join(dir, consolefleet.ReloadPending)); err == nil {
+ return consolefleet.Record{}, errors.New("a change to " + consolefleet.Unit + "'s drop-in is waiting for a daemon-reload")
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return consolefleet.Record{}, err
+ }
+ return rec, nil
}
// ready is nil when a box call may go to the socket: root's record says
@@ -197,6 +211,12 @@ func (c consoleFleetSource) ready() error {
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())
}
+ // 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)
+ }
si, err := os.Lstat(c.socket)
if err != nil {
return err
@@ -230,12 +250,20 @@ type replicaCallStatus struct {
}
func (w *replicaCallStatus) WriteHeader(code int) {
- if w.code == 0 {
+ // An informational answer (100 Continue, 103 Early Hints) precedes the
+ // final one and is not the call's result (task 4 review R1 P2-2); 101
+ // Switching Protocols is final.
+ if w.code == 0 && (code >= 200 || code == http.StatusSwitchingProtocols) {
w.code = code
}
w.ResponseWriter.WriteHeader(code)
}
+// Unwrap lets http.ResponseController reach the connection's writer, so
+// the proxy's flushes and upgrades work through this wrapper (task 4 review
+// R1 P2-1).
+func (w *replicaCallStatus) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+
func (w *replicaCallStatus) Write(b []byte) (int, error) {
if w.code == 0 {
w.code = http.StatusOK
diff --git a/internal/edge/replicaconsole_owner_other.go b/internal/edge/replicaconsole_owner_other.go
new file mode 100644
index 000000000..0e4c715f0
--- /dev/null
+++ b/internal/edge/replicaconsole_owner_other.go
@@ -0,0 +1,8 @@
+//go:build !unix
+
+package edge
+
+import "io/fs"
+
+// fileOwner: no uid to check here, so the socket is never used.
+func fileOwner(fs.FileInfo) (int, bool) { return -1, false }
diff --git a/internal/edge/replicaconsole_owner_unix.go b/internal/edge/replicaconsole_owner_unix.go
new file mode 100644
index 000000000..a51caf79d
--- /dev/null
+++ b/internal/edge/replicaconsole_owner_unix.go
@@ -0,0 +1,17 @@
+//go:build unix
+
+package edge
+
+import (
+ "io/fs"
+ "syscall"
+)
+
+// fileOwner is fi's owning uid, when the platform says.
+func fileOwner(fi fs.FileInfo) (int, bool) {
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return -1, false
+ }
+ return int(st.Uid), true
+}
diff --git a/internal/edge/replicaconsole_record_rootrunner_linux_test.go b/internal/edge/replicaconsole_record_rootrunner_linux_test.go
new file mode 100644
index 000000000..e8d04b895
--- /dev/null
+++ b/internal/edge/replicaconsole_record_rootrunner_linux_test.go
@@ -0,0 +1,66 @@
+//go:build linux && rootrunner
+
+package edge
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/consolefleet"
+)
+
+// TestReplicaConsoleRecordReaderTrust is the production reader against a
+// trusted chain (task 4 review R1 P2-3): root's record root:root 0644 is
+// accepted; another owner, 0666 (writable) and 0600 (only
+// CheckPublicConfig refuses it) are not; nor is a record while root's
+// reload-pending marker stands. Root only: it needs a root-owned directory
+// chain, which /tmp is not.
+func TestReplicaConsoleRecordReaderTrust(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Skip("needs root")
+ }
+ dir, err := os.MkdirTemp("/var/lib", "carlos-console-fleet-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, consolefleet.StatusFile)
+ write := func(mode os.FileMode, uid int) {
+ t.Helper()
+ os.Remove(path)
+ if err := os.WriteFile(path, []byte(`{"schema":1,"outcome":"unchanged","exclusive":true,"console_uid":997,"at":"2026-11-24T10:00:00Z"}`), mode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, mode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chown(path, uid, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write(0o644, 0)
+ if rec, err := readConsoleFleetRecordIn(dir); err != nil || !rec.Exclusive || rec.ConsoleUID != 997 {
+ t.Fatalf("root's record refused: %+v %v", rec, err)
+ }
+ marker := filepath.Join(dir, consolefleet.ReloadPending)
+ if err := os.WriteFile(marker, []byte("1\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readConsoleFleetRecordIn(dir); err == nil {
+ t.Fatal("accepted with a reload pending")
+ }
+ os.Remove(marker)
+ for name, tc := range map[string]struct {
+ mode os.FileMode
+ uid int
+ }{"another owner": {0o644, 1000}, "writable by others": {0o666, 0}, "not public": {0o600, 0}} {
+ write(tc.mode, tc.uid)
+ if _, err := readConsoleFleetRecordIn(dir); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
diff --git a/internal/edge/replicaconsole_socket_test.go b/internal/edge/replicaconsole_socket_test.go
index 2a49f68c3..9f1066269 100644
--- a/internal/edge/replicaconsole_socket_test.go
+++ b/internal/edge/replicaconsole_socket_test.go
@@ -22,6 +22,7 @@ type fleetSocketFixture struct {
dir, socket string
hits atomic.Int32
code atomic.Int32 // the console's answer; 0 = 200
+ early atomic.Bool // answer 103 Early Hints before the final status
record atomic.Pointer[consolefleet.Record]
recordErr atomic.Pointer[error]
srv *http.Server
@@ -49,6 +50,9 @@ func newFleetSocketFixture(t *testing.T) *fleetSocketFixture {
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 f.early.Load() {
+ w.WriteHeader(http.StatusEarlyHints)
+ }
if c := f.code.Load(); c != 0 {
w.WriteHeader(int(c))
}
@@ -56,7 +60,7 @@ func newFleetSocketFixture(t *testing.T) *fleetSocketFixture {
})}
go func() { _ = f.srv.Serve(ln) }()
t.Cleanup(func() { _ = f.srv.Close() })
- f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: true})
+ f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: true, ConsoleUID: os.Getuid()})
return f
}
@@ -167,6 +171,11 @@ func TestReplicaConsoleSocketRefusals(t *testing.T) {
t.Fatal(err)
}
},
+ "directory not the console user's": func(t *testing.T, f *fleetSocketFixture) {
+ // Task 3 review R1 P1: root recorded the console's uid, and the
+ // directory belongs to someone else.
+ f.record.Store(&consolefleet.Record{Schema: 1, Outcome: consolefleet.OutcomeUnchanged, Exclusive: true, ConsoleUID: os.Getuid() + 1})
+ },
"no directory": func(t *testing.T, f *fleetSocketFixture) {
_ = f.ln.Close()
if err := os.RemoveAll(f.dir); err != nil {
@@ -213,13 +222,26 @@ func TestReplicaConsoleSocketDialFailure(t *testing.T) {
func TestReplicaConsoleSocketResults(t *testing.T) {
f := newFleetSocketFixture(t)
e, _ := socketEdge(t, f)
- for _, code := range []int{401, 500} {
+ for _, tc := range []struct {
+ code int
+ early bool
+ }{{401, false}, {500, false}, {500, true}, {200, true}} {
+ code := tc.code
f.code.Store(int32(code))
- if w := postBoxCall(t, e); w.Code != code {
+ f.early.Store(tc.early)
+ // httptest's recorder keeps the first status written, 103 here, so
+ // the final answer is checked through the last-call record below.
+ if w := postBoxCall(t, e); !tc.early && 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)
+ want := strconv.Itoa(code)
+ if code == 200 {
+ want = "ok"
+ }
+ // An informational 103 before the final answer is not the result
+ // (task 4 review R1 P2-2).
+ if c := e.LastReplicaConsoleCall(); c == nil || c.Source != ReplicaConsoleSourceSocket || c.Result != want {
+ t.Fatalf("early=%v: last call %+v, want %s", tc.early, c, want)
}
}
}
@@ -316,3 +338,17 @@ func TestConsoleFleetSocketReadyIndependentOfSource(t *testing.T) {
t.Fatal("socket absent, reported ready")
}
}
+
+// TestReplicaCallStatusUnwraps: the proxy's flushes reach the connection
+// through the recording wrapper (task 4 review R1 P2-1).
+func TestReplicaCallStatusUnwraps(t *testing.T) {
+ rec := httptest.NewRecorder()
+ w := &replicaCallStatus{ResponseWriter: rec}
+ if err := http.NewResponseController(w).Flush(); err != nil || !rec.Flushed {
+ t.Fatalf("flush through the wrapper: %v flushed %v", err, rec.Flushed)
+ }
+ w.WriteHeader(http.StatusSwitchingProtocols)
+ if w.result() != "101" {
+ t.Fatalf("101 result %q", w.result())
+ }
+}
diff --git a/internal/host/consolefleet.go b/internal/host/consolefleet.go
index 605bc178b..e422bab10 100644
--- a/internal/host/consolefleet.go
+++ b/internal/host/consolefleet.go
@@ -12,11 +12,14 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"io/fs"
"log"
"os"
+ "os/user"
"path/filepath"
"slices"
+ "strconv"
"strings"
"sync/atomic"
"time"
@@ -37,6 +40,8 @@ type consoleUnitProps struct {
RuntimeDirectory []string
Mode string
Preserve string
+ User string
+ DynamicUser string
}
func (p consoleUnitProps) hasRuntimeDir(name string) bool {
@@ -44,7 +49,7 @@ func (p consoleUnitProps) hasRuntimeDir(name string) bool {
}
// consoleUnitShowKeys is the one systemctl show query the step makes.
-var consoleUnitShowKeys = []string{"Id", "LoadState", "ActiveState", "RuntimeDirectory", "RuntimeDirectoryMode", "RuntimeDirectoryPreserve"}
+var consoleUnitShowKeys = []string{"Id", "LoadState", "ActiveState", "RuntimeDirectory", "RuntimeDirectoryMode", "RuntimeDirectoryPreserve", "User", "DynamicUser"}
// parseConsoleUnitProps reads `systemctl show console.service -p <keys>`
// strictly: one block, every asked key exactly once, the unit's own Id.
@@ -79,6 +84,8 @@ func parseConsoleUnitProps(out []byte) (consoleUnitProps, error) {
RuntimeDirectory: strings.Fields(got["RuntimeDirectory"]),
Mode: got["RuntimeDirectoryMode"],
Preserve: got["RuntimeDirectoryPreserve"],
+ User: got["User"],
+ DynamicUser: got["DynamicUser"],
}, nil
}
@@ -94,10 +101,13 @@ type consoleFleetStep struct {
setMarker func() error
clearMarker func() error
claimant func() (host string, claimed bool)
- runDirExists func() (bool, error)
- readRecord func() ([]byte, error)
- writeRecord func([]byte) error
- now func() time.Time
+ lookupUID func(user string) (int, error)
+ // runDirOwner is /run/carlos-console's owner: exists false when absent,
+ // an error when it is not a real directory only its owner can write.
+ runDirOwner func() (uid int, exists bool, err error)
+ readRecord func() ([]byte, error)
+ writeRecord func([]byte) error
+ now func() time.Time
}
// run is spec §4 steps 1-5. It never fails the pass: every refusal is a
@@ -142,7 +152,7 @@ func (s consoleFleetStep) run() consolefleet.Record {
}
rec.Outcome = consolefleet.OutcomeInstalled
}
- rec.Exclusive, rec.Reason = s.exclusive(props)
+ rec.Exclusive, rec.ConsoleUID, rec.Reason = s.exclusive(props)
case "not-found":
rec.Outcome, rec.Reason = consolefleet.OutcomeAbsent, "no "+consolefleet.Unit+" on this box"
if exists {
@@ -178,39 +188,48 @@ func (s consoleFleetStep) change(edit func() error) string {
}
// exclusive is spec §4 step 5: the console holds /run/carlos-console alone,
-// with the lifetime and mode the design needs.
-func (s consoleFleetStep) exclusive(p consoleUnitProps) (bool, string) {
+// with the lifetime and mode the design needs, and the directory, when it
+// exists, belongs to the console's user. It returns that user's uid for the
+// record: the edge checks the directory's owner against it on every call.
+func (s consoleFleetStep) exclusive(p consoleUnitProps) (bool, int, string) {
+ no := func(format string, args ...any) (bool, int, string) { return false, 0, fmt.Sprintf(format, args...) }
if !p.hasRuntimeDir(consolefleet.RuntimeDirName) {
- return false, fmt.Sprintf("the drop-in is not in effect: %s has no RuntimeDirectory=%s", consolefleet.Unit, consolefleet.RuntimeDirName)
+ return no("the drop-in is not in effect: %s has no RuntimeDirectory=%s", consolefleet.Unit, consolefleet.RuntimeDirName)
}
if p.Preserve != "no" {
- return false, fmt.Sprintf("%s sets RuntimeDirectoryPreserve=%s, so %s would outlive the console", consolefleet.Unit, p.Preserve, consolefleet.Dir)
+ return no("%s sets RuntimeDirectoryPreserve=%s, so %s would outlive the console", consolefleet.Unit, p.Preserve, consolefleet.Dir)
}
if p.Mode != "0755" {
- return false, fmt.Sprintf("%s's RuntimeDirectoryMode is %s, not 0755", consolefleet.Unit, p.Mode)
+ return no("%s's RuntimeDirectoryMode is %s, not 0755", consolefleet.Unit, p.Mode)
+ }
+ if p.DynamicUser != "no" {
+ return no("%s sets DynamicUser=%s, so its user cannot be checked", consolefleet.Unit, p.DynamicUser)
}
if host, claimed := s.claimant(); claimed {
- return false, fmt.Sprintf("a capability drop-in for %s also claims %s", host, consolefleet.Dir)
+ return no("a capability drop-in for %s also claims %s", host, consolefleet.Dir)
}
- switch p.ActiveState {
- case "active", "activating", "reloading", "deactivating":
- default:
- found, err := s.runDirExists()
- if err != nil {
- return false, fmt.Sprintf("checking %s: %v", consolefleet.Dir, err)
- }
- if found {
- return false, fmt.Sprintf("%s exists while %s is %s, so something else made it", consolefleet.Dir, consolefleet.Unit, p.ActiveState)
+ 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)
}
}
- return true, ""
+ owner, exists, err := s.runDirOwner()
+ if err != nil {
+ return no("checking %s: %v", consolefleet.Dir, err)
+ }
+ if exists && owner != uid {
+ return no("%s belongs to uid %d, not %s's user (uid %d)", consolefleet.Dir, owner, consolefleet.Unit, uid)
+ }
+ return true, uid, ""
}
// 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) {
if raw, err := s.readRecord(); err == nil {
- if old, err := consolefleet.DecodeRecord(raw); err == nil && old.Outcome == rec.Outcome && old.Reason == rec.Reason && old.Exclusive == rec.Exclusive {
+ if old, err := consolefleet.DecodeRecord(raw); err == nil && old.Outcome == rec.Outcome && old.Reason == rec.Reason && old.Exclusive == rec.Exclusive && old.ConsoleUID == rec.ConsoleUID {
return
}
}
@@ -242,14 +261,8 @@ func productionConsoleFleetStep(ctx context.Context) consoleFleetStep {
}
return parseConsoleUnitProps(out)
},
- reload: daemonReload,
- readDropIn: func() ([]byte, bool, error) {
- b, err := os.ReadFile(consolefleet.DropInPath)
- if errors.Is(err, fs.ErrNotExist) {
- return nil, false, nil
- }
- return b, err == nil, err
- },
+ reload: daemonReload,
+ readDropIn: readConsoleFleetDropIn,
writeDropIn: func(b []byte) error {
if err := os.MkdirAll(filepath.Dir(consolefleet.DropInPath), 0o755); err != nil {
return err
@@ -281,13 +294,14 @@ func productionConsoleFleetStep(ctx context.Context) consoleFleetStep {
return withStore(func(st rootstate.Store) error { return st.Remove(consolefleet.ReloadPending) })
},
claimant: func() (string, bool) { return caps.RuntimeDirClaimant(dropInRoot, consolefleet.RuntimeDirName) },
- runDirExists: func() (bool, error) {
- _, err := os.Lstat(consolefleet.Dir)
- if errors.Is(err, fs.ErrNotExist) {
- return false, nil
+ lookupUID: func(name string) (int, error) {
+ u, err := user.Lookup(name)
+ if err != nil {
+ return 0, err
}
- return err == nil, err
+ return strconv.Atoi(u.Uid)
},
+ runDirOwner: func() (int, bool, error) { return dirOwner(consolefleet.Dir) },
readRecord: func() ([]byte, error) {
var raw []byte
err := withStore(func(st rootstate.Store) error {
@@ -304,6 +318,33 @@ 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.
+func readConsoleFleetDropIn() ([]byte, bool, error) {
+ f, err := rootstate.OpenTrustedFile(consolefleet.DropInPath)
+ 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, err
+ }
+ defer f.Close()
+ b, err := io.ReadAll(io.LimitReader(f, consolefleet.MaxRecord+1))
+ return b, true, err
+}
+
// adoptConsoleFleetStep is the step runAdoptUnderRootRelease runs; a
// variable so a test can drive the real pass with the step injected.
var adoptConsoleFleetStep = func(ctx context.Context) {
diff --git a/internal/host/consolefleet_owner_other.go b/internal/host/consolefleet_owner_other.go
new file mode 100644
index 000000000..845979179
--- /dev/null
+++ b/internal/host/consolefleet_owner_other.go
@@ -0,0 +1,10 @@
+//go:build !unix
+
+package host
+
+import "errors"
+
+// dirOwner: the console fleet socket is a Linux box's.
+func dirOwner(string) (int, bool, error) {
+ return 0, false, errors.New("no console fleet socket on this platform")
+}
diff --git a/internal/host/consolefleet_owner_unix.go b/internal/host/consolefleet_owner_unix.go
new file mode 100644
index 000000000..85d94d569
--- /dev/null
+++ b/internal/host/consolefleet_owner_unix.go
@@ -0,0 +1,31 @@
+//go:build unix
+
+package host
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "syscall"
+)
+
+// dirOwner is path's owner when it is a real directory (not a symlink) that
+// only its owner can write; exists false when absent.
+func dirOwner(path string) (uid int, exists bool, err error) {
+ fi, err := os.Lstat(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return 0, false, nil
+ }
+ if err != nil {
+ return 0, false, err
+ }
+ if !fi.IsDir() || fi.Mode().Perm()&0o022 != 0 {
+ return 0, true, fmt.Errorf("%s is not a directory only its owner can write (%v)", path, fi.Mode())
+ }
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, true, fmt.Errorf("%s has no owner to check", path)
+ }
+ return int(st.Uid), true, nil
+}
diff --git a/internal/host/consolefleet_test.go b/internal/host/consolefleet_test.go
index 04949455f..f91e1b3b0 100644
--- a/internal/host/consolefleet_test.go
+++ b/internal/host/consolefleet_test.go
@@ -13,23 +13,26 @@ import (
// fakeConsoleFleet is every seam of consoleFleetStep, in memory.
type fakeConsoleFleet struct {
- props consoleUnitProps
- showErr error
- dropIn []byte // nil = absent
- readErr error
- writeErr error
- removeErr error
- reloadErr error
- reloads int
- writes int
- removes int
- marker bool
- markerErr error
- claimant string
- claimed bool
- runDirFound bool
- record []byte
- recordErr error
+ props consoleUnitProps
+ showErr error
+ dropIn []byte // nil = absent
+ readErr error
+ writeErr error
+ removeErr error
+ reloadErr error
+ reloads int
+ writes int
+ removes int
+ marker bool
+ markerErr error
+ claimant string
+ claimed bool
+ dirOwner int
+ dirExists bool
+ dirErr error
+ uids map[string]int
+ record []byte
+ recordErr error
}
func (f *fakeConsoleFleet) step() consoleFleetStep {
@@ -62,19 +65,28 @@ func (f *fakeConsoleFleet) step() consoleFleetStep {
setMarker: func() error { f.marker = true; return f.markerErr },
clearMarker: func() error { f.marker = false; return f.markerErr },
claimant: func() (string, bool) { return f.claimant, f.claimed },
- runDirExists: func() (bool, error) { return f.runDirFound, nil },
- readRecord: func() ([]byte, error) { return f.record, f.recordErr },
- writeRecord: func(b []byte) error { f.record = append([]byte(nil), b...); return nil },
- now: func() time.Time { return time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC) },
+ lookupUID: func(name string) (int, error) {
+ if uid, ok := f.uids[name]; ok {
+ return uid, nil
+ }
+ return 0, errors.New("unknown user " + name)
+ },
+ runDirOwner: func() (int, bool, error) { return f.dirOwner, f.dirExists, f.dirErr },
+ readRecord: func() ([]byte, error) { return f.record, f.recordErr },
+ writeRecord: func(b []byte) error { f.record = append([]byte(nil), b...); return nil },
+ now: func() time.Time { return time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC) },
}
}
func loadedConsole() consoleUnitProps {
- return consoleUnitProps{LoadState: "loaded", ActiveState: "active", RuntimeDirectory: []string{consolefleet.RuntimeDirName}, Mode: "0755", Preserve: "no"}
+ return consoleUnitProps{LoadState: "loaded", ActiveState: "active", RuntimeDirectory: []string{consolefleet.RuntimeDirName}, Mode: "0755", Preserve: "no", User: "console", DynamicUser: "no"}
}
+// consoleUID is the console's user in these fakes.
+const consoleUID = 997
+
func TestConsoleFleetInstallsOnceAndReloadsOnce(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole()}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole()}
rec := f.step().run()
if rec.Outcome != consolefleet.OutcomeInstalled || !rec.Exclusive || string(f.dropIn) != consolefleet.DropInBody || f.reloads != 1 || f.marker {
t.Fatalf("first pass: %+v drop-in %q reloads %d marker %v", rec, f.dropIn, f.reloads, f.marker)
@@ -89,7 +101,7 @@ func TestConsoleFleetInstallsOnceAndReloadsOnce(t *testing.T) {
// next pass reloads although the bytes now match (round 2, P2-2), and the
// record is not exclusive until it does.
func TestConsoleFleetFailedReloadIsRetriedWithUnchangedBytes(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole(), reloadErr: errors.New("bus timeout")}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), reloadErr: errors.New("bus timeout")}
rec := f.step().run()
if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || !f.marker || string(f.dropIn) != consolefleet.DropInBody {
t.Fatalf("failed reload: %+v marker %v drop-in %q", rec, f.marker, f.dropIn)
@@ -108,7 +120,7 @@ func TestConsoleFleetFailedReloadIsRetriedWithUnchangedBytes(t *testing.T) {
// A failed write leaves the marker too: whatever reached the disk is
// reloaded next pass.
func TestConsoleFleetFailedWriteKeepsTheMarker(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole(), writeErr: errors.New("disk full")}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), writeErr: errors.New("disk full")}
rec := f.step().run()
if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || !f.marker || f.reloads != 0 {
t.Fatalf("failed write: %+v marker %v reloads %d", rec, f.marker, f.reloads)
@@ -120,7 +132,7 @@ func TestConsoleFleetFailedWriteKeepsTheMarker(t *testing.T) {
// No marker can be written: nothing is changed.
func TestConsoleFleetNoMarkerNoChange(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole(), markerErr: errors.New("read-only")}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), markerErr: errors.New("read-only")}
rec := f.step().run()
if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || f.writes != 0 || f.reloads != 0 {
t.Fatalf("%+v writes %d reloads %d", rec, f.writes, f.reloads)
@@ -150,13 +162,23 @@ func TestConsoleFleetNotExclusive(t *testing.T) {
f.props.RuntimeDirectory = nil
}, "not in effect"},
"app claim": {func(f *fakeConsoleFleet) { f.claimant, f.claimed = "old.example.com", true }, "old.example.com"},
- "directory while stopped": {func(f *fakeConsoleFleet) {
+ "directory owned by another user, console active": {func(f *fakeConsoleFleet) {
+ // Task 3 review R1 P1: a process that held the directory before
+ // root looked keeps it, whatever the claims on disk now say.
+ f.dirOwner, f.dirExists = 1234, true
+ }, "belongs to uid 1234"},
+ "directory owned by another user, console stopped": {func(f *fakeConsoleFleet) {
f.props.ActiveState = "inactive"
- f.runDirFound = true
- }, consolefleet.Dir},
+ f.dirOwner, f.dirExists = 1234, true
+ }, "belongs to uid 1234"},
+ "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"},
+ "dynamic user": {func(f *fakeConsoleFleet) { f.props.DynamicUser = "yes" }, "DynamicUser=yes"},
+ "unknown user": {func(f *fakeConsoleFleet) { f.props.User = "ghost" }, "ghost"},
} {
t.Run(name, func(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
tc.mutate(f)
rec := f.step().run()
if rec.Exclusive || !strings.Contains(rec.Reason, tc.reason) {
@@ -164,12 +186,24 @@ func TestConsoleFleetNotExclusive(t *testing.T) {
}
})
}
- // Stopped with no directory left behind is still exclusive.
- f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ // Stopped with no directory left behind is still exclusive, and so is a
+ // running console's own directory; the record names its user's uid.
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
f.props.ActiveState = "inactive"
- if rec := f.step().run(); !rec.Exclusive {
+ if rec := f.step().run(); !rec.Exclusive || rec.ConsoleUID != consoleUID {
t.Fatalf("stopped console, no directory: %+v", rec)
}
+ f.props.ActiveState = "active"
+ f.dirOwner, f.dirExists = consoleUID, true
+ if rec := f.step().run(); !rec.Exclusive || rec.ConsoleUID != consoleUID {
+ t.Fatalf("running console's own directory: %+v", rec)
+ }
+ // A console with no User= runs as root.
+ f.props.User = ""
+ f.dirOwner = 0
+ if rec := f.step().run(); !rec.Exclusive || rec.ConsoleUID != 0 {
+ t.Fatalf("root console: %+v", rec)
+ }
}
func TestConsoleFleetShowFailureChangesNothing(t *testing.T) {
@@ -187,7 +221,7 @@ func TestConsoleFleetShowFailureChangesNothing(t *testing.T) {
// The record is rewritten only when something but its time changed, so an
// idle hourly pass leaves the file alone.
func TestConsoleFleetRecordWrittenOnlyOnChange(t *testing.T) {
- f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ f := &fakeConsoleFleet{uids: map[string]int{"console": consoleUID}, props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
s := f.step()
s.persist(s.run())
first := string(f.record)
@@ -208,12 +242,12 @@ func TestConsoleFleetRecordWrittenOnlyOnChange(t *testing.T) {
}
func TestParseConsoleUnitProps(t *testing.T) {
- good := "Id=console.service\nLoadState=loaded\nActiveState=active\nRuntimeDirectory=console carlos-console\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\n"
+ good := "Id=console.service\nLoadState=loaded\nActiveState=active\nRuntimeDirectory=console carlos-console\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\nUser=console\nDynamicUser=no\n"
p, err := parseConsoleUnitProps([]byte(good))
- if err != nil || p.LoadState != "loaded" || len(p.RuntimeDirectory) != 2 || !p.hasRuntimeDir(consolefleet.RuntimeDirName) {
+ if err != nil || p.LoadState != "loaded" || len(p.RuntimeDirectory) != 2 || !p.hasRuntimeDir(consolefleet.RuntimeDirName) || p.User != "console" || p.DynamicUser != "no" {
t.Fatalf("%+v %v", p, err)
}
- notFound := "Id=console.service\nLoadState=not-found\nActiveState=inactive\nRuntimeDirectory=\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\n"
+ notFound := "Id=console.service\nLoadState=not-found\nActiveState=inactive\nRuntimeDirectory=\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\nUser=\nDynamicUser=no\n"
if p, err := parseConsoleUnitProps([]byte(notFound)); err != nil || p.LoadState != "not-found" || len(p.RuntimeDirectory) != 0 {
t.Fatalf("not-found: %+v %v", p, err)
}