Skip to content

feat: a root broker in place of sudo - #1943

Open
retr0h wants to merge 38 commits into
mainfrom
feat/sudo-declared-calls
Open

retr0h wants to merge 38 commits into
mainfrom
feat/sudo-declared-calls

Conversation

@retr0h

@retr0h retr0h commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

The agent no longer uses sudo. It runs as the user osapi (_osapi on macOS), with no capability and NoNewPrivileges=yes. A root broker runs each piece of root work that a behavior declares.

Specs: osapi-io/specs#756

Closes #1907
Closes #1962

What changes

  • The broker. osapi-privileged.socket (/run/osapi/privileged.sock, root:osapi 0660, Accept=yes) starts osapi-privileged@.service, which runs osapi agent privileged serve. It does these checks:

    • the peer UID (SO_PEERCRED, or getpeereid on macOS);
    • the hash of the declarations in its own binary;
    • the enabled list /etc/osapi-privileged/enabled.

    It runs each call or step in a transient unit (systemd-run, ProtectSystem=strict, ReadWritePaths for the declared writes, the declared capabilities only) and records it in the journal. macOS gets launchd plists.

  • Declared calls. behavior.Sudo is now behavior.Root. The broker matches the whole argument vector, argument by argument (RootCall.Matches), so sudoers globbing is gone. AnyArgs is gone, and validate refuses a call with no shape, with no exception for RootEquivalent. Work whose arguments no shape holds is a privileged step that builds the vector from typed input. This covers docker create and exec, user, group and password.

  • Steps. A step input may have a []string field, and each value is checked. A step marked Read() is the only root work a read can run, and validate refuses a secret field in its output. The step refusals:

    • sysctl refuses fs.protected_* and fs.suid_dumpable, on top of its earlier list;
    • user and group refuse UID and GID 0 and the root groups;
    • sshkey refuses root and each user with UID 0, and checks UID, GID and home against passwd.
  • Read steps:

    • user locked (a bool only);
    • sshkey keys (the public key lines only);
    • docker containers and image images, because the agent is never in the docker group.
  • Write guard. It walks each path from / with openat(O_NOFOLLOW|O_NONBLOCK), works on the descriptor (fchown, fchmod, Renameat, Unlinkat), and refuses setuid, setgid and sticky bits and nlink > 1. managedfile and sshkey no longer run stat or chown.

  • Warnings. A read whose gohai collector gives a partial fact returns the fact, with a warnings field on each row. A read that runs a collector as the agent, and that no read step covers, adds the collector's Privilege().Without text.

  • Install. osapi agent service install --privileged <names> makes the users and groups, owns the config by osapi, makes /var/lib/osapi/pki (2750, group osapi-admin), and writes the enabled list and the three units. osapi agent privileged enable|disable|list changes the list.

  • Preflight stops the start for sudo -n -l that works, a group that gives root, or a capability. It warns for a group that no enabled behavior declares, and for a broker that does not answer.

  • Removed:

    • dsl behavior sudoers get and dsl behavior systemd get;
    • the agent.privilege_escalation config;
    • the sudo prefix of internal/exec.

    osapi start is test only and refuses root.

  • CI. As root, the integration suite now starts NATS and the controller, and installs the agent with osapi agent service install under its real units, with every behavior enabled. As a user, it still uses osapi start.

Choices made by rule, for review

  • A literal may hold any text with no control character. A class may hold printable ASCII except the space, is never negated, and its first segment never holds -. The probes catch ;, |, newline and ../. A Regex argument skips the probes. Only the image reference uses one, because a class cannot say "no ..".
  • Preflight findings are fatal only when the process user is the agent's user. Thus osapi start on a dev machine still runs, with warnings.
  • The guard walk follows a link in a parent directory only when root owns the link and its directory, and that directory is not group or other writable, at most 8 times. macOS needs this for /etc and /var. The last component is never followed.
  • password calls the password step of user and declares no step of its own. packages runs one package per call, with an exact shape.
  • commandgen's validates now stops at dive, so omitempty,dive,required no longer marks a list flag as required.
  • agent privileged enable and disable are NoAudit, as agent service install is: they run on an agent host, which keeps no audit log.

Checks

  • go test -cover on each changed package: 100.0%. The exceptions are cmd, generated packages and process on macOS. process is the same as on main, because its darwin file has real kill paths.
  • golangci-lint fmt and run on the changed packages, go vet with GOOS=linux on the broker, agent and integration packages, and go run . dsl behavior validate.
  • just generate, then behavior-gen-check, go-fmt-check, md-fmt-check, docs-fmt-check, react-fmt-check, docs-build and react-build. The internal/apicontract golden is recorded again (the warnings fields).

Not tested

  • The integration suite under the real units. It has not run yet, because the dev machine has no systemd. This PR needs the integration label. The fork guessed these points, and CI confirms or breaks them:
    • runuser is on the runner;
    • the join string reaches NATS on localhost;
    • preflight passes for osapi on the runner.
  • The lab and the UI click-through. Another session holds the lab, so no just bump or just int ran, and nobody checked /var/lib/osapi/pki mode 2750 after a restart.
  • macOS launchd plists. They have unit tests only.
  • agent privileged enable and disable on a real host. The integration suite skips both (skipPrivileged in test/integration/clicases_test.go). Only root writes the enabled list, and a change to the list during the suite changes what each other test can do. The unit tests of internal/cli/commands/agentprivileged cover them against a list in a directory of their own. The lab hand checks run them as root, then restart the agent and run a write of the behavior. A CI test on a real host is test: privileged enable and disable on a real host #1949.

🤖 Generated with Claude Code

@retr0h retr0h added the integration Run the integration suite on this pull request label Dec 5, 2026
@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review at 44a078b. Changes requested.

What meets the rules:

  • The PR title has 36 characters, and the squash uses it. Each of the 12 commits has a subject of 48 characters or fewer, and its trailer.
  • Specs: https://github.com/osapi-io/specs/pull/756 and Closes #1907 are in the description, and specs#756 links back.
  • The choices made by rule are written in the description. NoAudit on agent privileged enable and disable agrees with agent service install.
  • There is no em dash in the added lines. The addresses in the regenerated pages were on main before this PR.
  • The export_test.go setters give back a function that restores the value.
  • The docs no longer describe sudo as the way to root. Each sudo that is left is a command that a person types, or a check that preflight runs.

Open, each a written rule:

  1. Spans on the root path. CONTRIBUTING.md, "Audit and spans", says to start a span for each operation that runs a command or writes a file. On main, each command, including a sudo one, gets its span from internal/exec (startSpan). With this PR, RunPrivilegedCmd and Escalate go to privileged.Client.RunRoot and Escalate (internal/privileged/client.go:55, :92). Neither starts a span, so each root call and step is no longer in the trace of job.process. Start a span in Client.Do, or in RunRoot and Escalate, named for the call or the step, with opspan.End(span, err). Then assert it in client_public_test.go.

  2. Hand-written doubles of osapi interfaces. The Test doubles section allows a hand-written double only for a standard library interface, a real implementation or a goroutine recorder.

    • noEscalator in internal/privileged/privileged_public_test.go:163 implements host.Escalator. host/mocks has MockEscalator. Use it, with an expectation of no call or with a return of the error.
    • fakeProvider in internal/behaviors/managedfile/steps_public_test.go:213 embeds managedfile.Provider. Use mocks.NewMockProvider, as methods_public_test.go:44 does.

    fakeInfo, noSys, rootInfo (fs.FileInfo), failReader (io.Reader), closer (io.WriteCloser) and panicReporter (gomock.TestReporter) are not osapi interfaces. They are correct.

  3. Custom assertion messages. CONTRIBUTING.md says "Do not write a custom assertion message". The added tests have more than 40. Most are in internal/privileged/guard_public_test.go, which has 28. Others are in internal/authtoken/permissions_public_test.go, internal/cli/commands/behaviordsl/methods_public_test.go, internal/privileged/server_public_test.go, internal/behavior/privileged_public_test.go, cmd/agent_test.go and internal/behaviors/process/signal_{linux,darwin}_public_test.go:43,39. The text of each message is the name of a row.

  4. Rows, not scripts or extra methods. "Use testify/suite with table-driven cases" and "one suite method for each function under test":

    • GuardPublicTestSuite.TestHostWrite, TestHostChange, TestHostTree, TestHostLinks and TestHostSystemCalls are sequences of assertions, with no table. Make each a table of rows for the function that it tests, such as WriteFile, Chmod and RemoveAll. The messages from item 3 become the row names.
    • ClientPublicTestSuite has TestRunRoot, TestRunRootRefused and TestRunRootNoArgs for one function. They are rows of TestRunRoot.
    • ServerPublicTestSuite has TestCall, TestCallUnit, TestCallOnDarwin, TestNoRecord, TestReadFails, TestNotEnabled and TestRefusals around Serve. Group them by the function under test.
  5. Suite name for each file. *_public_test.go has {Name}PublicTestSuite. internal/behaviors/process/signal_linux_public_test.go and signal_darwin_public_test.go add methods to StepsPublicTestSuite, which steps_public_test.go declares. Give each file its own suite, such as SignalLinuxPublicTestSuite. CI's go-test-name-check also fails on internal/behaviors/process/export_linux_test.go and internal/behavior/behaviortest/escalate_public_test.go. Each must have the name of its production file.

CI, run https://github.com/osapi-io/osapi/actions/runs/47577464515, also fails these. Each is a rule that a check enforces:

  • dslcheck: TestNoLiteralForATypedValue finds "" as behavior.PlatformName at methods.go:604.
  • go-vet: revive unused-parameter at signal_linux_public_test.go:81.
  • behavior-scaffold-check: the scaffold writes /etc/osapi/scaffoldcheck as the agent. The scaffold that build-a-behavior gives must write through a privileged step, as managedfile.Steps does. Otherwise each new behavior starts with the old model.
  • unit 6: TestServertestPublicTestSuite/TestRun, two rows of a broadcast write.

Notes that do not block:

  • panicReporter hides each unexpected call of newTestAgent as a panic. A reporter from the suite's s.T() reports it as a test failure.
  • The integration suite under the real units, the lab and the UI click-through are not tested, as the description says. The warnings field of the reads is new in the UI.

The label is now needs-standards-review.

@retr0h retr0h added the needs-standards-review The author asks for the independent standards review label Dec 5, 2026
@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review at 44a078b, part 2: the docs, the generated pages, CONTRIBUTING.md and the skills. The team lead asked for these parts. My review of the test conventions is in #1943 (comment), and it still applies.

What meets the rules:

  • operate/secure/agent-hardening.md is in STE and has no em dash. It agrees with the code: the broker's checks in order, the 64 KiB cap, the sandbox table, the enabled list, the unit lines and the preflight. It names the groups that give root as examples ("such as"), so the list in internal/behavior/systemd.go stays the only full list.
  • The sudo that is left in the docs is a command that a person types, or the check that preflight runs.
  • The generated pages, the API docs and the SDK change together, and the generated-file checks pass in CI.
  • The build-a-behavior skill sends the reader to dsl behavior spec get, under "Root" and "Privileged", for the rule, and copies no text. Its evals no longer use Sudo or AnyArgs.

Open:

  1. One fact in one place: the new rule in CONTRIBUTING.md (line 993). It writes the rule of root work again: the shapes, the steps, Read() and .AdminOnly(). Then it says that spec get gives the rule. specs#756, "The rule", says that the text has one place, the description of the DSL, and that CONTRIBUTING.md links to the command and copies no text. Make the entry one sentence that names the error. For example: "Declare each command line that runs as root, with behavior.Root or a privileged step." Then point to osapi dsl behavior spec get, under "Root" and "Privileged", and to the Why link.

The label stays needs-standards-review.

@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: changes requested (head 44a078b). I read internal/privileged/server.go, guard.go, guard_unix.go, internal/behavior/rootmatch.go, the user, group, sshkey and sysctl steps, the broker units in internal/initsys, and the CI run for this head. In a throwaway worktree I ran go test -cover on internal/privileged, internal/behavior, user, group, sshkey, sysctl, password, packages and internal/initsys (all pass, 100.0%), and GOOS=linux go vet on the broker and agent packages. I ran nothing under the real units.

Required

  1. sshkey add, remove and keys fail under an empty bounding set. internal/behaviors/sshkey/steps.go:110 and :120 declare Needs("CAP_CHOWN", "CAP_FOWNER"), and the keys read step declares no capability. Each step opens /home/<user>/.ssh and authorized_keys, which the user owns with mode 0700 and 0600. The transient unit sets CapabilityBoundingSet= to exactly the declared set (internal/behavior/systemd.go:177). Root without CAP_DAC_OVERRIDE or CAP_DAC_READ_SEARCH is an ordinary user to a file that another user owns, so the walk in dirAt fails with EACCES at .ssh. CAP_FOWNER does not grant read or search. The user steps are not affected: AccountCaps has CAP_DAC_OVERRIDE. Fix: CAP_DAC_OVERRIDE on add and remove (they write into a directory of the user), CAP_DAC_READ_SEARCH on keys, and a lab step that adds a key, reads it and removes it under the real unit. The unit tests cannot find this, because they run the step in the test process.

  2. A - in the middle of a class is a range in the matcher. rootmatch.go regexp() writes each rune of ExpandClass through regexp.QuoteMeta, which does not escape -. ExpandClass accepts a class like [a-z0-9-_] and gives abc...z0123456789-_, and the regexp [...9-_] is the range 9 to _. Reproducer, an in-package test that builds RootArg{Segments: []Segment{{Class: c, Min: 1, Max: 1}}} and matches every rune below 300 against ExpandClass(c):

    • [a-z0-9-_] matches 38 characters that it does not hold: :;<=>?@, A-Z, [, \, ], ^.
    • [a-c-e] matches d, and does not match -.

    I ran the same check on each of the 15 classes that the behaviors declare today ([a-zA-Z0-9_.-], [A-Za-z0-9_+/-], [a-zA-Z0-9.+_:~=-] and the others): none differs, because each has the - last. So nothing is exploitable now, but this is the one matcher that decides root, and the probes cannot catch it (the option probe only tries a leading -). Fix: write \- for a - in the builder (or refuse a - that is not last in ExpandClass), and add a test row that compares the regexp with ExpandClass for each rune.

  3. The checks are red at this head (https://github.com/osapi-io/osapi/actions/runs/47577464515 and https://github.com/osapi-io/osapi/actions/runs/47577464939):

    • dslcheck: TestNoLiteralForATypedValue (methods.go:604: "" as behavior.PlatformName) and TestStringsAreReviewed (the new and removed symbols of behavior, such as Behavior.Unit, PrivilegedStep and the old Sudo, are not in strings.txt).
    • go-vet: internal/behaviors/process/signal_linux_public_test.go:81 unused parameter sig (revive).
    • quick checks: go-test-name-check. behavior-scaffold-check also fails.
    • unit 6: TestServertestPublicTestSuite/TestRun "a write is broadcast ..." and "a write completes on one host ...": the token of the test has only sysctl:read, and the write answers Insufficient permissions. Required: [sysctl:write]. A write behavior that is now root equivalent needs the admin permission set in the test.
    • integration (cli): the first job fails. client node sysctl get --key net.ipv4.ping_group_range --target _any times out after the suite installs the agent. The agent journal in the log shows the agent joined, registered, and heartbeating, and the broker answered its preflight ping, but it logs no job at all before the timeout. So the first failure is the agent not taking the job, not a refusal by the broker. I did not find the cause from the log.
  4. The broker has no deadline, and the transient unit has no run time limit. This was item 4 of my review of specs#756, and the code has neither. readRequest (server.go) reads until EOF with no deadline, so 64 idle connections from the osapi user fill MaxConnections=64 and no later request gets an answer. RunCommand kills only systemd-run when the 30-minute context ends; with --wait --pipe the transient unit keeps running. Fix: conn.SetReadDeadline for the request (the peer is checked first, so only the agent can hold a slot), and RuntimeMaxSec= on the transient unit, or a systemctl stop of a named unit when the context ends. It is an availability problem, not a privilege one.

Notes, not blocking

  • specs#756 says the broker unit has a CapabilityBoundingSet= with only what it needs. brokerSandbox in internal/initsys/initsys.go has none, so the broker keeps all capabilities. Either set it (the lab decides the set) or change the page to say it has none. The page does not mention StandardError=journal or MaxConnections=64, which the unit has.
  • The broker reads 64 KiB (MaxRequest = MaxStepInput), and the request wraps the step input in an envelope, so an input of 64 KiB less than about 100 bytes passes Decode and fails at the broker with "longer than 65536 bytes". Give MaxRequest the envelope.
  • Mkdir and MkdirAll of the guard check no Writes pattern (the comment says so). A step that builds a directory path from its input is held only by the walk. I found no step that does today.
  • On a default Linux host the osapi user is in no group of net.ipv4.ping_group_range, so each ICMP ping of the connectivity behavior fails. The preflight warns about it, as the journal line in the CI log shows. That is a behavior change from sudo, so the page and the release note should say it.

What I checked and found correct

  • server.go: the peer is refused before the request is read; the hash, the behavior, the enabled list and the call index are checked in that order; the arguments go through RootCall.Matches with the path from rootpath, never from the request; the step input is decoded with DisallowUnknownFields and checked again; the journal entry has each secret as its length, and oneLine removes line breaks from each field.
  • guard_unix.go: each component opens with O_NOFOLLOW|O_NONBLOCK|O_DIRECTORY from /; O_TRUNC waits for the fstat check; setuid, setgid, sticky, nlink > 1 and a non-regular file are refused on the descriptor; a link is followed only when root owns it and its directory and no other user can write the directory, at most 8 times; rename and remove work on directory descriptors.
  • The refusals: the step patterns are anchored by ^(?:...)$, a value never starts with - or holds .., chpasswd takes a hash with no colon, CR or LF, user and group refuse UID and GID 0 and the root groups, sshkey checks the path, UID and GID against passwd, and the sysctl list has kernel.core_pattern, kernel.modprobe and fs.protected_*. The image Regex has no .., no leading - and a bounded length.

@retr0h retr0h added the needs-code-review The author asks for the independent code review label Dec 5, 2026
@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Standards re-review at a634a9d. Approved.

Each finding from my two reviews at 44a078b is fixed:

  1. Spans. Client.Do starts a span for each request: privileged ping, privileged call or privileged step, with osapi.privileged.* attributes and process.executable.name for a call. It also records the exit code and marks an error. client_public_test.go asserts the name and the attributes of each span.
  2. Doubles. noEscalator and fakeProvider are gone. The tests use MockEscalator and mocks.NewMockProvider. The new hand-written types wrap avfs.VFS or io.Reader, hold the rows of a table, or are the func fields of a Runner. None is an osapi interface.
  3. Assertion messages. My scan of the added lines finds no custom message.
  4. Tables. The Guard suite has one method for each function, from TestOpenFile to TestLstatLink. Client has TestNewClient, TestPing, TestRunRoot, TestEscalate and TestDo. Server has TestServe, TestUnitArgv, TestUnitName and TestStopUnit.
  5. Suites. signal_linux_public_test.go and signal_darwin_public_test.go each declare SignalPublicTestSuite, and the build tags select one. go-test-name-check passes.
  6. CONTRIBUTING.md. The entry is one sentence. It points to osapi dsl behavior spec get and to the Why link.

The PR title has 36 characters, and the squash uses it. Each of the 26 commits has a subject of 50 characters or fewer, and its trailer. No em dash. The branch is on the current origin/main.

Notes that do not block:

  • The span uses otel.Tracer("osapi-privileged") and the name privileged call, as internal/exec names exec <program>. CONTRIBUTING.md asks for opspan.Start and <area>.<verb>. The agent's command spans on main already differ from that rule, so this follows the precedent of internal/exec.
  • internal/behaviors/process/signal_linux_test.go holds only the SetKernel setter, which was export_linux_test.go, and has no suite. go-test-name-check does not accept the name export_<goos>_test.go. An issue on the check would let that file keep the export name.
  • CI is still running on this head. The description says that the integration suite under the real units, the lab and the UI are not tested yet.

The label is now standards-reviewed.

@retr0h retr0h added standards-reviewed An independent reviewer checked this PR against the standards and removed needs-standards-review The author asks for the independent standards review labels Dec 5, 2026
@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: changes requested (head a634a9d). I re-read the delta from 44a078b, ran go test -cover on internal/privileged, internal/behavior, internal/behaviors/..., internal/initsys, internal/cli/commands/agentservice, internal/agent and internal/dslcheck (all pass; process is 91.4% on macOS, as on main), and GOOS=linux go vet on the broker, installer and agent packages. I ran nothing under the real units, and the integration checks on this head had not finished when I looked.

Fixed, and checked by running it

  • Each of my four required items. A comparison of the class regexp with ExpandClass over every rune, for [a-z0-9-_], [a-c-e] and the 15 classes in use, gives no difference. sshkey add and remove declare CAP_DAC_OVERRIDE, and the read steps declare CAP_DAC_READ_SEARCH.
  • The broker names the requester and the owner. For each pair of behaviors I enabled one and asked for every step and call of the other: a behavior that the list does not name is refused, and a step of a required behavior is refused unless the requester declared it with UsesSteps.
  • The read guard refuses a FIFO (checked with a real FIFO), Mkdir refuses a path outside Writes (checked: no directory is left behind), and the installer's MakeDir opens with O_NOFOLLOW and sets the owner and mode on the descriptor.
  • The broker reads one line with a 5 s deadline and watches the connection. The client no longer half-closes after the request, so the watcher fires only when the agent really closes.

Required

  1. No call or step sets .MaxRuntime. grep -rn MaxRuntime internal finds the spec text and the default only, so each call and step gets DefaultRuntime (5 minutes), and the broker stops it at 5 minutes and 10 seconds. The old broker gave one request 30 minutes. apt-get install and upgrade (packages, updatepackages), docker pull, and the image pull steps can run longer on a slow host or a large image, and each would now fail with "it ran longer than 5m0s". Set .MaxRuntime on those (30 minutes is what the code had), and add a row to the capability table of the page that lists the runtimes.

Notes, not blocking

  • Behavior.IsRootEquivalent looks at the behavior's own calls and steps only. password (not root equivalent by that test) is granted user.password through UsesSteps, and that step is root equivalent, so osapi dsl behavior privileges get and the Relaxes rule treat password as safe when it can set the password of any user that is not UID 0. The behavior is AdminOnly, so the API is held; the output and the rule should count the granted steps.
  • A Linux ping call now runs as root with CAP_NET_RAW, and its argument is a class of [0-9a-fA-F.:] with 2 to 45 characters, so it cannot be an option, a name or a path. It can still be a broadcast or multicast address; iputils refuses broadcast without -b, which the shape does not allow. I found nothing to fix.

@codecov

codecov Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1943      +/-   ##
==========================================
- Coverage   99.99%   99.99%   -0.01%     
==========================================
  Files         457      499      +42     
  Lines       27050    30152    +3102     
==========================================
+ Hits        27049    30150    +3101     
- Misses          1        2       +1     
Files with missing lines Coverage Δ
internal/agent/preflight.go 100.00% <ø> (ø)
internal/agent/server.go 100.00% <ø> (ø)
internal/agent/setup.go 100.00% <ø> (ø)
internal/atomicfile/atomic.go 100.00% <ø> (ø)
internal/authtoken/permissions.go 100.00% <ø> (ø)
internal/behavior/behavior.go 100.00% <ø> (ø)
internal/behavior/behaviortest/check.go 100.00% <ø> (ø)
internal/behavior/behaviortest/fakehost.go 100.00% <ø> (ø)
internal/behavior/behaviortest/icmp.go 100.00% <ø> (ø)
internal/behavior/chain.go 100.00% <ø> (ø)
... and 3 more

... and 112 files with indirect coverage changes


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 163222c...bf3f1af. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Standards re-review at 0c65464, of the three commits after a634a9d. Approved again.

  • Named calls and UsesCalls. netplan names its calls generate and apply, and dns, interface and route take both with UsesCalls (internal/behaviors/netplan/behavior.go:58, network/*/behavior.go). systemd_public_test.go has rows for a call that the behavior names, a behavior that it does not require, a name that is not a call, and two calls with one name.
  • Runtimes. The packages and updatepackages calls and the docker create and image pull steps declare MaxRuntime(30 * time.Minute), as specs#756 says.
  • IsRootEquivalent. New rows cover a write step, a call and a read step of a required behavior, and a behavior that uses none of them.
  • The server test. It makes one row for each index of each call that is not granted.
  • Integration. The agent gets the suite's namespace.

The new test code is rows in the tables that were there, with no custom message. No em dash. The commits are a fast-forward from a634a9d and are on the current origin/main. One subject has 53 characters, but the squash uses the PR title, which has 36. Each commit has its trailer.

The label stays standards-reviewed.

@retr0h

retr0h commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at 0c65464. I read the delta from a634a9d and ran go test on internal/privileged, internal/behavior, internal/behaviors/..., internal/initsys, internal/cli/commands/..., internal/agent and internal/dslcheck (all pass), and GOOS=linux go vet on the broker and internal/behavior. I ran nothing under the real units, and the CI checks and the integration run had not finished when I looked.

Checked by running or reading:

  • .MaxRuntime(30 * time.Minute) is on the apt-get install and remove call, the apt-get update call, the image pull step and the docker create step; the rest keep the 5 minute default.
  • Grants (listed from the declarations on debian and darwin): dns, route and interface get only the generate and apply calls of netplan plus its write and remove steps; password gets user.password and user.locked; sshkey gets user.locked. A required behavior's call with no Named is granted to no one.
  • IsRootEquivalent now counts the granted steps and calls: password reports root equivalent.
  • The UsesCalls validation refuses a name that is not a named call, and two calls with one name.

@retr0h retr0h added code-reviewed An independent reviewer checked correctness, bugs and edge cases and removed needs-code-review The author asks for the independent code review labels Dec 5, 2026
@retr0h
retr0h force-pushed the feat/sudo-declared-calls branch from 0c65464 to 08d127b Compare December 6, 2026 00:46
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards re-review at 08d127b, after the rebase onto main with #1707. Approved again.

The rescue through the broker:

  • Calls. netplan declares rescue-start, rescue-stop and check as systemctl calls whose last argument is the template, a lowercase UUID in bracket classes, and .service (internal/behaviors/netplan/behavior.go:76). dns, interface and route name them with UsesCalls. The sudoers forms UnitPattern and CheckUnitPattern are gone with their tests, and no caller is left.
  • Change.Requester. Begin stores the requester from the context, and Confirm gives it to the broker when it stops the unit. Each step has a comment that tells why.
  • Installer. It writes the rescue units through RescueFiles, from feat: hold a netplan change until it is confirmed #1707, so the three unit files still have one source.
  • Tests. The new tests in internal/rescue, agentservice and netplan are tables, and my scan of the added lines finds no custom message. The one message in netplan/debian_public_test.go ("the copy has the other files") was on main before this PR.

The docs:

  • agent-hardening.md. "Pending changes and the rescue" agrees with the code: the three calls, UsesCalls, Type=notify, Restart=on-failure, the boot unit and the check unit.
  • "Ping". The section agrees with the ping call of connectivity, which needs CAP_NET_RAW.
  • Anchors. The #ping, #enable-a-behavior and #the-agents-unit links resolve. The old #kernel-settings link is gone.
  • sudo. The network and architecture pages no longer tell the reader to use sudo. security.md:99 says only that the agent has no sudo rule.

No em dash. The PR title has 36 characters, and the squash uses it. Each of the 7 commits has a subject of 50 characters or fewer, and its trailer. The branch is on the current origin/main.

Note that does not block: no unit test holds the shape of unitOf to rescue.Unit(job) and rescue.CheckUnit(job). The netplan and rescue tests use MockExec, which does not check the shapes, so a change to one side shows only in the integration test. A row in netplan that checks that GrantedCalls matches {"start", rescue.Unit(job)} would hold them together, as the sudoers test did before.

The label stays standards-reviewed.

@retr0h retr0h added needs-code-review The author asks for the independent code review and removed code-reviewed An independent reviewer checked correctness, bugs and edge cases labels Dec 6, 2026
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at 7a0265b for the rescue and check part (the change from 08d127b). I re-ran my reproducer against it and ran go test -cover on internal/rescue (100.0%), internal/behaviors/netplan (100.0%), internal/behaviors/network/... and internal/agent: all pass. The rescue puts back only files that match rescue.NetplanFiles, from the copy that its own unit keeps, and the check output keeps only lines that name such a file. The commits that follow need their own review.

@retr0h retr0h added code-reviewed An independent reviewer checked correctness, bugs and edge cases and removed needs-code-review The author asks for the independent code review labels Dec 6, 2026
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards re-review at 68dc6ef, of the five commits after 08d127b. Approved again.

  • Rescue copy. Root keeps its own copy of the change. TestRootCalls in internal/behaviors/netplan/behavior_public_test.go holds the shapes to rescue.Unit(job) and rescue.CheckUnit(job). It has rows for start, stop and check that the shape takes, and rows for a crossed unit, an uppercase job, a wrong length and an extra argument that the shape refuses. This closes the note from my last review.
  • Root steps in the chain record. TestAddRootStep covers them in Go, steps.test.ts in the UI, and job_steps_public_test.go in the SDK. The golden file of internal/apicontract is recorded again.
  • The lab fixes. They have rows in the tables of user/reader, sshkey/debian and netplan/steps.
  • The page rename. agent-hardening.md is now least-privilege.md, "Least privilege". No link to the old name is left in the repository.
  • Test conventions. One new suite, StepsPublicTestSuite in netplan/steps_public_test.go, has one method for each function. My scan of the added lines finds no custom assertion message. There is no hand-written double of an osapi interface.
  • The commits. No em dash. Each of the five commits has a subject of 50 characters or fewer, and its trailer. They are a fast-forward from 08d127b, on the current origin/main.

Note that does not block:

  • The doc comment of stepTarget in internal/privileged/client.go:179 has a line of 114 characters. The other comments wrap at 80.
  • The comment says "A secret shows its length". The chain record shows (secret, N bytes), from PrivilegedStep.Record. That agrees with the code. specs#756 says <redacted>, and I asked for the fix there.

The label stays standards-reviewed.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at 68dc6ef for the commits after 7a0265b (1f770f4, c3a5109, e178bc3, 68dc6ef). I ran the checks below on the head, and ran no real unit.

file sum step. I ran SumStep behind the guard on a real directory. A file gives exists and the SHA-256, a directory gives exists and dir, a missing path gives not-exists, and the result has no content. A link ("is a symbolic link, which root does not follow"), a FIFO and a file over 1 MiB each give an error, with no hang. file declares Writes("*"), so the step is not narrower than the write step it sits with, and only file owns it; the .. and leading - refusals apply in the broker's check, as for each step.

Secrets in the chain. stepTarget leaves out each Data field, so a password_hash or env never reaches the target, not even as a length (the journal keeps the length). I ran it for user add, user password, docker create and docker exec with a marker in the secret: the target has no marker. I also sent four refused requests (leading -, user root, a hash over the limit, an image with -) to Server.step: neither the refusal error nor the journal input has the marker, only (secret, N bytes). Calls declare no stdin, and their targets are the arguments.

Not blocking

  1. sysctl caps: apply and reload both carry CAP_SYS_ADMIN, CAP_SYS_PTRACE, CAP_SYS_RAWIO, CAP_NET_ADMIN and CAP_MAC_ADMIN. Each has a kernel check behind it, and the comment says the lab found them. But apply refuses kernel.yama.ptrace_scope and vm.mmap_min_addr, which are the parameters that need CAP_SYS_PTRACE and CAP_SYS_RAWIO, so apply can drop those two; reload needs them, because sysctl --system applies the host's own files.
  2. file get on a deployed file that grew over 1 MiB (another program wrote it) now fails with the guard's size error, where it reported Drifted before. The write step takes 48 KiB, so only a file changed outside osapi gets there.
  3. The skipped agent privileged enable and disable examples: the reason is that only root writes the enabled list, and a write would change what each other integration test can do. The unit tests cover them with a list in a temp directory. Left untested: the real run as root, with the group added to the agent's unit and the agent restarted.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards re-review at 0e1a80b, of the commit after 68dc6ef. Approved again.

  • sysctl. It relaxes PrivateDevices, with the reason in least-privilege.md: sysctl --system needs CAP_SYS_RAWIO for vm.mmap_min_addr. A row in sysctl/behavior_public_test.go asserts PrivateDevices=no in the unit.
  • iface. It declares CAP_NET_ADMIN, with a row in its test.
  • file's sum step. It reads only a path that Writes matches. It uses Lstat, so it never follows a link, and it refuses a file that is not regular. steps_public_test.go is a new StepsPublicTestSuite with one table for TestSumStep. It has no custom message, and the new file has its license header.
  • The commit. The subject has 45 characters, and the commit has its trailer. It is a fast-forward on the current origin/main. No em dash.

Notes that do not block:

  • file.Writes is an exported var, and the test assigns it and puts it back in TearDownSubTest. The package usually keeps such a value unexported, with a setter in export_test.go that gives back a restore function, as managedfile and process do. As an exported var, any package can change it.
  • Writes is "*", so the new check lets sum read the SHA-256 of each regular file as root, /etc/shadow too. The check is correct. It limits nothing until file declares narrower paths. The code reviewer can decide whether that needs an issue.

The label stays standards-reviewed.

StopUnit takes a unit that systemd does not have as stopped: exit 5 of
systemctl stop, or "not loaded" from systemctl kill. A watch tick in
the few ms between the end of a unit and the return of systemd-run no
longer fails a good run.

Closes #1962

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review: approved (head 764f368). Checked: 764f368 on 3993dc9 (which I approved), a fast-forward, rebased on main, with its trailer. The two new StopUnit rows (a stop of a unit that is not loaded, and a kill of a unit that ended) are in the one table of TestStopUnit, and each can fail. No custom assertion messages. stopNotLoaded and systemctl have doc comments that match the code. No em dash. The body has Closes #1962 for #1962, and Specs: links specs#756.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at 764f368 (one commit on 3993dc9, based on current main). StopUnit returns nil with no record and no kill when systemctl stop exits 5, and when the kill says "not loaded"; any other stop or kill failure still records, kills and errors. The three rows cover both paths, and the old exit-5 row now uses exit 1. go test -race -cover on internal/privileged: pass, 100.0%. GOOS=linux go vet: clean. Closes #1962 is in the body.

Note, not blocking: Server.run also calls Stop when the agent closes the connection. If that lands before systemd has created the unit, exit 5 is now taken as stopped, where it was an error before; the unit would still end at its RuntimeMaxSec. Neither version stops it, so this is not a regression.

retr0h and others added 2 commits December 5, 2026 21:53
The chain record printed the mode of a managedfile write in decimal,
such as mode=420. The mode is now a behavior.FileMode, whose record is
octal, such as mode=0644, and the step accepts four octal digits.

A refused step read "sysctl create: sysctl write: [err] sysctl write:
...". The step command printed its error with the mark of the terminal,
and privileged.Main named the behavior and the step, which the client
names too. The step command now prints the bare error, and Main adds no
prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
chronyc makes its client socket in /run/chrony, which is chrony's and
0700. In the transient unit, /run was read-only and the bounding set was
empty, so chronyc fell back to UDP, and chronyd refused the command with
"501 Not authorised". The call declares Writes("/run/chrony/*") and
CAP_DAC_OVERRIDE. A systemd-run test with the unit's properties on
ubuntu-1 gave 501 without both, and 200 OK with both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review: approved (head c72b4cc). Checked: 9367cd9 and c72b4cc on 764f368 (which I approved), a fast-forward, rebased on main, each with its trailer. behavior.FileMode and its String have doc comments, and the new row "when a field is a mode, it is octal" is in the one table of the record test and can fail. The managedfile shape [0-7]{4} matches the octal record. The broker error is now bare: cmd/agent_test.go checks clicommand.FailedError and the exact output in the same table, and privileged_public_test.go has the shorter error. No custom assertion messages. The chronyc reload sources call declares Writes("/run/chrony/*") and Needs("CAP_DAC_OVERRIDE"), with a comment that tells why. The capabilities table in specs least-privilege.md already lists only some calls (iface and file are not in it either), so it does not disagree, and the generated ntp page does not change. No panic, no context.Background(), no em dash. specs#756 stays approved at 74023358.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at c72b4cc (two commits on 764f368, based on current main). behavior.FileMode records as %04o. The write step arg is [0-7]{4}, so a mode above 0o7777 is refused, and WriteStep still refuses the setuid, setgid and sticky bits before it takes Perm(). agent privileged run prints the bare error to stderr and exits 1, and Main no longer adds a prefix that the client adds. The ntp call declares Writes("/run/chrony/*") and Needs("CAP_DAC_OVERRIDE"): the argv is fixed ("chronyc reload sources"), CallUnit makes only /run/chrony writable, the bounding set holds only that capability, and the InaccessiblePaths for the secret files still apply because the call is not root-equivalent. go test -race -cover on internal/privileged, internal/behavior, managedfile and ntp: pass, 100.0% each; ./cmd passes. GOOS=linux go vet: clean. gofmt: clean. I did not run the lab.

CAP_DAC_OVERRIDE let the unit of chronyc reload sources read each file
of root that InaccessiblePaths does not hide. chronyd takes commands on
its socket from its own user too, so the call now runs as _chrony with
no capability, and keeps Writes("/run/chrony/*") for its client socket.

A RootCall can run as a user of the host with .As(user): its unit gets
User=. validate refuses As("root"), a name that is not a user name, and
As on a call of macOS, where no unit of systemd changes the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review: approved (head 69724bd). Checked: one commit on c72b4cc (which I approved), a fast-forward, rebased on main, with its trailer. RootCall.As and the User field have doc comments. The new unit row and the five validate rows (a user of the host, As("root"), a name that is not a user name, a call of each platform on a behavior of macOS, a call of macOS) are rows in the existing tables, and each can fail. No custom assertion messages. The DSL page comes from spec.go, and least-privilege.md agrees with the code: User=, no capability, and the reason that it is not CAP_DAC_OVERRIDE. No panic, no context.Background(), no em dash.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at 69724bd (one commit on c72b4cc, based on current main). The chronyc call now has User=_chrony, no capability and ReadWritePaths=/run/chrony; the unit keeps NoNewPrivileges, the empty bounding set and the InaccessiblePaths for the secret files, so this is narrower than CAP_DAC_OVERRIDE. The user comes from the compiled declaration (it is in the hash), never from the request. validate refuses As("root"), a non-user name and As on a macOS call, with a row for each. go test -race -cover on internal/behavior, ntp and internal/privileged: pass, 100.0% each; behaviordsl 100.0%; ./cmd passes. GOOS=linux go vet and gofmt: clean. I did not run the lab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review: approved (head d22a99d). Checked: one commit on 69724bd (which I approved), a fast-forward, rebased on main, with its trailer. It changes only internal/dslcheck/testdata/strings.txt. The two new rows, RootCall.As and RootCall.User, are checked, are in sorted place, and give reasons that agree with the validate rules of 69724bd. No code changed.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at d22a99d. The delta from 69724bd is two lines in internal/dslcheck/testdata/strings.txt, and both are accurate for As and User as reviewed. go test ./internal/dslcheck: pass.

The Check it list of build-a-behavior had no go test ./internal/dslcheck/,
so a new string in the DSL API passed the per-package checks and failed
in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Standards review: approved (head bf3f1af). Checked: one commit on d22a99d (which I approved), a fast-forward, rebased on main, with its trailer. It adds one line to the "Check it" block of internal/skills/resources/dev-skills/build-a-behavior/SKILL.md: go test ./internal/dslcheck/, with a comment that matches what the test checks. No other copy of that check list exists in the repository (your-first-behavior.md shows a shorter walk-through, not the check list), so the fact is in one place. No em dash.

@retr0h

retr0h commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code review: clean at bf3f1af. The delta from d22a99d is one line in the "Check it" block of internal/skills/resources/dev-skills/build-a-behavior/SKILL.md: go test ./internal/dslcheck/, with an accurate comment. The .claude/skills copy is a different, shorter document, so no matching edit is needed. go test ./internal/skills ./internal/dslcheck: pass.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code-reviewed An independent reviewer checked correctness, bugs and edge cases integration Run the integration suite on this pull request kind/action kind/deps kind/docs kind/go kind/ts kind/yaml standards-reviewed An independent reviewer checked this PR against the standards test/unit

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StopUnit fails on a unit that already ended Behaviors declare exact sudo calls; osapi generates and checks the sudoers rules

1 participant