db forward round 1, fix 1 (Astra P1): tenants cannot reach or start db-read workers
- carlos-dbread.socket listens at /run/carlos/dbread/worker.sock, under the tree every tenant unit replaces with an empty TemporaryFileSystem. Tenants run as carlos, the uid the worker serves, so the old /run/carlos-dbread path let one start workers directly. - The socket follows the capability's dark gate: ensureSystemUnits arms it only when the installed host.env arms db reads (dbReadsSocketWanted, the same dbReadsSettings rule), and stops and disables one left armed elsewhere (CARLOS_DB_READS=0, no hibernation, host claims, no key). - The worker bounds what it writes across all files: a header whose files total more than PlanBytesFactor (2) times its restored-size cap, or whose cap is above the worker's own (its LimitFSIZE), is refused before any byte is written. Tests first: TestDBReadUnitsCarryTheSandbox (path), TestEnsureSystemUnitsKeepsTheDBReadSocketDarkWithoutTheGate, TestWorkerRefusesAPlanOverItsTotal. Two claim tests that model an armed box now model its db-read socket dark, as the gate keeps it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+276
−17
internal/dbreads/limits.go+7 −3internal/dbreads/worker.go+32 −0internal/dbreads/worker_linux.go+11 −1internal/dbreads/worker_test.go+36 −0internal/host/claimreview_test.go+8 −0internal/host/claimunit_test.go+8 −0internal/host/dbreads.go+52 −2internal/host/dbreads_test.go+83 −1internal/host/systemunits.go+27 −6internal/host/systemunits_test.go+5 −3internal/host/units/carlos-dbread.socket+7 −1
diff --git a/internal/dbreads/limits.go b/internal/dbreads/limits.go| index 7a19ca557..09a085f6a 100644 |
| --- a/internal/dbreads/limits.go |
| +++ b/internal/dbreads/limits.go |
| @@ -44,9 +44,13 @@ const ( |
| MaxJitter = 500 * time.Millisecond |
| DefaultMaxRestored int64 = 2 << 30 // CARLOS_DB_READ_MAX_BYTES |
| - MaxOutputBytes = runs.MaxOutputBytes |
| - ChunkBytes = runs.ChunkBytes |
| - ChunkEvery = runs.ChunkEvery |
| + // PlanBytesFactor bounds a plan's LTX files, all together, at this many |
| + // times the restored-size cap: the most a worker writes before it |
| + // restores (Astra round 1, finding 1). |
| + PlanBytesFactor int64 = 2 |
| + MaxOutputBytes = runs.MaxOutputBytes |
| + ChunkBytes = runs.ChunkBytes |
| + ChunkEvery = runs.ChunkEvery |
| ReadsPerBox = 2 |
| MaxConnections = 3 // two reads and one probe (carlos-dbread.socket) |
diff --git a/internal/dbreads/worker.go b/internal/dbreads/worker.go| index cc5aadf80..f8b7d88cf 100644 |
| --- a/internal/dbreads/worker.go |
| +++ b/internal/dbreads/worker.go |
| @@ -35,6 +35,11 @@ type WorkerOptions struct { |
| Self func() HelloReply |
| // Restore is dbdoor.RestoreLocal when nil. Tests replace it. |
| Restore func(ctx context.Context, c litestream.ReplicaClient, out string, target uint64) error |
| + // MaxRestored is the largest restored-size cap a header may claim: |
| + // DefaultMaxRestored when zero, and in the unit the process's own |
| + // RLIMIT_FSIZE (LimitFSIZE), which a box raising the cap raises too. The |
| + // header's files may total at most PlanBytesFactor times its cap. |
| + MaxRestored int64 |
| } |
| type frame struct { |
| @@ -65,6 +70,9 @@ func ServeWorker(conn io.ReadWriter, opt WorkerOptions) error { |
| if opt.Restore == nil { |
| opt.Restore = dbdoor.RestoreLocal |
| } |
| + if opt.MaxRestored <= 0 { |
| + opt.MaxRestored = DefaultMaxRestored |
| + } |
| ctx, cancel := context.WithCancel(context.Background()) |
| defer cancel() |
| frames := make(chan frame) |
| @@ -128,6 +136,13 @@ func ServeWorker(conn io.ReadWriter, opt WorkerOptions) error { |
| if err := json.Unmarshal(f.p, &h); err != nil || h.V != ProtocolVersion || h.Op != OpQuery { |
| return errProtocol |
| } |
| + // Every byte this worker writes is bounded before the first is |
| + // written: each file by its header size (receiveFile), and all of them |
| + // together by PlanBytesFactor times a cap no larger than the worker's |
| + // own (Astra round 1, finding 1). LimitFSIZE alone bounds one file. |
| + if err := planWithinBounds(h, opt.MaxRestored); err != nil { |
| + return end(CodeCheckFailed, err) |
| + } |
| dir, err := os.MkdirTemp(opt.Scratch, "dbread-") |
| if err != nil { |
| return err |
| @@ -289,3 +304,20 @@ func parseNetDev(s string) []string { |
| } |
| return out |
| } |
| + |
| +// planWithinBounds refuses a header whose restored-size cap is not in |
| +// (0, limit], or whose files have a negative size or total more than |
| +// PlanBytesFactor times that cap. |
| +func planWithinBounds(h planHeader, limit int64) error { |
| + if h.MaxRestored <= 0 || h.MaxRestored > limit { |
| + return fmt.Errorf("dbreads: the plan's restored-size cap %d is outside (0, %d]", h.MaxRestored, limit) |
| + } |
| + var total int64 |
| + for _, f := range h.Files { |
| + if f.Size < 0 || f.Size > PlanBytesFactor*h.MaxRestored-total { |
| + return fmt.Errorf("dbreads: the plan's files exceed %d bytes", PlanBytesFactor*h.MaxRestored) |
| + } |
| + total += f.Size |
| + } |
| + return nil |
| +} |
diff --git a/internal/dbreads/worker_linux.go b/internal/dbreads/worker_linux.go| index bcff41825..ef433bad9 100644 |
| --- a/internal/dbreads/worker_linux.go |
| +++ b/internal/dbreads/worker_linux.go |
| @@ -23,7 +23,7 @@ func RunWorker(args []string) { |
| fmt.Fprintln(os.Stderr, "db-worker: takes no arguments") |
| os.Exit(2) |
| } |
| - RunWorkerWith(WorkerOptions{Scratch: "/var/tmp"}) |
| + RunWorkerWith(WorkerOptions{Scratch: "/var/tmp", MaxRestored: fileSizeLimit()}) |
| } |
| // RunWorkerWith is RunWorker with its options supplied: the seam the root |
| @@ -81,3 +81,13 @@ func StdinConn(f *os.File, wantUID func() (uint32, error)) (net.Conn, error) { |
| } |
| return c, nil |
| } |
| + |
| +// fileSizeLimit is the unit's LimitFSIZE, the restored-size cap the box set |
| +// for its workers, or DefaultMaxRestored when the process has no limit. |
| +func fileSizeLimit() int64 { |
| + var r unix.Rlimit |
| + if err := unix.Getrlimit(unix.RLIMIT_FSIZE, &r); err != nil || r.Cur == unix.RLIM_INFINITY || r.Cur > 1<<62 { |
| + return DefaultMaxRestored |
| + } |
| + return int64(r.Cur) |
| +} |
diff --git a/internal/dbreads/worker_test.go b/internal/dbreads/worker_test.go| index 2e4882aa1..2359cae9c 100644 |
| --- a/internal/dbreads/worker_test.go |
| +++ b/internal/dbreads/worker_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/json" |
| "io" |
| "net" |
| + "os" |
| "strings" |
| "sync/atomic" |
| "testing" |
| @@ -271,3 +272,38 @@ func TestWorkerCheckFailsAMissingFile(t *testing.T) { |
| } |
| <-done |
| } |
| + |
| +// The worker bounds the bytes it will write across ALL files, not just each |
| +// file (Astra round 1, finding 1): a header whose files sum past |
| +// PlanBytesFactor times its restored-size cap, or whose cap is above the |
| +// worker's own, is refused before anything is written. LimitFSIZE bounds |
| +// one file only. |
| +func TestWorkerRefusesAPlanOverItsTotal(t *testing.T) { |
| + t.Parallel() |
| + for name, h := range map[string]planHeader{ |
| + "files past twice the cap": {V: ProtocolVersion, Op: OpQuery, Target: 3, MaxRestored: 1000, |
| + Files: []dbdoor.LTXFile{{Level: 0, MinTXID: 1, MaxTXID: 1, Size: 800}, {Level: 0, MinTXID: 2, MaxTXID: 2, Size: 800}, {Level: 0, MinTXID: 3, MaxTXID: 3, Size: 800}}}, |
| + "a cap above the worker's": {V: ProtocolVersion, Op: OpQuery, Target: 1, MaxRestored: 5000, |
| + Files: []dbdoor.LTXFile{{Level: 0, MinTXID: 1, MaxTXID: 1, Size: 10}}}, |
| + "a negative size": {V: ProtocolVersion, Op: OpQuery, Target: 2, MaxRestored: 1000, |
| + Files: []dbdoor.LTXFile{{Level: 0, MinTXID: 1, MaxTXID: 1, Size: -5}, {Level: 0, MinTXID: 2, MaxTXID: 2, Size: 10}}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + t.Parallel() |
| + scratch := t.TempDir() |
| + conn, done := workerPipe(t, WorkerOptions{Scratch: scratch, MaxRestored: 1000}) |
| + if err := writeJSONFrame(conn, frameHeader, h); err != nil { |
| + t.Fatal(err) |
| + } |
| + var end endMsg |
| + readTyped(t, conn, frameEnd, &end) |
| + if end.Code != CodeCheckFailed { |
| + t.Fatalf("end = %+v", end) |
| + } |
| + <-done |
| + if ents, _ := os.ReadDir(scratch); len(ents) != 0 { |
| + t.Fatalf("the worker wrote %d entries for a refused plan", len(ents)) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/claimreview_test.go b/internal/host/claimreview_test.go| index d30d0be44..6a5efa416 100644 |
| --- a/internal/host/claimreview_test.go |
| +++ b/internal/host/claimreview_test.go |
| @@ -36,6 +36,14 @@ func TestClaimReviewFlagOffAdoptPreservesDrift(t *testing.T) { |
| calls := 0 |
| ctl := func(...string) (string, error) { calls++; return "", nil } |
| probe := func(args ...string) (string, error) { |
| + // This box's host.env does not arm db reads, so its db-read socket |
| + // is dark (dbReadsSocketWanted), as ensureSystemUnits keeps it. |
| + if args[1] == dbReadSocketUnit { |
| + if args[0] == "is-active" { |
| + return "inactive", systemctlExit(3) |
| + } |
| + return "disabled", systemctlExit(1) |
| + } |
| if args[0] == "is-active" { |
| return "active", nil |
| } |
diff --git a/internal/host/claimunit_test.go b/internal/host/claimunit_test.go| index ecd9638f0..9a2190b5f 100644 |
| --- a/internal/host/claimunit_test.go |
| +++ b/internal/host/claimunit_test.go |
| @@ -147,6 +147,14 @@ func TestClaimControlUnitInstallers(t *testing.T) { |
| var calls []string |
| ctl := func(args ...string) (string, error) { calls = append(calls, strings.Join(args, " ")); return "", nil } |
| probe := func(args ...string) (string, error) { |
| + // host.env here does not arm db reads, so the db-read socket |
| + // is dark (dbReadsSocketWanted), as ensureSystemUnits keeps it. |
| + if args[1] == dbReadSocketUnit { |
| + if args[0] == "is-active" { |
| + return "inactive\n", systemctlExit(3) |
| + } |
| + return "disabled\n", systemctlExit(1) |
| + } |
| if args[0] == "is-active" { |
| return "active\n", nil |
| } |
diff --git a/internal/host/dbreads.go b/internal/host/dbreads.go| index 85416a670..a836646ff 100644 |
| --- a/internal/host/dbreads.go |
| +++ b/internal/host/dbreads.go |
| @@ -1,6 +1,8 @@ |
| package host |
| import ( |
| + "bufio" |
| + "bytes" |
| "context" |
| "crypto/ed25519" |
| "log" |
| @@ -19,8 +21,10 @@ import ( |
| ) |
| const ( |
| - dbReadSocketUnit = "carlos-dbread.socket" |
| - dbReadSocketPath = "/run/carlos-dbread/worker.sock" |
| + dbReadSocketUnit = "carlos-dbread.socket" |
| + // dbReadSocketPath is under /run/carlos, the tree every tenant unit hides |
| + // (carlos-dbread.socket says why). |
| + dbReadSocketPath = "/run/carlos/dbread/worker.sock" |
| dbReadMaxBytesEnv = "CARLOS_DB_READ_MAX_BYTES" |
| dbReadsSwitchEnv = "CARLOS_DB_READS" |
| ) |
| @@ -145,3 +149,49 @@ func armDBReads(hib activator.Config) { |
| go a.Run(ctx, dbReadsNudge) |
| log.Printf("agent: db reads armed (region %s)", env.region) |
| } |
| + |
| +// dbReadsHostEnvKeys are the host.env settings dbReadsSettings reads. |
| +var dbReadsHostEnvKeys = []string{"CARLOS_HIBERNATE_BUCKET", "CARLOS_REGION", "CARLOS_RELEASE_PUBKEY", dbReadsSwitchEnv, "CARLOS_HOST_CLAIM", dbReadMaxBytesEnv} |
| + |
| +// dbReadsSocketWanted is root's half of the dark gate (Astra round 1, |
| +// finding 1): the adopt pass arms carlos-dbread.socket only when the box's |
| +// installed host.env, the file the agent's own environment comes from, |
| +// arms db reads by the same rule the capability follows (dbReadsSettings). |
| +// A host.env it cannot read or parse keeps the socket dark. why is the |
| +// reason when it is not wanted. |
| +func dbReadsSocketWanted(hostEnv string) (bool, string) { |
| + raw, err := readClaimUnitFile(hostEnv) |
| + if err != nil { |
| + return false, "host.env: " + err.Error() |
| + } |
| + values := map[string]string{} |
| + for _, k := range dbReadsHostEnvKeys { |
| + values[k] = "" |
| + } |
| + scan := bufio.NewScanner(bytes.NewReader(raw)) |
| + for scan.Scan() { |
| + line := strings.TrimSpace(scan.Text()) |
| + if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") { |
| + continue |
| + } |
| + key, v, ok := strings.Cut(line, "=") |
| + key, v = strings.TrimSpace(key), strings.TrimSpace(v) |
| + if _, known := values[key]; !ok || !known { |
| + continue |
| + } |
| + if len(v) >= 2 && ((v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'')) { |
| + v = v[1 : len(v)-1] |
| + } |
| + if strings.ContainsAny(v, "\\\"'\x00\r\n") { |
| + return false, "host.env: unsupported value for " + key |
| + } |
| + values[key] = v |
| + } |
| + if err := scan.Err(); err != nil { |
| + return false, "host.env: " + err.Error() |
| + } |
| + if _, why := dbReadsSettings(func(k string) string { return values[k] }); why != "" { |
| + return false, why |
| + } |
| + return true, "" |
| +} |
diff --git a/internal/host/dbreads_test.go b/internal/host/dbreads_test.go| index 80f85314a..620804c23 100644 |
| --- a/internal/host/dbreads_test.go |
| +++ b/internal/host/dbreads_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "crypto/ed25519" |
| "crypto/rand" |
| "encoding/base64" |
| + "fmt" |
| "os" |
| "path/filepath" |
| "slices" |
| @@ -99,7 +100,19 @@ func unitLines(t *testing.T, name string) []string { |
| func TestDBReadUnitsCarryTheSandbox(t *testing.T) { |
| t.Parallel() |
| sock := unitLines(t, "carlos-dbread.socket") |
| - for _, want := range []string{"ListenStream=/run/carlos-dbread/worker.sock", "SocketUser=carlos", "SocketMode=0600", "Accept=yes", "MaxConnections=3"} { |
| + // The socket lives under /run/carlos, which every tenant unit replaces |
| + // with an empty TemporaryFileSystem: tenants run as carlos, the uid the |
| + // worker serves, so a path they could see would let them start workers |
| + // directly (Astra round 1, finding 1). |
| + if !strings.HasPrefix(dbReadSocketPath, "/run/carlos/") { |
| + t.Errorf("the worker socket %s is outside the tree tenant units hide", dbReadSocketPath) |
| + } |
| + for _, tenant := range []string{"carlos-instance@.service", "carlos-instance-cmd@.service"} { |
| + if !slices.Contains(unitLines(t, tenant), "TemporaryFileSystem=/run/carlos:ro") { |
| + t.Errorf("%s no longer hides /run/carlos", tenant) |
| + } |
| + } |
| + for _, want := range []string{"ListenStream=" + dbReadSocketPath, "SocketUser=carlos", "SocketMode=0600", "Accept=yes", "MaxConnections=3"} { |
| if !slices.Contains(sock, want) { |
| t.Errorf("the socket lacks %q", want) |
| } |
| @@ -130,10 +143,25 @@ func TestDBReadUnitsCarryTheSandbox(t *testing.T) { |
| } |
| } |
| +// dbReadsHostEnv writes etc/carlos/host.env with the settings that arm the |
| +// db-reads gate (spec §7.1), plus extra lines. |
| +func dbReadsHostEnv(t *testing.T, etc string, extra ...string) { |
| + t.Helper() |
| + pub, _, _ := ed25519.GenerateKey(rand.Reader) |
| + lines := append([]string{"CARLOS_HIBERNATE_BUCKET=data-uk", "CARLOS_REGION=uk", "CARLOS_RELEASE_PUBKEY=" + base64.StdEncoding.EncodeToString(pub)}, extra...) |
| + if err := os.MkdirAll(filepath.Join(etc, "carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(etc, "carlos", "host.env"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| func TestEnsureSystemUnitsInstallsTheDBReadUnits(t *testing.T) { |
| t.Parallel() |
| etc := t.TempDir() |
| os.MkdirAll(filepath.Join(etc, "systemd", "system"), 0o755) |
| + dbReadsHostEnv(t, etc) |
| var calls []string |
| systemctl := func(args ...string) (string, error) { |
| calls = append(calls, strings.Join(args, " ")) |
| @@ -170,3 +198,57 @@ func TestEnsureSystemUnitsInstallsTheDBReadUnits(t *testing.T) { |
| t.Fatal("a worker service was started") |
| } |
| } |
| + |
| +// The socket follows the capability's dark gate (Astra round 1, finding 1): |
| +// a box whose host.env does not arm db reads (no hibernation, CARLOS_DB_READS=0, |
| +// host claims, no release key, or no host.env) has no listening worker |
| +// socket. The adopt pass never arms it there, and stops and disables one |
| +// left armed. |
| +func TestEnsureSystemUnitsKeepsTheDBReadSocketDarkWithoutTheGate(t *testing.T) { |
| + t.Parallel() |
| + for name, env := range map[string][]string{ |
| + "no host.env": nil, |
| + "CARLOS_DB_READS=0": {"CARLOS_DB_READS=0"}, |
| + "host claims": {"CARLOS_HOST_CLAIM=1"}, |
| + "no hibernation": {"CARLOS_HIBERNATE_BUCKET="}, |
| + } { |
| + for _, armed := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("%s/armed=%v", name, armed), func(t *testing.T) { |
| + t.Parallel() |
| + etc := t.TempDir() |
| + os.MkdirAll(filepath.Join(etc, "systemd", "system"), 0o755) |
| + if env != nil { |
| + dbReadsHostEnv(t, etc, env...) |
| + } |
| + var calls []string |
| + systemctl := func(args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + return "", nil |
| + } |
| + probe := func(args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + on := armed && args[1] == dbReadSocketUnit |
| + switch { |
| + case args[0] == "is-active" && on: |
| + return "active\n", nil |
| + case args[0] == "is-active": |
| + return "inactive\n", systemctlExit(3) |
| + case on: |
| + return "enabled\n", nil |
| + } |
| + return "disabled\n", systemctlExit(1) |
| + } |
| + ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), systemctl, probe, t.Logf) |
| + joined := strings.Join(calls, "\n") |
| + for _, c := range calls { |
| + if (strings.HasPrefix(c, "start ") || strings.HasPrefix(c, "enable ")) && strings.Contains(c, dbReadSocketUnit) { |
| + t.Fatalf("the dark socket was armed: %q\n%s", c, joined) |
| + } |
| + } |
| + if disabled := strings.Contains(joined, "disable --now "+dbReadSocketUnit); disabled != armed { |
| + t.Fatalf("armed %v, disabled %v:\n%s", armed, disabled, joined) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go| index 3cb8a949d..0d7972188 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -5,6 +5,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "slices" |
| "strings" |
| ) |
| @@ -20,9 +21,10 @@ const systemRecoverUnit = "carlos-system-recover.service" |
| const instanceControlSocket = "carlos-instance-control.socket" |
| // ensureSystemArmed is what ensureSystemUnits arms (systemctlPlan: enable, |
| -// and start for the path unit and the sockets). The claim census reads the |
| -// same list (claimCensusEnabledUnits), so a unit armed here always has its |
| -// install links classified there. |
| +// and start for the path unit and the sockets); carlos-dbread.socket only |
| +// where host.env arms db reads (dbReadsSocketWanted). The claim census reads |
| +// the same list (claimCensusEnabledUnits), so a unit armed here always has |
| +// its install links classified there. |
| var ensureSystemArmed = []string{systemUpdatePathUnit, systemRecoverUnit, instanceControlSocket, dbReadSocketUnit} |
| // carlos-dbread.socket and its service template are the db-read worker's |
| @@ -86,8 +88,12 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st |
| // path unit's: the same silent-systemctl-vs-unarmed-unit question, one |
| // more unit wide (design §5.2). |
| ctlActiveOut, ctlActiveErr := probe("is-active", instanceControlSocket) |
| - // And the db-read worker's socket (db region forward spec §8.3). |
| + // And the db-read worker's socket (db region forward spec §8.3), which |
| + // is armed only where host.env arms db reads: elsewhere it must not |
| + // listen at all, so its enablement is asked too. |
| dbrActiveOut, dbrActiveErr := probe("is-active", dbReadSocketUnit) |
| + dbrEnabledOut, _ := probe("is-enabled", dbReadSocketUnit) |
| + dbrWant, dbrWhy := dbReadsSocketWanted(filepath.Join(etcDir, "carlos", "host.env")) |
| // The is-enabled error is dropped on purpose: its cases are the words |
| // parseIsEnabled reads, and "no such unit file" is a perfectly good |
| // "not enabled" on the box we are here to fix. |
| @@ -121,7 +127,11 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st |
| return |
| } |
| controlChanged := settingsErr == nil && (claimSettings.enabled || bytes.Contains(installed, []byte(claimControlEnvironment))) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings))) |
| - if !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && *dbrActive { |
| + dbrEnabled := parseIsEnabled(dbrEnabledOut) |
| + // Dark: neither listening nor enabled for the next boot. |
| + dbrDark := !*dbrActive && (dbrEnabled == nil || !*dbrEnabled) |
| + dbrSettled := (dbrWant && *dbrActive) || (!dbrWant && dbrDark) |
| + if !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled { |
| return |
| } |
| if err := os.MkdirAll(unitDir, 0o755); err != nil { |
| @@ -144,7 +154,18 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st |
| return |
| } |
| } |
| - for _, args := range systemctlPlan(ensureSystemArmed) { |
| + arm := ensureSystemArmed |
| + if !dbrWant { |
| + arm = slices.DeleteFunc(slices.Clone(arm), func(u string) bool { return u == dbReadSocketUnit }) |
| + if !dbrDark { |
| + logf("adopt: system units: db reads are not armed here (%s); stopping %s", dbrWhy, dbReadSocketUnit) |
| + if _, err := systemctl("disable", "--now", dbReadSocketUnit); err != nil { |
| + logf("adopt: system units: systemctl disable --now %s: %v", dbReadSocketUnit, err) |
| + return |
| + } |
| + } |
| + } |
| + for _, args := range systemctlPlan(arm) { |
| if _, err := systemctl(args...); err != nil { |
| logf("adopt: system units: systemctl %s: %v", strings.Join(args, " "), err) |
| return |
diff --git a/internal/host/systemunits_test.go b/internal/host/systemunits_test.go| index 770e07f1c..08b60928c 100644 |
| --- a/internal/host/systemunits_test.go |
| +++ b/internal/host/systemunits_test.go |
| @@ -51,9 +51,11 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) { |
| if strings.Contains(joined, "start carlos-system-recover.service") || strings.Contains(joined, "start carlos-system-update.service") { |
| t.Fatal("a service was started") |
| } |
| - // All present and armed: no writes, no systemctl beyond the four checks |
| + // All present and armed: no writes, no systemctl beyond the five checks |
| // (is-active x3: the self-update path unit, the control socket and the |
| - // db-read socket, plus is-enabled). |
| + // db-read socket; is-enabled x2: the recover service and the db-read |
| + // socket). The db-read socket is wanted because host.env arms db reads. |
| + dbReadsHostEnv(t, etc) |
| calls = nil |
| probe2 := func(args ...string) (string, error) { |
| calls = append(calls, strings.Join(args, " ")) |
| @@ -66,7 +68,7 @@ func TestEnsureSystemUnitsInstallsAndArmsWhatIsMissing(t *testing.T) { |
| return "", nil |
| } |
| ensureSystemUnits(etc, lockPath, systemctl, probe2, t.Logf) |
| - if len(calls) != 4 { |
| + if len(calls) != 5 { |
| t.Fatalf("an armed box got %v", calls) |
| } |
| } |
diff --git a/internal/host/units/carlos-dbread.socket b/internal/host/units/carlos-dbread.socket| index 4bfb12f53..09f1d5a72 100644 |
| --- a/internal/host/units/carlos-dbread.socket |
| +++ b/internal/host/units/carlos-dbread.socket |
| @@ -3,11 +3,17 @@ |
| # its own. Each connection starts one carlos-dbread@ instance with the |
| # connection as its stdin and stdout. Three connections at most: two reads |
| # and the readiness probe (spec §7.1). |
| +# |
| +# It lives under /run/carlos because every tenant unit hides that tree |
| +# (TemporaryFileSystem=/run/carlos:ro): tenants run as carlos too, the one |
| +# uid the worker serves, so they must not be able to see this path. Only |
| +# ensureSystemUnits arms it, and only on a box whose host.env arms db reads; |
| +# elsewhere nothing listens (Astra round 1, finding 1). |
| [Unit] |
| Description=carlos db-read worker socket |
| [Socket] |
| -ListenStream=/run/carlos-dbread/worker.sock |
| +ListenStream=/run/carlos/dbread/worker.sock |
| SocketUser=carlos |
| SocketGroup=carlos |
| SocketMode=0600 |