Add root group maintenance permit, revoke and status verbs
Serve the attended operator through the existing system command family. Share permit validation with the mutation guard, serialize with apply, and replace permits durably through protected directory descriptors. Report bounded local process, artifact, permit and health observations without cloud calls. Preserve consumed-action markers on revocation. Targeted tests, six mutation checks, build, vet and cross-builds pass. Controller census and independent review remain pending.
internal/host/group_maintenance.go+44 −21internal/host/group_maintenance_verbs.go+272 −0internal/host/group_maintenance_verbs_linux.go+208 −0internal/host/group_maintenance_verbs_other.go+19 −0internal/host/group_maintenance_verbs_test.go+425 −0system.go+3 −1system_test.go+9 −0
Intent
<task-notification> <task-id>bscc1ahsb</task-id> <tool-use-id>toolu_01FvhX2tAioLmzxfEBjSsVUi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/bscc1ahsb.output</output-file> <status>completed</status> <summary>Background command "git rev-parse HEAD > .superpowers/sdd/2026-11-04-region-ha-p3b-group/b1.base; .superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ad5a7e36164d8e043</task-id> <tool-use-id>toolu_01G1u46iLCqam6sN82rN1oMW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/ad5a7e36164d8e043.output</output-file> <status>completed</status> <summary>Agent "Review B1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ The agent installs from the regional `debian_arm64` bucket and runs `enable --now` plus an `is-active` check. See infra/modules/region-host/group-init.sh.tftpl:142-149, which matches the scanner/pdf pattern (scanner-init.sh.tftpl:33-37, pdf-init.sh.tftpl:21-25). - ✅ Boot ordering. I read the whole template once. Agent install (L142-149) comes after: - the apt timer/service masks (L80-81) - `APT::Periodic::Enable "0"` - the `Restart=no` drop-in `50-group.conf` (L82-96) - the protected `/var/lib/carlos-group-boot` 0700 staging directory (L20-46) - the metadata firewall being loaded and persisted, with `nft list table` checked (L104-140) It comes before chrony, the bootstrap fetch, digest verification and `systemctl start carlos-edge`. The digest check still sits right before each bootstrap execution, and the 022 host-env subshell is untouched. Root (uid 0) is allowed past the IMDS fence, so the agent keeps its credentials. Session shells running as `ssm-user` stay fenced. - ✅ A failed install stops the boot. `set -eu` stops it before edge starts, so the initial hook reaches ABANDON at 900s. The choice is justified in the report and README.md:144-148, and is consistent with "initial failed boots retain the separate 900s default ABANDON". - ✅ The module creates no State Manager association. README.md:161-164 forbids `AWS-UpdateSSMAgent`, patch baselines and patch/reboot jobs, and no apt source is added for the agent. - ✅ `AmazonSSMManagedInstanceCore` attachment (main.tf:454) and the parameter Denies are unchanged. The diff does not touch main.tf or group_iam.tf. - ✅ Operator writes are exactly UpdateASG, EnterStandby, ExitStandby and CompleteLifecycleAction, on the exact group ARN with the same `carlos:deployment`/`carlos:region` tags as the boot adapter (group_operator.tf:31-39 vs group_iam.tf:79-84). The boot adapter uses a wildcard UUID; the operator's exact ARN is narrower. The ASG carries these tags (group.tf:19-23, 263-268). - ✅ The seven describes are on `*` with a region condition and the required comment (group_operator.tf:41-47). - ✅ The `return_member` comment says IAM cannot bind iid, hook, CONTINUE-only or transaction (group_operator.tf:23-25). - ✅ No forbidden actions: none of TerminateInstances, TerminateInstanceInAutoScalingGroup, SetDesiredCapacity, SetInstanceHealth, SendCommand or GetParameter*. A test asserts this (group_operator.tftest.hcl:166-171). - ✅ The document input defaults to the regional AWS-owned `AWS-StartNonInteractiveCommand`. The regex rejects wildcards. A precondition limits it to the AWS default or a document owned by this account in this region. Tests cover wildcard, empty, region, account, partition, `AWS-StartSSHSession` and wrong resource type. - ✅ StartSession has separate statements for the instance resource (group tag plus `ssm:SessionDocumentAccessCheck`) and the document resource (group_operator.tf:50-68). This is the correct shape: IAM must allow every resource in the request, and AWS-owned documents carry no group tag. Requiring the access check means an omitted document name falls back to `SSM-SessionManagerRunShell`, which is not granted, so the request is denied. - ✅ TerminateSession and ResumeSession apply only to the caller's own sessions, via `ssm:resourceTag/aws:ssmmessages:session-id` = `${aws:userid}` on `session/*` (group_operator.tf:70-77). This is AWS's documented role/federated pattern, and `$${...}` renders as the literal IAM variable. - ✅ Fixed mode is unchanged. The template is only rendered in group mode. The new variable defaults to null, the output is `""` behind `!local.group_enabled`, and the precondition short-circuits. fixed_state_unchanged.tftest.hcl asserts the empty output, and no fixed resource or wire field changed. - ✅ I ran `go test ./internal/provision -run TestRegionGroup` myself, because those tests read the template and the implementer did not run them. UserDataSize, UserDataOpenTofu and PythonGuards all PASS. - ✅ I ran `python3 -m unittest scripts.region_group_ssm_boot_test`: OK. - ⚠️ I could not run `TestHairpinControlGroupDropIn`. The sandbox's Go cache is read-only for that package ("setup failed"), so this is unverified. - ⚠️ `Bool` vs `BoolIfExists` on `ssm:SessionDocumentAccessCheck` (group_operator.tf:58). AWS's CLI example uses `BoolIfExists`, as I recall it; I could not fetch the page. If the key is missing when the caller passes `--document-name` explicitly, every operator session would be denied. That fails closed, so it is safe, but it would break the channel. Only the live probe can settle it. - ⚠️ Whether `aws:ResourceTag/aws:autoscaling:groupName` (rather than the documented `ssm:resourceTag/...`) is evaluated for StartSession on EC2 instance ARNs cannot be confirmed without a live call. This also fails closed. - ⚠️ The report says dpkg resets its umask to 022 internally. It cites dpkg source; I did not verify it. The low-risk case is fine: the agent runs as root either way. ### Strengths - The install sits after every OS mask, the restart guard and the IMDS fence, and before any bootstrap bytes are fetched or run. A failed install cannot leave a member serving without its maintenance channel. - The document pin is defended at three layers: input regex, precondition, and the access check that stops the default-shell fallback. - The tests check exact equality on the whole policy, not just whether actions appear. The fake-command Python test actually runs the install fragment and checks that each failure stops before edge starts. - The report is candid. It raises `ssmmessages:OpenDataChannel` and the OpenTofu 1.12 vs 1.13 mismatch instead of quietly widening the policy or rewriting fixtures. ### Issues **Critical:** none. **Important:** none. **Minor** 1. **The README's termination claim is too strong.** - Where: README.md:159 and group_operator.tf:33. - What: the README says "Termination requires separate fault authority", but UpdateAutoScalingGroup on the group ARN can lower min/max/desired or set `MaxInstanceLifetime`. Either one makes AWS terminate members. - Why it matters: the plan grants UpdateASG on purpose, but the README sentence overstates the guarantee. - Fix: reword it ("this policy grants no direct termination action; UpdateAutoScalingGroup can still shrink the group, and `return_member` must refuse that"). Optionally add `NumericEquals autoscaling:MaxSize = N` and `NumericGreaterThanEquals autoscaling:MinSize = N-1` conditions; desired capacity has no condition key. 2. **The new Python test crashes when `TMPDIR` is unset.** - Where: scripts/region_group_ssm_boot_test.py:36. - What: it uses `os.environ['TMPDIR']`. I confirmed it fails with `KeyError: 'TMPDIR'`. - Why it matters: the sibling tests use `os.environ.get('TMPDIR')` (region_group_boot_umask_test.py:32, check_region_group_plan_test.py:203), so this one breaks where they don't. - Fix: use `.get('TMPDIR')`. 3. **The agent package is unpinned and its signature is not checked.** - Where: group-init.sh.tftpl:144-146. - What: it fetches `latest` over HTTPS with no `.sig`/GPG check, while the bootstrap on the same root boot path is digest-pinned. - Why it matters: ruling R2 and the scanner/pdf precedent sanction this, so it is acceptable. But members can now boot with different agent versions. With fail-boot, a broken AWS release or an outage of the regional bucket turns every launch into an ABANDON/replace loop. - Fix: record it as an accepted risk on the census claim, or later pin a version path plus its sha256. 4. **The operator policy may be missing a transport permission.** - Where: the operator policy omits `ssmmessages:OpenDataChannel`, as the implementer flagged. - What: if AWS enforces it for users starting sessions, the root channel fails closed. - Why it matters: the session channel would not work at the live step. - Fix: the controller should decide before the first live probe. Keep it out of this task; the exact set was in the brief. ### Assessment **Task quality:** Approved The boot ordering, fail-closed behavior, exact least-privilege policy and unchanged fixed mode all match the brief and the plan's binding constraints. The remaining items are wording, test hygiene, and IAM semantics that can only be confirmed on the planned live probe, and all of those fail closed. Separately: during my review the shared worktree gained uncommitted changes I did not make: `internal/host/group_maintenance.go` and `system.go` modified, `internal/host/group_maintenance_verbs_test.go` untracked. Another agent, probably B2, is working there now. I left them alone.</result> <usage><subagent_tokens>97149</subagent_tokens><tool_uses>20</tool_uses><duration_ms>248012</duration_ms></usage> </task-notification>
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go| index 32747fd83..081506c8b 100644 |
| --- a/internal/host/group_maintenance.go |
| +++ b/internal/host/group_maintenance.go |
| @@ -100,14 +100,9 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s |
| if err != nil { |
| return errors.Join(errGroupMaintenance, err) |
| } |
| - var p groupMaintenancePermit |
| - if decodeMaintenancePermit(b, &p) != nil || p.V != 1 || p.Account != c.Account || p.Region != c.AWSRegion || p.Group != c.Group || p.Instance != c.InstanceID || p.BootID != c.BootID || p.ConfigDigest != c.ConfigDigest || !groupTransactionID.MatchString(p.Transaction) || p.Phase != "mutation" || !a.ops.now().Before(time.Unix(p.Expires, 0)) || !groupDigest(p.OldSHA256) || !groupDigest(p.NewSHA256) { |
| - return errGroupMaintenance |
| - } |
| - switch p.Action { |
| - case "apply", "rollback", "repair", "install": |
| - default: |
| - return errGroupMaintenance |
| + p, err := a.validateMaintenancePermit(b, c) |
| + if err != nil { |
| + return err |
| } |
| if slices.Contains(alternatives, p.Action) { |
| action = p.Action |
| @@ -115,21 +110,11 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s |
| if action != "check" && action != p.Action && !(action == "rollback" && p.AllowRollback && p.Action == "apply") { |
| return errGroupMaintenance |
| } |
| - if g.permit != nil && *g.permit != p { |
| - return errGroupMaintenance |
| - } |
| - // The installed binary must still be one of the exact operator-authorized |
| - // artifacts. The normal release verifier independently verifies new code. |
| - if !groupArtifactHolds(systemBinaryPath(a.optDir), p.OldSHA256) && !groupArtifactHolds(systemBinaryPath(a.optDir), p.NewSHA256) { |
| - return errGroupMaintenance |
| + if err := a.validateMaintenanceArtifact(p); err != nil { |
| + return err |
| } |
| if action == "check" { |
| - if !g.used[p.Action] { |
| - if _, err := os.Lstat(filepath.Join(g.dir, "used-"+p.Transaction+"-"+p.Action)); !errors.Is(err, os.ErrNotExist) { |
| - return errGroupMaintenance |
| - } |
| - } |
| - return nil |
| + return a.maintenanceUnconsumed(p) |
| } |
| if g.used[action] { |
| return a.clearGroupHairpin() |
| @@ -144,6 +129,44 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s |
| g.permit = &p |
| return a.clearGroupHairpin() |
| } |
| + |
| +// The operator writer and the mutation guard use the same field checks. |
| +func (a *systemApplier) validateMaintenancePermit(b []byte, c *hostenv.GroupConfig) (groupMaintenancePermit, error) { |
| + var p groupMaintenancePermit |
| + if decodeMaintenancePermit(b, &p) != nil || p.V != 1 || p.Account != c.Account || p.Region != c.AWSRegion || p.Group != c.Group || p.Instance != c.InstanceID || p.BootID != c.BootID || p.ConfigDigest != c.ConfigDigest || !groupTransactionID.MatchString(p.Transaction) || p.Phase != "mutation" || !a.ops.now().Before(time.Unix(p.Expires, 0)) || !groupDigest(p.OldSHA256) || !groupDigest(p.NewSHA256) { |
| + return p, errGroupMaintenance |
| + } |
| + switch p.Action { |
| + case "apply", "rollback", "repair", "install": |
| + default: |
| + return p, errGroupMaintenance |
| + } |
| + return p, nil |
| +} |
| + |
| +// The installed binary must be one of the exact operator-authorized artifacts. |
| +// The release verifier independently verifies new code before installation. |
| +func (a *systemApplier) validateMaintenanceArtifact(p groupMaintenancePermit) error { |
| + g := a.maintenance() |
| + if g.permit != nil && *g.permit != p { |
| + return errGroupMaintenance |
| + } |
| + if !groupArtifactHolds(systemBinaryPath(a.optDir), p.OldSHA256) && !groupArtifactHolds(systemBinaryPath(a.optDir), p.NewSHA256) { |
| + return errGroupMaintenance |
| + } |
| + return nil |
| +} |
| + |
| +func (a *systemApplier) maintenanceUnconsumed(p groupMaintenancePermit) error { |
| + g := a.maintenance() |
| + if !g.used[p.Action] { |
| + if _, err := os.Lstat(filepath.Join(g.dir, "used-"+p.Transaction+"-"+p.Action)); !errors.Is(err, os.ErrNotExist) { |
| + return errGroupMaintenance |
| + } |
| + } |
| + return nil |
| +} |
| + |
| func (a *systemApplier) groupTarget(path string, rollback bool) error { |
| if !groupMarkerPresent(a.etcDir) { |
| return nil |
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go| new file mode 100644 |
| index 000000000..f29cc3523 |
| --- /dev/null |
| +++ b/internal/host/group_maintenance_verbs.go |
| @@ -0,0 +1,272 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/lbhealth" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke} |
| +Root only, on a group member. Use through the attended Session Manager operator. |
| + permit Read at most 4096 bytes of permit JSON from stdin and install it. |
| + revoke Remove the permit. Keep all consumed-action records. |
| + status Print one v1 JSON object, at most 8192 bytes. Make one local health GET. |
| +Status is local evidence, not proof of fresh admission or role publication. |
| +The operator must also check the published edges object for this process. |
| +Exit codes: 0 success or help, 1 refused or failed, 2 invalid arguments. |
| +Errors go to stderr, prefixed with "group-maintenance:". A held apply lock |
| +refuses the command. Unknown status fields are null or state "unknown". |
| +` |
| + |
| +// RunGroupMaintenance returns an exit code so command errors never log.Fatal |
| +// inside tests. No store, credentials provider or host.env is opened here. |
| +func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int { |
| + if len(args) == 1 && (args[0] == "help" || args[0] == "-h" || args[0] == "--help") { |
| + if _, err := io.WriteString(out, groupMaintenanceHelp); err != nil { |
| + return 1 |
| + } |
| + return 0 |
| + } |
| + if len(args) != 1 || (args[0] != "permit" && args[0] != "revoke" && args[0] != "status") { |
| + fmt.Fprint(stderr, groupMaintenanceHelp) |
| + return 2 |
| + } |
| + cmd := groupMaintenanceCommand{ |
| + a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), ops: productionSysOps()}, |
| + euid: os.Geteuid, root: "/", edge: maintenanceEdgeProcess, |
| + client: maintenanceHealthClient(nil), |
| + } |
| + if err := cmd.run(context.Background(), args[0], in, out); err != nil { |
| + fmt.Fprintf(stderr, "group-maintenance: %v\n", err) |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| +type groupMaintenanceCommand struct { |
| + a *systemApplier |
| + euid func() int |
| + // root anchors protected directory traversal. Production always uses /. |
| + root string |
| + edge func(context.Context) (int, string, error) |
| + client *http.Client |
| + rename func(int, string, int, string) error |
| +} |
| + |
| +func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.Reader, out io.Writer) error { |
| + if cmd.euid() != 0 { |
| + return errors.New("root required") |
| + } |
| + c, err := cmd.a.maintenanceConfig() |
| + if err != nil { |
| + return err |
| + } |
| + if c == nil { |
| + return errors.New("group marker required") |
| + } |
| + if verb != "permit" && verb != "revoke" && verb != "status" { |
| + return errors.New("unknown operation") |
| + } |
| + // Use the same lock and refusal behavior as system apply. Refuse before |
| + // reading stdin or probing the edge when an apply is already in progress. |
| + if err = os.MkdirAll(cmd.a.rootDir(), 0755); err != nil { |
| + return err |
| + } |
| + lock, err := openMaintenanceLock(cmd.a.lockPath()) |
| + if err != nil { |
| + return err |
| + } |
| + defer lock.Close() |
| + if err = flockExclusiveNonblock(lock); err != nil { |
| + return errors.New("apply lock busy") |
| + } |
| + // Check again under the mutation lock, and discard process-local permits. |
| + cmd.a.resetGroupMaintenance() |
| + c, err = cmd.a.maintenanceConfig() |
| + if err != nil { |
| + return err |
| + } |
| + if c == nil { |
| + return errors.New("group marker required") |
| + } |
| + var body []byte |
| + var permit groupMaintenancePermit |
| + if verb == "permit" { |
| + body, err = io.ReadAll(io.LimitReader(in, 4097)) |
| + if err != nil { |
| + return err |
| + } |
| + permit, err = cmd.a.validateMaintenancePermit(body, c) |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + g := cmd.a.maintenance() |
| + dir, err := openMaintenanceDirectory(cmd.root, g.dir, g.owner, verb == "permit") |
| + if err != nil && !(errors.Is(err, os.ErrNotExist) && verb != "permit") { |
| + return err |
| + } |
| + if dir != nil { |
| + defer dir.Close() |
| + } |
| + switch verb { |
| + case "permit": |
| + if err = cmd.a.validateMaintenanceArtifact(permit); err != nil { |
| + return err |
| + } |
| + if err = cmd.a.maintenanceUnconsumed(permit); err != nil { |
| + return err |
| + } |
| + return replaceMaintenancePermit(dir, body, g.owner, cmd.rename) |
| + case "revoke": |
| + if dir == nil { |
| + return nil |
| + } |
| + return revokeMaintenancePermit(dir) |
| + default: |
| + return cmd.status(ctx, c, dir != nil, out) |
| + } |
| +} |
| + |
| +type groupMaintenanceStatus struct { |
| + V int `json:"v"` |
| + Instance string `json:"iid"` |
| + BootID string `json:"boot_id"` |
| + Account string `json:"account"` |
| + Region string `json:"region"` |
| + Group string `json:"group"` |
| + ConfigDigest string `json:"config_digest"` |
| + BoxRef string `json:"box_ref"` |
| + Edge maintenanceProcessStatus `json:"edge"` |
| + BinarySHA256 *string `json:"binary_sha256"` |
| + BinaryError *string `json:"binary_error"` |
| + Permit maintenancePermitStatus `json:"permit"` |
| + Health maintenanceHealthStatus `json:"health"` |
| +} |
| +type maintenanceProcessStatus struct { |
| + State string `json:"state"` |
| + PID *int `json:"pid"` |
| + StartTime *string `json:"start_time"` |
| + Identity *string `json:"identity"` |
| + Error *string `json:"error"` |
| +} |
| +type maintenancePermitStatus struct { |
| + State string `json:"state"` |
| + Transaction *string `json:"transaction"` |
| + Action *string `json:"action"` |
| + Expires *int64 `json:"expires"` |
| + Consumed *bool `json:"consumed"` |
| + Error *string `json:"error"` |
| +} |
| +type maintenanceHealthStatus struct { |
| + State string `json:"state"` |
| + Code *int `json:"code"` |
| + Error *string `json:"error"` |
| +} |
| + |
| +func maintenanceError(err error) *string { |
| + if err == nil { |
| + return nil |
| + } |
| + s := err.Error() |
| + if len(s) > 256 { |
| + s = s[:256] |
| + } |
| + return &s |
| +} |
| +func maintenanceHealthClient(transport http.RoundTripper) *http.Client { |
| + if transport == nil { |
| + transport = &http.Transport{Proxy: nil, DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, DisableKeepAlives: true} |
| + } |
| + return &http.Client{Transport: transport, Timeout: time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| +} |
| +func (cmd *groupMaintenanceCommand) status(ctx context.Context, c *hostenv.GroupConfig, hasDir bool, out io.Writer) error { |
| + s := groupMaintenanceStatus{V: 1, Instance: c.InstanceID, BootID: c.BootID, Account: c.Account, Region: c.AWSRegion, Group: c.Group, ConfigDigest: c.ConfigDigest, BoxRef: groupReferenceOf(c.Account, c.InstanceID), Permit: maintenancePermitStatus{State: "absent"}, Health: maintenanceHealthStatus{State: "unknown"}, Edge: maintenanceProcessStatus{State: "unknown"}} |
| + if hasDir { |
| + g := cmd.a.maintenance() |
| + b, err := g.read(filepath.Join(g.dir, "permit.json"), g.owner, 0600) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + case err != nil: |
| + s.Permit.State = "unknown" |
| + s.Permit.Error = maintenanceError(err) |
| + default: |
| + var p groupMaintenancePermit |
| + if err = decodeMaintenancePermit(b, &p); err != nil || !groupTransactionID.MatchString(p.Transaction) || (p.Action != "apply" && p.Action != "rollback" && p.Action != "repair" && p.Action != "install") { |
| + s.Permit.State = "unknown" |
| + s.Permit.Error = maintenanceError(errGroupMaintenance) |
| + } else { |
| + s.Permit.State = "present" |
| + s.Permit.Transaction = &p.Transaction |
| + s.Permit.Action = &p.Action |
| + s.Permit.Expires = &p.Expires |
| + _, err = os.Lstat(filepath.Join(g.dir, "used-"+p.Transaction+"-"+p.Action)) |
| + if err == nil || errors.Is(err, os.ErrNotExist) { |
| + used := err == nil |
| + s.Permit.Consumed = &used |
| + } else { |
| + s.Permit.Error = maintenanceError(err) |
| + } |
| + } |
| + } |
| + } |
| + digest, err := maintenanceBinaryDigest(systemBinaryPath(cmd.a.optDir)) |
| + if err == nil { |
| + s.BinarySHA256 = &digest |
| + } else { |
| + s.BinaryError = maintenanceError(err) |
| + } |
| + pid, start, processErr := cmd.edge(ctx) |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1"+lbhealth.Path, nil) |
| + if err != nil { |
| + return err |
| + } |
| + resp, err := cmd.client.Do(req) |
| + if err != nil { |
| + s.Health.Error = maintenanceError(err) |
| + } else { |
| + resp.Body.Close() |
| + s.Health.Code = &resp.StatusCode |
| + s.Health.State = "unhealthy" |
| + if resp.StatusCode == http.StatusOK { |
| + s.Health.State = "healthy" |
| + } |
| + } |
| + // A health response from a process that changed during the probe cannot |
| + // establish readiness for the start identity returned to the operator. |
| + afterPID, afterStart, afterErr := cmd.edge(ctx) |
| + if processErr == nil && afterErr == nil && pid > 0 && start != "" && pid == afterPID && start == afterStart { |
| + identity := fmt.Sprintf("%s:%d:%s", c.BootID, pid, start) |
| + s.Edge = maintenanceProcessStatus{State: "known", PID: &pid, StartTime: &start, Identity: &identity} |
| + } else { |
| + if processErr == nil { |
| + processErr = afterErr |
| + } |
| + if processErr == nil { |
| + processErr = errors.New("edge process changed") |
| + } |
| + s.Edge.Error = maintenanceError(processErr) |
| + s.Health.State = "unknown" |
| + s.Health.Error = maintenanceError(errors.New("edge process unknown")) |
| + } |
| + b, err := json.Marshal(s) |
| + if err != nil { |
| + return err |
| + } |
| + if len(b)+1 > 8192 { |
| + return errors.New("status exceeds 8192 bytes") |
| + } |
| + _, err = out.Write(append(b, '\n')) |
| + return err |
| +} |
diff --git a/internal/host/group_maintenance_verbs_linux.go b/internal/host/group_maintenance_verbs_linux.go| new file mode 100644 |
| index 000000000..9921211fc |
| --- /dev/null |
| +++ b/internal/host/group_maintenance_verbs_linux.go |
| @@ -0,0 +1,208 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Open every ancestor by descriptor. Production starts at /; the test anchor |
| +// avoids depending on permissions outside its own private fixture directory. |
| +func openMaintenanceDirectory(root, path string, owner int, create bool) (*os.File, error) { |
| + rel, err := filepath.Rel(root, path) |
| + if err != nil || !filepath.IsLocal(rel) || rel == "." { |
| + return nil, errGroupMaintenance |
| + } |
| + fd, err := unix.Openat2(unix.AT_FDCWD, root, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer func() { |
| + if fd >= 0 { |
| + unix.Close(fd) |
| + } |
| + }() |
| + parts := strings.Split(rel, string(filepath.Separator)) |
| + for i, part := range parts { |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) != nil || (int(st.Uid) != owner && st.Uid != 0) || st.Mode&0022 != 0 { |
| + return nil, errGroupMaintenance |
| + } |
| + next, e := unix.Openat2(fd, part, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + if errors.Is(e, unix.ENOENT) && create && i == len(parts)-1 { |
| + if e = unix.Mkdirat(fd, part, 0700); e != nil && !errors.Is(e, unix.EEXIST) { |
| + return nil, e |
| + } |
| + if e = unix.Fsync(fd); e != nil { |
| + return nil, e |
| + } |
| + next, e = unix.Openat2(fd, part, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + } |
| + if e != nil { |
| + return nil, e |
| + } |
| + unix.Close(fd) |
| + fd = next |
| + } |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) != nil || int(st.Uid) != owner || (owner == 0 && st.Gid != 0) || st.Mode&07777 != 0700 { |
| + return nil, errGroupMaintenance |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + fd = -1 |
| + return f, nil |
| +} |
| +func openMaintenanceLock(path string) (*os.File, error) { |
| + fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDWR | unix.O_CREAT | unix.O_NONBLOCK | unix.O_CLOEXEC, Mode: 0600, Resolve: unix.RESOLVE_NO_SYMLINKS}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || int(st.Uid) != os.Geteuid() || st.Mode&0022 != 0 { |
| + f.Close() |
| + return nil, errGroupMaintenance |
| + } |
| + return f, nil |
| +} |
| +func replaceMaintenancePermit(dir *os.File, b []byte, owner int, rename func(int, string, int, string) error) error { |
| + var nonce [16]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| + return err |
| + } |
| + name := ".permit-" + hex.EncodeToString(nonce[:]) |
| + fd := int(dir.Fd()) |
| + leaf, err := unix.Openat2(fd, name, &unix.OpenHow{Flags: unix.O_WRONLY | unix.O_CREAT | unix.O_EXCL | unix.O_CLOEXEC, Mode: 0600, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + if err != nil { |
| + return err |
| + } |
| + defer unix.Unlinkat(fd, name, 0) |
| + f := os.NewFile(uintptr(leaf), name) |
| + defer f.Close() |
| + if owner == 0 { |
| + if err = f.Chown(0, 0); err != nil { |
| + return err |
| + } |
| + } |
| + if err = f.Chmod(0600); err != nil { |
| + return err |
| + } |
| + if _, err = f.Write(b); err != nil { |
| + return err |
| + } |
| + if err = f.Sync(); err != nil { |
| + return err |
| + } |
| + if err = f.Close(); err != nil { |
| + return err |
| + } |
| + if rename == nil { |
| + rename = unix.Renameat |
| + } |
| + if err = rename(fd, name, fd, "permit.json"); err != nil { |
| + return err |
| + } |
| + return dir.Sync() |
| +} |
| +func revokeMaintenancePermit(dir *os.File) error { |
| + if err := unix.Unlinkat(int(dir.Fd()), "permit.json", 0); err != nil && !errors.Is(err, unix.ENOENT) { |
| + return err |
| + } |
| + return dir.Sync() |
| +} |
| +func maintenanceBinaryDigest(path string) (string, error) { |
| + fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_NONBLOCK | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS}) |
| + if err != nil { |
| + return "", err |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + defer f.Close() |
| + st, err := f.Stat() |
| + if err != nil { |
| + return "", err |
| + } |
| + if !st.Mode().IsRegular() || st.Size() > systemArtifactLimit { |
| + return "", errGroupMaintenance |
| + } |
| + h := sha256.New() |
| + n, err := io.Copy(h, io.LimitReader(f, systemArtifactLimit+1)) |
| + if err != nil { |
| + return "", err |
| + } |
| + if n > systemArtifactLimit { |
| + return "", errGroupMaintenance |
| + } |
| + return hex.EncodeToString(h.Sum(nil)), nil |
| +} |
| + |
| +type maintenanceBoundedOutput struct{ body []byte } |
| + |
| +func (b *maintenanceBoundedOutput) Write(p []byte) (int, error) { |
| + if len(b.body)+len(p) > 4096 { |
| + return 0, errors.New("process output too large") |
| + } |
| + b.body = append(b.body, p...) |
| + return len(p), nil |
| +} |
| +func maintenanceEdgeProcess(ctx context.Context) (int, string, error) { |
| + ctx, cancel := context.WithTimeout(ctx, time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", "show", "--property=MainPID", "--value", "carlos-edge.service") |
| + cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} |
| + cmd.Dir = "/" |
| + cmd.WaitDelay = time.Second |
| + var out maintenanceBoundedOutput |
| + cmd.Stdout = &out |
| + if err := cmd.Run(); err != nil { |
| + return 0, "", err |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(out.body))) |
| + if err != nil || pid <= 0 { |
| + return 0, "", errors.New("edge MainPID unavailable") |
| + } |
| + f, err := os.Open("/proc/" + strconv.Itoa(pid) + "/stat") |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + defer f.Close() |
| + b, err := io.ReadAll(io.LimitReader(f, 4097)) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + start, err := maintenanceProcStart(b, pid) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + return pid, start, nil |
| +} |
| +func maintenanceProcStart(b []byte, pid int) (string, error) { |
| + // comm may itself contain spaces and parentheses. Fields after its final |
| + // close parenthesis start at field 3; starttime is field 22. |
| + s := string(b) |
| + end := strings.LastIndex(s, ") ") |
| + if len(b) > 4096 || !strings.HasPrefix(s, strconv.Itoa(pid)+" (") || end < 0 { |
| + return "", errors.New("edge stat invalid") |
| + } |
| + fields := strings.Fields(s[end+2:]) |
| + if len(fields) < 20 || fields[0] == "Z" || fields[0] == "X" { |
| + return "", errors.New("edge stat unavailable") |
| + } |
| + ticks, err := strconv.ParseUint(fields[19], 10, 64) |
| + if err != nil || ticks == 0 { |
| + return "", errors.New("edge start time unavailable") |
| + } |
| + return strconv.FormatUint(ticks, 10), nil |
| +} |
diff --git a/internal/host/group_maintenance_verbs_other.go b/internal/host/group_maintenance_verbs_other.go| new file mode 100644 |
| index 000000000..407202c5b |
| --- /dev/null |
| +++ b/internal/host/group_maintenance_verbs_other.go |
| @@ -0,0 +1,19 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "os" |
| +) |
| + |
| +func openMaintenanceDirectory(string, string, int, bool) (*os.File, error) { |
| + return nil, errSystemUnsupported |
| +} |
| +func openMaintenanceLock(string) (*os.File, error) { return nil, errSystemUnsupported } |
| +func replaceMaintenancePermit(*os.File, []byte, int, func(int, string, int, string) error) error { |
| + return errSystemUnsupported |
| +} |
| +func revokeMaintenancePermit(*os.File) error { return errSystemUnsupported } |
| +func maintenanceBinaryDigest(string) (string, error) { return "", errSystemUnsupported } |
| +func maintenanceEdgeProcess(context.Context) (int, string, error) { return 0, "", errSystemUnsupported } |
diff --git a/internal/host/group_maintenance_verbs_test.go b/internal/host/group_maintenance_verbs_test.go| new file mode 100644 |
| index 000000000..72d844001 |
| --- /dev/null |
| +++ b/internal/host/group_maintenance_verbs_test.go |
| @@ -0,0 +1,425 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type maintenanceRoundTrip func(*http.Request) (*http.Response, error) |
| + |
| +func (f maintenanceRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +func maintenanceVerbFixture(t *testing.T) (*applyFixture, groupMaintenancePermit, *groupMaintenanceCommand) { |
| + t.Helper() |
| + f, p := maintenanceFixture(t) |
| + cmd := &groupMaintenanceCommand{a: f.a, euid: func() int { return 0 }, root: filepath.Dir(f.a.maintenance().dir), edge: func(context.Context) (int, string, error) { return 123, "456", nil }, client: maintenanceHealthClient(maintenanceRoundTrip(func(r *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("ok")), Header: make(http.Header)}, nil |
| + }))} |
| + return f, p, cmd |
| +} |
| +func runMaintenanceVerb(cmd *groupMaintenanceCommand, verb string, body []byte) ([]byte, error) { |
| + var out bytes.Buffer |
| + err := cmd.run(context.Background(), verb, bytes.NewReader(body), &out) |
| + return out.Bytes(), err |
| +} |
| +func TestGroupMaintenanceVerbsPermit(t *testing.T) { |
| + for _, bad := range []string{"valid", "v", "account", "region", "group", "iid", "boot", "digest", "transaction", "expired", "phase", "action", "old", "new", "oversize", "duplicate", "unknown", "null", "missing", "trailing", "used", "foreign-binary"} { |
| + t.Run(bad, func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + path := filepath.Join(f.a.maintenance().dir, "permit.json") |
| + original, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + switch bad { |
| + case "v": |
| + p.V = 2 |
| + case "account": |
| + p.Account = "other" |
| + case "region": |
| + p.Region = "other" |
| + case "group": |
| + p.Group = "other" |
| + case "iid": |
| + p.Instance = "other" |
| + case "boot": |
| + p.BootID = "other" |
| + case "digest": |
| + p.ConfigDigest = strings.Repeat("b", 64) |
| + case "transaction": |
| + p.Transaction = "../escape" |
| + case "expired": |
| + p.Expires = f.now.Unix() |
| + case "phase": |
| + p.Phase = "return" |
| + case "action": |
| + p.Action = "stop" |
| + case "old": |
| + p.OldSHA256 = "bad" |
| + case "new": |
| + p.NewSHA256 = "bad" |
| + case "used": |
| + if err := consumeGroupAction(f.a.maintenance().dir, "used-"+p.Transaction+"-"+p.Action, os.Geteuid()); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "foreign-binary": |
| + p.OldSHA256 = strings.Repeat("b", 64) |
| + } |
| + b, _ := json.Marshal(p) |
| + switch bad { |
| + case "oversize": |
| + b = append(b, bytes.Repeat([]byte(" "), 4097)...) |
| + case "duplicate": |
| + b = append([]byte(`{"v":1,`), b[1:]...) |
| + case "unknown": |
| + b = append([]byte(`{"extra":1,`), b[1:]...) |
| + case "null": |
| + b = bytes.Replace(b, []byte(`"allow_rollback":false`), []byte(`"allow_rollback":null`), 1) |
| + case "missing": |
| + b = bytes.Replace(b, []byte(`,"allow_rollback":false`), nil, 1) |
| + case "trailing": |
| + b = append(b, []byte(` {}`)...) |
| + } |
| + _, err = runMaintenanceVerb(cmd, "permit", b) |
| + if bad == "valid" { |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = f.a.requireGroupMaintenance("check"); err != nil { |
| + t.Fatal("guard refused installed permit", err) |
| + } |
| + } else { |
| + if err == nil { |
| + t.Fatal("accepted invalid permit") |
| + } |
| + got, e := os.ReadFile(path) |
| + if e != nil || !bytes.Equal(got, original) { |
| + t.Fatal("refusal changed permit", e) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsRefusals(t *testing.T) { |
| + for _, verb := range []string{"permit", "revoke", "status"} { |
| + for _, bad := range []string{"fixed", "nonroot", "marker-mode", "marker-boot", "directory-mode", "directory-owner", "directory-symlink", "ancestor-symlink", "ancestor-mode"} { |
| + t.Run(verb+"/"+bad, func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + switch bad { |
| + case "fixed": |
| + if err := os.Remove(filepath.Join(f.a.etcDir, "carlos/group.json")); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "nonroot": |
| + cmd.euid = func() int { return 1001 } |
| + case "marker-mode": |
| + if err := os.Chmod(filepath.Join(f.a.etcDir, "carlos/group.json"), 0664); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "marker-boot": |
| + f.a.maintenance().bootID = func() string { return "other" } |
| + case "directory-mode": |
| + if err := os.Chmod(f.a.maintenance().dir, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "directory-owner": |
| + old := f.a.maintenance().read |
| + f.a.maintenance().read = func(path string, _ int, mode os.FileMode) ([]byte, error) { return old(path, os.Geteuid(), mode) } |
| + f.a.maintenance().owner = os.Geteuid() + 1 |
| + case "directory-symlink": |
| + d := f.a.maintenance().dir |
| + if err := os.Rename(d, d+"-real"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(d+"-real", d); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "ancestor-symlink": |
| + link := filepath.Join(cmd.root, "link") |
| + if err := os.Symlink(cmd.root, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.maintenance().dir = filepath.Join(link, "maintenance") |
| + case "ancestor-mode": |
| + if err := os.Chmod(cmd.root, 0770); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + b, _ := json.Marshal(p) |
| + if _, err := runMaintenanceVerb(cmd, verb, b); err == nil { |
| + t.Fatal("unsafe command accepted") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsAtomicReplace(t *testing.T) { |
| + for _, present := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "absent", true: "existing"}[present], func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + path := filepath.Join(f.a.maintenance().dir, "permit.json") |
| + old, _ := os.ReadFile(path) |
| + if !present { |
| + if err := os.Remove(path); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + p.Transaction = "tx-2" |
| + b, _ := json.Marshal(p) |
| + cmd.rename = func(int, string, int, string) error { return errors.New("crash before rename") } |
| + if _, err := runMaintenanceVerb(cmd, "permit", b); err == nil { |
| + t.Fatal("rename failure ignored") |
| + } |
| + got, err := os.ReadFile(path) |
| + if present && (err != nil || !bytes.Equal(got, old)) { |
| + t.Fatal("partial replacement", err) |
| + } |
| + if !present && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("partial creation", err) |
| + } |
| + entries, err := os.ReadDir(f.a.maintenance().dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range entries { |
| + if e.Name() != "permit.json" { |
| + t.Fatal("temp file left", e.Name()) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsCreateAndRevoke(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + d := f.a.maintenance().dir |
| + if err := os.RemoveAll(d); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := json.Marshal(p) |
| + if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := checkGroupMaintenanceDirectory(d, os.Geteuid()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.a.requireGroupMaintenance("check"); err != nil { |
| + t.Fatal(err) |
| + } |
| + used := "used-" + p.Transaction + "-" + p.Action |
| + if err := consumeGroupAction(d, used, os.Geteuid()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + if _, err := runMaintenanceVerb(cmd, "revoke", nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := os.Stat(filepath.Join(d, used)); err != nil { |
| + t.Fatal("lost replay marker", err) |
| + } |
| + if _, err := os.Stat(filepath.Join(d, "permit.json")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("permit not revoked", err) |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsLock(t *testing.T) { |
| + for _, verb := range []string{"permit", "revoke", "status"} { |
| + t.Run(verb, func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + if err := os.MkdirAll(f.a.rootDir(), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + held, err := os.OpenFile(f.a.lockPath(), os.O_CREATE|os.O_RDWR, 0600) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer held.Close() |
| + if err = flockExclusiveNonblock(held); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := json.Marshal(p) |
| + if _, err = runMaintenanceVerb(cmd, verb, b); err == nil { |
| + t.Fatal("command ran while apply held lock") |
| + } |
| + }) |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsStatus(t *testing.T) { |
| + for _, mode := range []string{"healthy", "unhealthy", "dial-error", "redirect", "process-change", "unknown-process", "used", "expired", "absent", "unknown-binary"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + calls := 0 |
| + cmd.client = maintenanceHealthClient(maintenanceRoundTrip(func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + if r.Method != "GET" || r.URL.String() != "http://127.0.0.1/.carlos/lb-health" { |
| + t.Fatal("nonlocal request", r.Method, r.URL) |
| + } |
| + if mode == "dial-error" { |
| + return nil, errors.New(strings.Repeat("dial failed", 2000)) |
| + } |
| + code := 200 |
| + if mode == "unhealthy" { |
| + code = 503 |
| + } |
| + if mode == "redirect" { |
| + code = 302 |
| + } |
| + return &http.Response{StatusCode: code, Header: http.Header{"Location": []string{"https://example.com/"}}, Body: io.NopCloser(strings.NewReader("ignored"))}, nil |
| + })) |
| + if mode == "process-change" { |
| + n := 0 |
| + cmd.edge = func(context.Context) (int, string, error) { n++; return 123, string(rune('0' + n)), nil } |
| + } |
| + if mode == "unknown-process" { |
| + cmd.edge = func(context.Context) (int, string, error) { return 0, "", errors.New("no process") } |
| + } |
| + if mode == "used" { |
| + if err := consumeGroupAction(f.a.maintenance().dir, "used-"+p.Transaction+"-"+p.Action, os.Geteuid()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if mode == "expired" { |
| + f.now = f.now.Add(2 * time.Hour) |
| + } |
| + if mode == "absent" { |
| + if err := os.RemoveAll(f.a.maintenance().dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if mode == "unknown-binary" { |
| + if err := os.Remove(systemBinaryPath(f.a.optDir)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + b, err := runMaintenanceVerb(cmd, "status", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(b) > 8192 { |
| + t.Fatal("unbounded status", len(b)) |
| + } |
| + var s groupMaintenanceStatus |
| + if err = json.Unmarshal(b, &s); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s.V != 1 || s.Instance != p.Instance || s.BootID != p.BootID || s.BoxRef != groupReferenceOf(p.Account, p.Instance) { |
| + t.Fatal("wrong identity", string(b)) |
| + } |
| + if calls != 1 { |
| + t.Fatal("request count", calls) |
| + } |
| + want := "healthy" |
| + switch mode { |
| + case "unhealthy", "redirect": |
| + want = "unhealthy" |
| + case "dial-error", "process-change", "unknown-process": |
| + want = "unknown" |
| + } |
| + if s.Health.State != want { |
| + t.Fatal("health", string(b)) |
| + } |
| + if mode == "used" && (s.Permit.Consumed == nil || !*s.Permit.Consumed) { |
| + t.Fatal("consumption missing", string(b)) |
| + } |
| + if mode == "expired" && (s.Permit.Expires == nil || *s.Permit.Expires != p.Expires) { |
| + t.Fatal("expired permit hidden", string(b)) |
| + } |
| + if mode == "absent" && s.Permit.State != "absent" { |
| + t.Fatal("absence", string(b)) |
| + } |
| + if mode == "unknown-binary" && s.BinarySHA256 != nil { |
| + t.Fatal("invented digest", string(b)) |
| + } |
| + if mode == "healthy" && (s.Edge.PID == nil || *s.Edge.PID != 123 || s.Edge.StartTime == nil || *s.Edge.StartTime != "456" || s.BinarySHA256 == nil || *s.BinarySHA256 != p.OldSHA256) { |
| + t.Fatal("missing local evidence", string(b)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupMaintenanceVerbsProcStart(t *testing.T) { |
| + fields := []string{"S"} |
| + for i := 0; i < 18; i++ { |
| + fields = append(fields, "0") |
| + } |
| + fields = append(fields, "456") |
| + good := []byte("123 (edge (worker) name) " + strings.Join(fields, " ")) |
| + if got, err := maintenanceProcStart(good, 123); err != nil || got != "456" { |
| + t.Fatal(got, err) |
| + } |
| + for _, bad := range [][]byte{[]byte("123 (short) S"), bytes.Replace(good, []byte("123 ("), []byte("124 ("), 1), bytes.Replace(good, []byte(") S "), []byte(") Z "), 1), append(good, bytes.Repeat([]byte(" "), 4097)...), bytes.Replace(good, []byte("456"), []byte("not-a-time"), 1)} { |
| + if _, err := maintenanceProcStart(bad, 123); err == nil { |
| + t.Fatal("accepted invalid process stat") |
| + } |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsHelp(t *testing.T) { |
| + for _, args := range [][]string{{"--help"}, {"help"}, {"-h"}, nil, {"stop"}, {"permit", "extra"}} { |
| + var out, stderr bytes.Buffer |
| + code := RunGroupMaintenance(args, strings.NewReader(""), &out, &stderr) |
| + want := 2 |
| + if len(args) == 1 && (args[0] == "--help" || args[0] == "-h" || args[0] == "help") { |
| + want = 0 |
| + } |
| + if code != want || !strings.Contains(out.String()+stderr.String(), "Exit codes:") { |
| + t.Fatal(args, code, out.String(), stderr.String()) |
| + } |
| + } |
| + if os.Geteuid() != 0 { |
| + var out, stderr bytes.Buffer |
| + if code := RunGroupMaintenance([]string{"status"}, strings.NewReader(""), &out, &stderr); code != 1 || out.Len() != 0 || stderr.String() != "group-maintenance: root required\n" { |
| + t.Fatal(code, out.String(), stderr.String()) |
| + } |
| + } |
| + client := maintenanceHealthClient(nil) |
| + tr, ok := client.Transport.(*http.Transport) |
| + if !ok || tr.Proxy != nil || client.Timeout != time.Second || !tr.DisableKeepAlives { |
| + t.Fatal("unsafe local client") |
| + } |
| +} |
| +func TestGroupMaintenanceVerbsPermitLeafLinks(t *testing.T) { |
| + for _, kind := range []string{"symlink", "hardlink"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f, p, cmd := maintenanceVerbFixture(t) |
| + path := filepath.Join(f.a.maintenance().dir, "permit.json") |
| + target := filepath.Join(f.a.maintenance().dir, "unrelated") |
| + old, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.Rename(path, target); err != nil { |
| + t.Fatal(err) |
| + } |
| + if kind == "symlink" { |
| + err = os.Symlink(target, path) |
| + } else { |
| + err = os.Link(target, path) |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p.Transaction = "tx-2" |
| + b, _ := json.Marshal(p) |
| + if _, err = runMaintenanceVerb(cmd, "permit", b); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = f.a.requireGroupMaintenance("check"); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := os.ReadFile(target) |
| + if err != nil || !bytes.Equal(got, old) { |
| + t.Fatal("replacement touched unrelated inode", err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/system.go b/system.go| index 98d2353f2..6b10ac631 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -53,7 +53,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) { |
| // untouched in rest for runSystemAntivirusVerb to read. |
| // layout is a family too: migrate|revert|status stay in rest for |
| // runSystemLayout. |
| - case "demos", "managed-fleets", "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "pdf", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help": |
| + case "group-maintenance", "demos", "managed-fleets", "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "pdf", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help": |
| return args[0], args[1:], component |
| } |
| return "", args, component |
| @@ -62,6 +62,8 @@ func systemVerb(args []string) (verb string, rest []string, component string) { |
| func runSystem(args []string) { |
| verb, rest, _ := systemVerb(args) |
| switch verb { |
| + case "group-maintenance": |
| + os.Exit(host.RunGroupMaintenance(rest, os.Stdin, os.Stdout, os.Stderr)) |
| case "demos": |
| runSystemDemos(rest) |
| case "managed-fleets": |
diff --git a/system_test.go b/system_test.go| index 0ccda14b9..bafb4f22e 100644 |
| --- a/system_test.go |
| +++ b/system_test.go |
| @@ -423,3 +423,12 @@ func TestSystemPDFThroughTheBinary(t *testing.T) { |
| t.Fatalf("command = %v, output = %q; want %q", err, out, want) |
| } |
| } |
| + |
| +func TestSystemGroupMaintenanceVerb(t *testing.T) { |
| + for _, leaf := range []string{"status", "permit", "revoke"} { |
| + verb, rest, _ := systemVerb([]string{"group-maintenance", leaf}) |
| + if verb != "group-maintenance" || len(rest) != 1 || rest[0] != leaf { |
| + t.Fatalf("dispatch: %q %v", verb, rest) |
| + } |
| + } |
| +} |