Repository navigation
feat(cli): add dirctl daemon config init command - #1931
Conversation
d709981 to
fe72534
Compare
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Add `dirctl daemon config init`, which writes the daemon's embedded default configuration to disk so it can be customized and passed back in via `--config`. The target defaults to the daemon's resolved config path (<data-dir>/daemon.config.yaml, or an explicit --config), can be overridden with --output, and the write refuses to clobber an existing file unless --force is given. Without --force, the existence check and the write happen as a single filesystem operation (stage to a temp file, then os.Link it onto the target, which fails if the target already exists) instead of a Stat-then-write, closing the TOCTOU window where a file created between the two steps would otherwise be silently clobbered. Documents the new command in dir-cli-reference.md alongside the existing daemon start/stop/status sections. Closes agntcy#1779. Co-Authored-By: Claude <[email protected]> Signed-off-by: Conor Bronsdon <[email protected]>
fe72534 to
8137b62
Compare
| var configInitOpts = &struct { | ||
| Output string | ||
| Force bool | ||
| }{} |
There was a problem hiding this comment.
The convention across cli/cmd is a named struct type paired with a package-level opts. Please, follow this pattern.
There was a problem hiding this comment.
Done in 938b36d3. Named type plus a package-level opts, matching cli/cmd/pull, push, sync, search, import, export, validate, and network/init.
One deviation worth flagging: those packages all use the bare names options/opts, but the daemon package already owns Options/opts for the daemon command itself, so this is configInitOptions/configInitOpts to avoid shadowing it. Say the word if you would rather it live in its own cli/cmd/daemon/config/ package so it can use the bare names.
Also added TestConfigInitCommand_ParsesFlags, which drives the real command with argv. Every existing test called runConfigInit directly with a bare cobra.Command, so flag registration was entirely uncovered: a renamed flag or a wrong binding would not have failed anything.
| // single filesystem operation. A separate os.Stat followed by a write would | ||
| // leave a window where a file created between the two steps gets silently | ||
| // clobbered. | ||
| func writeIfAbsent(path string, data []byte, perm os.FileMode) error { |
There was a problem hiding this comment.
Hm. Maybe we wshould move the cli/internal/agentcfg/fsutil into cli/internal/fsutil and it's test also. Seems to me a common fs package which can be reused by other packages.
There was a problem hiding this comment.
Agreed, and done in 938b36d3: cli/internal/agentcfg/fsutil is now cli/internal/fsutil, with its test. Three import sites updated (cmd/daemon/config_init.go, internal/agentcfg/mcp_engine.go, internal/agentcfg/skill_engine.go), no code changes, and nothing else in the repo referenced the old path.
Your reasoning held up wrt what the package was accumulating. writeIfAbsent in this command was a near-duplicate of fsutil.WriteAtomic, identical through MkdirAll → CreateTemp → defer Remove → Write → Close → Chmod and diverging only at Link vs Rename. Rather than move that duplicate into the newly shared package too, I replaced it with a single O_CREATE|O_EXCL open in 4faf1efc: it closes the same create-if-absent race in one syscall, and it does not need hardlink support, which the previous version did. That mattered as: os.Link fails outright on exFAT, on SMB shares, and in FUSE bind mounts, so --output onto a USB stick or a mounted share failed on the default path while --force succeeded on the same path.
Two other things came out of the same pass, both in 4faf1efc:
configDirPermwas0755whiledaemon startcreates the data directory0700. Since this command is meant to run before the daemon has ever started, it is usually what creates~/.agntcy/dir, andMkdirAllis a no-op on an existing directory, so a laterdaemon startnever repairs the mode. The daemon then writes its peer identity key, database, and object store beneath it. Now0700on both write paths, with a test; nothing asserted directory mode before, which is why it slipped through.- The
gosecsuppression carried over intointernal/fsutilstill said the destination "is a known agent config location resolved by the integrate descriptors, not untrusted input". That stopped being true the moment this command started passing--outputstraight through, so the justification is reworded rather than left asserting a guarantee the code no longer has.
There was a problem hiding this comment.
@conorbronsdon Thank you very much for your cooperation! WDYT about give fsutil both writers and a mode-carrying options struct, so neither call site has to pre-create directories or re-implement chmod, for example
package fsutil
// ErrExists is returned by WriteNew when the target already exists.
var ErrExists = errors.New("file already exists")
// WriteOptions controls the modes applied by the writers. A zero FileMode
// means 0600; a zero DirMode means 0755.
type WriteOptions struct {
FileMode os.FileMode
DirMode os.FileMode
}
// WriteAtomic replaces path's contents atomically (temp file + rename).
func WriteAtomic(path string, data []byte, o WriteOptions) error
// WriteNew creates path, returning ErrExists if it is already there.
// O_CREATE|O_EXCL makes the existence check and the create one syscall.
func WriteNew(path string, data []byte, o WriteOptions) errorBoth funnel through one unexported helper that does MkdirAll(dir, o.DirMode), applies FileMode through the descriptor, and removes the partial file on failure.
config_init.go then keeps only policy and messaging:
func writeDefaultConfig(target string, force, callerChosePath bool) error {
wo := fsutil.WriteOptions{FileMode: configFilePerm, DirMode: dirPermFor(callerChosePath)}
write := fsutil.WriteNew
if force {
write = fsutil.WriteAtomic
}
if err := write(target, []byte(defaultConfigYAML), wo); err != nil {
if errors.Is(err, fsutil.ErrExists) {
return fmt.Errorf("config file already exists at %s (use --force to overwrite)", target)
}
return fmt.Errorf("failed to write default config to %s: %w", target, err)
}
return nil
}The mechanism tests move with the code: mode bits under a restrictive umask, cleanup after a failed write, unwritable parent, directory target — all become table tests over both writers in fsutil, run once instead of once per caller.
There was a problem hiding this comment.
Done in ce0fcef — this is a better shape than what I had, thank you.
fsutil now exports both writers over a shared WriteOptions{FileMode, DirMode} (zero → 0600 / 0755), funnelling through one unexported write(): MkdirAll at o.DirMode, mode applied through the descriptor, partial file removed on any failure. WriteNew returns fsutil.ErrExists, so callers match with errors.Is and phrase their own message — the writers don't know what the file is for.
writeDefaultConfig is now exactly the shape you sketched. config_init.go drops writeIfAbsent, errConfigExists, the pre-create MkdirAll, and the path/filepath import: 235 lines → 161, policy and messaging only.
One thing your sketch surfaced that I hadn't noticed: WriteAtomic was doing os.Chmod(tmpName, perm) on the path, while writeIfAbsent chmod'd through the descriptor. Sharing one implementation forces them to agree, so the atomic path now goes through the descriptor too. That closes a symlink-swap window on the staging file and drops a //nolint:gosec.
The mechanism tests moved as you described — table tests over both writers, run once instead of once per caller: mode bits under a restrictive umask, DirMode on created parents, zero-value defaults, unwritable parent, unreachable parent, directory target, no temp files left behind. Four caller-side tests deleted as redundant (writeIfAbsent's own test, dir-creation-failure, unwritable-directory, plus one that duplicated the existing both-paths directory-target case). config_init_test.go keeps the policy: 0700 for the data dir, 0755 for an --output parent, the --force messaging, flag parsing.
setUmask is build-tagged (syscall.Umask doesn't exist on Windows) with a no-op so GOOS=windows still compiles.
Verified on Linux rather than just on my Windows box, since the umask and DirMode cases only mean anything under POSIX:
fsutil 13 tests, PASS (umask + DirMode cases execute for real)
cmd/daemon 11/11 config-init tests PASS
internal/agentcfg PASS — covers the three other WriteAtomic call sites
gofmt clean on every file touched
TestWritersLeaveNothingBehindWhenParentIsUnwritable skips under my WSL root shell via the existing Geteuid() == 0 guard; it'll run on CI.
The three other WriteAtomic callers (mcp_engine.go, skill_engine.go ×2) took the new signature as fsutil.WriteOptions{FileMode: ...}; a zero DirMode gives them the 0755 they had hard-coded before, so their behaviour is unchanged.
Addresses review on agntcy#1931. - config_init.go used an anonymous struct literal for its flags. The convention across cli/cmd is a named type paired with a package-level opts (cli/cmd/pull, push, sync, search, import, export, validate, network/init). The daemon package already owns Options/opts for the daemon command itself, so this one is configInitOptions/configInitOpts. - Moved cli/internal/agentcfg/fsutil to cli/internal/fsutil, with its test. It was nested under agentcfg when agentcfg was its only consumer; this command made it a second, unrelated one, which is the argument for promoting it. Three import sites updated, no code changes. Coverage: writeDefaultConfig goes from 90% to 100%. Two branches that were uncovered are now exercised: --force pointed at an existing directory (a distinct write path, fsutil.WriteAtomic rather than writeIfAbsent), and a directory the process cannot write to, which fails at the temp-file stage rather than at MkdirAll. The second skips on Windows and as root, where POSIX permission bits do not gate the write. writeIfAbsent's remaining uncovered lines are the tmp.Write, tmp.Close, os.Chmod, and non-ErrExist os.Link failures. Reaching them needs fault injection at the filesystem boundary, which would mean an indirection seam in the function purely for tests; happy to add one if preferred. Signed-off-by: Conor Bronsdon <[email protected]>
…ance Fixes problems an adversarial review of my own branch turned up. Permissions. configDirPerm was 0755 while `daemon start` creates the data directory 0700. This command is meant to run BEFORE the daemon has ever started, so it is usually what creates ~/.agntcy/dir, and MkdirAll is a no-op on an existing directory, so a later `daemon start` never repairs the mode. The daemon then writes its peer identity key, database, and object store under a world-traversable directory. Now 0700 on both write paths: --force goes through fsutil.WriteAtomic, which creates parents at its own 0755, so writeDefaultConfig creates the parent itself first. TestRunConfigInitCreatesDataDirWithRestrictivePerms covers both paths; nothing asserted directory mode before, which is why this shipped. Create-if-absent. Replaced the temp-file-plus-os.Link staging with a single O_CREATE|O_EXCL open. It closes the same race in one syscall with no hardlink support required: the previous version failed outright on exFAT, SMB shares, and FUSE bind mounts, and failed there only on the default path while --force kept working. This writes in place, so a crash mid-write can truncate the file; that is the accepted trade, since the file is new by definition and a truncated YAML config fails loudly. The partial file is removed on any error after creation. This also drops the near-duplicate of fsutil.WriteAtomic that had been sitting in cmd/daemon. Flag registration had no test. Every existing test called runConfigInit directly with a bare cobra.Command, so a renamed flag or a wrong binding would not have failed anything. TestConfigInitCommand_ParsesFlags drives the real command with argv. Docs and comments corrected: the reference said the write was "atomic (temp file + rename)", which described neither path accurately once the default path stopped renaming, and did not mention the modes. The gosec suppression in fsutil still claimed the destination could not be untrusted input, which stopped being true when this command started passing --output straight through. TestRunConfigInitDumpedFileLoadsUnchanged claimed to catch drift between the embedded and dumped config; it cannot, because both loads parse the same bytes, so its comment now says what it actually checks. Signed-off-by: Conor Bronsdon <[email protected]>
Test / E2E / Test Client failed on 'Event Streaming E2E Tests > No events scenario > should timeout when no events occur [Serial]', 106 of 108 specs passing. This branch touches only dirctl daemon config init, cli/internal/fsutil, and docs, none of which are on the event-streaming path; the same job passes on feat/mcp-scanner-coverage in the same window. Signed-off-by: Conor Bronsdon <[email protected]>
… flags A review of the previous commit found the permission fix over-applied, one error path leaking a file, and the flag test unable to fail. The flag test was the blocker. It built its own cobra.Command and registered its own flags, so it exercised cobra rather than this command's registration: renaming --output in init() left it green. withConfigInitState was the cause, swapping the configInitOpts POINTER and orphaning the real command's bindings. It now saves and restores the values, and the test parses argv against configInitCmd itself. Verified by mutation: renaming the flag now fails it, and binding --force to the wrong field fails to compile. The --force half of that test also passed vacuously, since the first run had already written the defaults; it now seeds different content first. 0700 was applied to every parent MkdirAll creates, including for a path the caller named. `config init --output /etc/agntcy/daemon.config.yaml` created /etc/agntcy as 0700, locking out the service account that has to read the file. The mode is now chosen by provenance: 0700 for the daemon's own data directory, 0755 for a caller-named path. Both are covered, and both mutations fail on Linux (they skip on Windows, which is why a Windows-only run reported them as surviving). The directory-target check moved above the force branch. Previously --force on a directory produced a rename error leaking the staging temp file's name, while the non-force path produced the friendly message, so the two disagreed about the same input. chmod now runs through the file descriptor rather than the path, before the write instead of after: os.Chmod follows symlinks and ran after Close, leaving an unbounded window. Its error path also returned without removing the file, contradicting the doc comment two lines above and leaving the next run to report "already exists" for a failure the user did not cause. Corrected two claims rather than leaving them. The doc comment said a truncated config "fails loudly"; it does not, because loadConfig registers defaults before reading, so viper backfills every missing key and the daemon starts on a silently partial config. And the previous commit message blamed exFAT and SMB for the old os.Link failure, but the old code chmod'd before linking, so a chmod-less filesystem failed earlier and --force failed there too; the real argument is FUSE mounts without hardlink support, which stands on its own. The dir-mode assertion checked exact equality against 0700, which fails under a umask of 0200 on a machine that is strictly safer. It now asserts the invariant the message states: no group or world bits. Docs no longer claim 0700 unconditionally, and say plainly that an existing directory keeps its mode. Nothing here repairs a data directory created 0755 by an earlier release; that needs a chmod in daemon start and is called out in the PR thread rather than smuggled in here. Signed-off-by: Conor Bronsdon <[email protected]>
…truct
Per review: neither call site should pre-create directories or
re-implement chmod.
fsutil now exports WriteAtomic and WriteNew over a shared WriteOptions
{FileMode, DirMode}, zero meaning 0600 and 0755. Both funnel through one
unexported write(): MkdirAll at o.DirMode, mode applied through the
descriptor, partial file removed on any failure. WriteNew returns
fsutil.ErrExists so callers match with errors.Is and phrase their own
message; the writers do not know what the file is for.
config_init.go keeps only policy and messaging -- which mode the parent
gets, which writer --force selects, what the user is told. It drops
writeIfAbsent, errConfigExists, the pre-create MkdirAll, and the
path/filepath import: 235 lines to 161.
WriteAtomic now chmods through the descriptor like WriteNew always did,
rather than os.Chmod on the temp path. That closes a symlink-swap window
and lets the two writers share one implementation.
Mechanism tests move to fsutil as table tests over BOTH writers, run
once instead of once per caller: mode bits under a restrictive umask,
DirMode on created parents, zero-value defaults, unwritable parent,
unreachable parent, directory target, no temp files left behind. Three
caller-side tests are deleted as now-redundant (writeIfAbsent's own
test, dir-creation-failure, unwritable-directory) plus one that
duplicated the existing both-paths directory-target case.
config_init_test.go keeps the policy tests: 0700 for the data dir, 0755
for a --output parent, the --force messaging, flag parsing.
The umask test needs syscall.Umask, so setUmask is build-tagged with a
Windows no-op to keep GOOS=windows compiling.
Verified on Linux (WSL): fsutil 13 tests pass with real POSIX
semantics -- the umask and DirMode cases are the ones that only mean
something there. daemon config-init tests 11/11. agentcfg passes, which
covers the three other WriteAtomic call sites updated for the new
signature. gofmt clean on every file touched. (TestEmbeddedZot fails
locally for want of a running registry, unrelated and also red on
the parent commit.)
Signed-off-by: Conor Bronsdon <[email protected]>
golangci-lint flagged require.True(t, errors.Is(...)) as error-is-as, and it was right about more than the call style: the test asserted exactly what TestWriteNewRefusesExistingFile already asserts with require.ErrorIs, just less directly. Removed rather than rewritten, with the errors.Is contract noted on the test that remains. Verified with golangci-lint v2.11.3, the version CI installs, against the repo's own .golangci.yml: 0 issues in ./internal/fsutil/... Signed-off-by: Conor Bronsdon <[email protected]>
Two consecutive infrastructure failures on a branch whose code has not changed since 6de099b: Test / Unit cmd/daemon TestEmbeddedZot. Predates this branch (agntcy#1422); no commit here touches daemon_test.go. Passes locally both alone and after the config-init tests, so the new tests in that package do not pollute it -- withConfigInitState saves and restores opts/configInitOpts by value in t.Cleanup. It is timing-dependent on zot readiness: one local run failed after 10s on connection-refused, later runs pass in ~1.2s. Verify `buf dep update` -> permission_denied: 403 Forbidden, a registry auth/rate response. Verify SUCCEEDED on ce0fcef, e7326a2 and 6de099b, and failed only on an EMPTY commit, which cannot change generated code. Signed-off-by: Conor Bronsdon <[email protected]>
ee4ccf9 to
635f5b7
Compare
|
Correcting myself on the The CI task pipes stdout to The failure is It makes an unconditional live HTTPS call to Unrelated to this branch:
Happy to leave it for a retrigger. If it's worth addressing separately, the durable fix is to gate that test on an env var or an explicit build tag so a remote schema service can't make the unit job red — it's a network integration test living in the unit suite. I didn't touch it here since it's outside this PR's scope, but I can open a separate issue if useful. Apologies for the earlier misattribution — I named |
|
The one red check here —
Merging #1953 first should clear this one. |
Two gaps an adversarial review found, both in tests this refactor's own commit message cites as its justification. 1. "the partial file is removed on any failure" was asserted nowhere. The two leave-nothing-behind tests both fail BEFORE anything is created -- one at MkdirAll, one at open -- and the second skips as root. Gutting cleanup() and both post-create os.Remove calls left the suite green. TestWritersRejectDirectoryTarget already reaches the one post-create failure a test can trigger: the atomic path stages a temp file and then fails at the rename. It now asserts the parent directory is unchanged, which kills that mutant. Stated plainly rather than overclaimed: this covers the rename branch. The chmod-, write- and close-failure branches still survive mutation, because reaching them needs fault injection rather than a better assertion -- a bigger change than a test fix, and one I did not want to smuggle into a PR under review. 2. TestWritersZeroOptionsUseDefaults asserted the defaults against themselves. Changing defaultFileMode to 0o644 -- making every config file this package writes world-readable -- passed the whole suite, and the daemon tests miss it too because config_init.go always passes both modes explicitly. Now written as literals: both mutants die. Verified: fsutil 27 subtests pass, daemon config-init passes, gofmt clean on the committed (LF) form, golangci-lint v2.11.3 reports no issues on the LF form. Each mutation was confirmed to actually apply to the file before its result was believed. Signed-off-by: Conor Bronsdon <[email protected]>
TestWritersApplyFileModeUnderRestrictiveUmask set umask 0o277 for the whole test, then called t.TempDir() inside each subtest. MkdirTemp asks for 0700, the umask masks that down to 0500 — no owner-write — and t.TempDir then creates a numbered subdirectory inside it, which fails with EACCES. Only for non-root users. Root bypasses the DAC check, so the test passes locally and fails on CI runners, which is why the earlier retrigger did not help: it was never an infra flake. Verified as a non-root user on ext4 (the only setup that reproduces it — running as root passes either way, and /mnt/... DrvFs mounts fake POSIX permissions, so neither is a valid test for this): before: FAIL, TempDir: mkdir .../001: permission denied after: ok, 21 packages, coverage unchanged at 82.9% The umask only has to cover the write being asserted, so hoisting the TempDir call above it preserves what the test is for. Signed-off-by: Conor Bronsdon <[email protected]>
* feat(cli): add dirctl daemon config init command Add `dirctl daemon config init`, which writes the daemon's embedded default configuration to disk so it can be customized and passed back in via `--config`. The target defaults to the daemon's resolved config path (<data-dir>/daemon.config.yaml, or an explicit --config), can be overridden with --output, and the write refuses to clobber an existing file unless --force is given. Without --force, the existence check and the write happen as a single filesystem operation (stage to a temp file, then os.Link it onto the target, which fails if the target already exists) instead of a Stat-then-write, closing the TOCTOU window where a file created between the two steps would otherwise be silently clobbered. Documents the new command in dir-cli-reference.md alongside the existing daemon start/stop/status sections. Closes agntcy#1779. Co-Authored-By: Claude <[email protected]> Signed-off-by: Conor Bronsdon <[email protected]> * refactor(cli): adopt the named-options convention and promote fsutil Addresses review on agntcy#1931. - config_init.go used an anonymous struct literal for its flags. The convention across cli/cmd is a named type paired with a package-level opts (cli/cmd/pull, push, sync, search, import, export, validate, network/init). The daemon package already owns Options/opts for the daemon command itself, so this one is configInitOptions/configInitOpts. - Moved cli/internal/agentcfg/fsutil to cli/internal/fsutil, with its test. It was nested under agentcfg when agentcfg was its only consumer; this command made it a second, unrelated one, which is the argument for promoting it. Three import sites updated, no code changes. Coverage: writeDefaultConfig goes from 90% to 100%. Two branches that were uncovered are now exercised: --force pointed at an existing directory (a distinct write path, fsutil.WriteAtomic rather than writeIfAbsent), and a directory the process cannot write to, which fails at the temp-file stage rather than at MkdirAll. The second skips on Windows and as root, where POSIX permission bits do not gate the write. writeIfAbsent's remaining uncovered lines are the tmp.Write, tmp.Close, os.Chmod, and non-ErrExist os.Link failures. Reaching them needs fault injection at the filesystem boundary, which would mean an indirection seam in the function purely for tests; happy to add one if preferred. Signed-off-by: Conor Bronsdon <[email protected]> * fix(cli): create the data dir 0700 and use O_EXCL instead of a link dance Fixes problems an adversarial review of my own branch turned up. Permissions. configDirPerm was 0755 while `daemon start` creates the data directory 0700. This command is meant to run BEFORE the daemon has ever started, so it is usually what creates ~/.agntcy/dir, and MkdirAll is a no-op on an existing directory, so a later `daemon start` never repairs the mode. The daemon then writes its peer identity key, database, and object store under a world-traversable directory. Now 0700 on both write paths: --force goes through fsutil.WriteAtomic, which creates parents at its own 0755, so writeDefaultConfig creates the parent itself first. TestRunConfigInitCreatesDataDirWithRestrictivePerms covers both paths; nothing asserted directory mode before, which is why this shipped. Create-if-absent. Replaced the temp-file-plus-os.Link staging with a single O_CREATE|O_EXCL open. It closes the same race in one syscall with no hardlink support required: the previous version failed outright on exFAT, SMB shares, and FUSE bind mounts, and failed there only on the default path while --force kept working. This writes in place, so a crash mid-write can truncate the file; that is the accepted trade, since the file is new by definition and a truncated YAML config fails loudly. The partial file is removed on any error after creation. This also drops the near-duplicate of fsutil.WriteAtomic that had been sitting in cmd/daemon. Flag registration had no test. Every existing test called runConfigInit directly with a bare cobra.Command, so a renamed flag or a wrong binding would not have failed anything. TestConfigInitCommand_ParsesFlags drives the real command with argv. Docs and comments corrected: the reference said the write was "atomic (temp file + rename)", which described neither path accurately once the default path stopped renaming, and did not mention the modes. The gosec suppression in fsutil still claimed the destination could not be untrusted input, which stopped being true when this command started passing --output straight through. TestRunConfigInitDumpedFileLoadsUnchanged claimed to catch drift between the embedded and dumped config; it cannot, because both loads parse the same bytes, so its comment now says what it actually checks. Signed-off-by: Conor Bronsdon <[email protected]> * chore: retrigger CI (e2e event-streaming timeout flake) Test / E2E / Test Client failed on 'Event Streaming E2E Tests > No events scenario > should timeout when no events occur [Serial]', 106 of 108 specs passing. This branch touches only dirctl daemon config init, cli/internal/fsutil, and docs, none of which are on the event-streaming path; the same job passes on feat/mcp-scanner-coverage in the same window. Signed-off-by: Conor Bronsdon <[email protected]> * fix(cli): scope the 0700 mode, close the chmod gap, and test the real flags A review of the previous commit found the permission fix over-applied, one error path leaking a file, and the flag test unable to fail. The flag test was the blocker. It built its own cobra.Command and registered its own flags, so it exercised cobra rather than this command's registration: renaming --output in init() left it green. withConfigInitState was the cause, swapping the configInitOpts POINTER and orphaning the real command's bindings. It now saves and restores the values, and the test parses argv against configInitCmd itself. Verified by mutation: renaming the flag now fails it, and binding --force to the wrong field fails to compile. The --force half of that test also passed vacuously, since the first run had already written the defaults; it now seeds different content first. 0700 was applied to every parent MkdirAll creates, including for a path the caller named. `config init --output /etc/agntcy/daemon.config.yaml` created /etc/agntcy as 0700, locking out the service account that has to read the file. The mode is now chosen by provenance: 0700 for the daemon's own data directory, 0755 for a caller-named path. Both are covered, and both mutations fail on Linux (they skip on Windows, which is why a Windows-only run reported them as surviving). The directory-target check moved above the force branch. Previously --force on a directory produced a rename error leaking the staging temp file's name, while the non-force path produced the friendly message, so the two disagreed about the same input. chmod now runs through the file descriptor rather than the path, before the write instead of after: os.Chmod follows symlinks and ran after Close, leaving an unbounded window. Its error path also returned without removing the file, contradicting the doc comment two lines above and leaving the next run to report "already exists" for a failure the user did not cause. Corrected two claims rather than leaving them. The doc comment said a truncated config "fails loudly"; it does not, because loadConfig registers defaults before reading, so viper backfills every missing key and the daemon starts on a silently partial config. And the previous commit message blamed exFAT and SMB for the old os.Link failure, but the old code chmod'd before linking, so a chmod-less filesystem failed earlier and --force failed there too; the real argument is FUSE mounts without hardlink support, which stands on its own. The dir-mode assertion checked exact equality against 0700, which fails under a umask of 0200 on a machine that is strictly safer. It now asserts the invariant the message states: no group or world bits. Docs no longer claim 0700 unconditionally, and say plainly that an existing directory keeps its mode. Nothing here repairs a data directory created 0755 by an earlier release; that needs a chmod in daemon start and is called out in the PR thread rather than smuggled in here. Signed-off-by: Conor Bronsdon <[email protected]> * refactor(cli): give fsutil both writers and a mode-carrying options struct Per review: neither call site should pre-create directories or re-implement chmod. fsutil now exports WriteAtomic and WriteNew over a shared WriteOptions {FileMode, DirMode}, zero meaning 0600 and 0755. Both funnel through one unexported write(): MkdirAll at o.DirMode, mode applied through the descriptor, partial file removed on any failure. WriteNew returns fsutil.ErrExists so callers match with errors.Is and phrase their own message; the writers do not know what the file is for. config_init.go keeps only policy and messaging -- which mode the parent gets, which writer --force selects, what the user is told. It drops writeIfAbsent, errConfigExists, the pre-create MkdirAll, and the path/filepath import: 235 lines to 161. WriteAtomic now chmods through the descriptor like WriteNew always did, rather than os.Chmod on the temp path. That closes a symlink-swap window and lets the two writers share one implementation. Mechanism tests move to fsutil as table tests over BOTH writers, run once instead of once per caller: mode bits under a restrictive umask, DirMode on created parents, zero-value defaults, unwritable parent, unreachable parent, directory target, no temp files left behind. Three caller-side tests are deleted as now-redundant (writeIfAbsent's own test, dir-creation-failure, unwritable-directory) plus one that duplicated the existing both-paths directory-target case. config_init_test.go keeps the policy tests: 0700 for the data dir, 0755 for a --output parent, the --force messaging, flag parsing. The umask test needs syscall.Umask, so setUmask is build-tagged with a Windows no-op to keep GOOS=windows compiling. Verified on Linux (WSL): fsutil 13 tests pass with real POSIX semantics -- the umask and DirMode cases are the ones that only mean something there. daemon config-init tests 11/11. agentcfg passes, which covers the three other WriteAtomic call sites updated for the new signature. gofmt clean on every file touched. (TestEmbeddedZot fails locally for want of a running registry, unrelated and also red on the parent commit.) Signed-off-by: Conor Bronsdon <[email protected]> * test(cli): drop the redundant ErrExists assertion (testifylint) golangci-lint flagged require.True(t, errors.Is(...)) as error-is-as, and it was right about more than the call style: the test asserted exactly what TestWriteNewRefusesExistingFile already asserts with require.ErrorIs, just less directly. Removed rather than rewritten, with the errors.Is contract noted on the test that remains. Verified with golangci-lint v2.11.3, the version CI installs, against the repo's own .golangci.yml: 0 issues in ./internal/fsutil/... Signed-off-by: Conor Bronsdon <[email protected]> * chore: retrigger CI (infra flakes, not this diff) Two consecutive infrastructure failures on a branch whose code has not changed since 6de099b: Test / Unit cmd/daemon TestEmbeddedZot. Predates this branch (agntcy#1422); no commit here touches daemon_test.go. Passes locally both alone and after the config-init tests, so the new tests in that package do not pollute it -- withConfigInitState saves and restores opts/configInitOpts by value in t.Cleanup. It is timing-dependent on zot readiness: one local run failed after 10s on connection-refused, later runs pass in ~1.2s. Verify `buf dep update` -> permission_denied: 403 Forbidden, a registry auth/rate response. Verify SUCCEEDED on ce0fcef, e7326a2 and 6de099b, and failed only on an EMPTY commit, which cannot change generated code. Signed-off-by: Conor Bronsdon <[email protected]> * test(cli): cover the post-create cleanup and pin the mode defaults Two gaps an adversarial review found, both in tests this refactor's own commit message cites as its justification. 1. "the partial file is removed on any failure" was asserted nowhere. The two leave-nothing-behind tests both fail BEFORE anything is created -- one at MkdirAll, one at open -- and the second skips as root. Gutting cleanup() and both post-create os.Remove calls left the suite green. TestWritersRejectDirectoryTarget already reaches the one post-create failure a test can trigger: the atomic path stages a temp file and then fails at the rename. It now asserts the parent directory is unchanged, which kills that mutant. Stated plainly rather than overclaimed: this covers the rename branch. The chmod-, write- and close-failure branches still survive mutation, because reaching them needs fault injection rather than a better assertion -- a bigger change than a test fix, and one I did not want to smuggle into a PR under review. 2. TestWritersZeroOptionsUseDefaults asserted the defaults against themselves. Changing defaultFileMode to 0o644 -- making every config file this package writes world-readable -- passed the whole suite, and the daemon tests miss it too because config_init.go always passes both modes explicitly. Now written as literals: both mutants die. Verified: fsutil 27 subtests pass, daemon config-init passes, gofmt clean on the committed (LF) form, golangci-lint v2.11.3 reports no issues on the LF form. Each mutation was confirmed to actually apply to the file before its result was believed. Signed-off-by: Conor Bronsdon <[email protected]> * test(cli): create TempDir before narrowing the umask TestWritersApplyFileModeUnderRestrictiveUmask set umask 0o277 for the whole test, then called t.TempDir() inside each subtest. MkdirTemp asks for 0700, the umask masks that down to 0500 — no owner-write — and t.TempDir then creates a numbered subdirectory inside it, which fails with EACCES. Only for non-root users. Root bypasses the DAC check, so the test passes locally and fails on CI runners, which is why the earlier retrigger did not help: it was never an infra flake. Verified as a non-root user on ext4 (the only setup that reproduces it — running as root passes either way, and /mnt/... DrvFs mounts fake POSIX permissions, so neither is a valid test for this): before: FAIL, TempDir: mkdir .../001: permission denied after: ok, 21 packages, coverage unchanged at 82.9% The umask only has to cover the write being asserted, so hoisting the TempDir call above it preserves what the test is for. Signed-off-by: Conor Bronsdon <[email protected]> --------- Signed-off-by: Conor Bronsdon <[email protected]> Co-authored-by: Claude <[email protected]>
What
Adds
dirctl daemon config init, a command that writes the daemon's embeddeddefault configuration (
daemon.config.yaml) to disk so it can be edited andpassed back in via
--config.Why
Closes #1779.
dirctl daemon startloads configuration in one of two ways: an embeddeddefault when no
--configis given, or a user-supplied file read as-is withno defaults merged. There was no way to get a starting point for a custom
config short of copying the file out of the source tree, so this adds a
command that dumps the exact embedded default to disk.
How
daemon configcommand group with a singleinitsubcommand(
cli/cmd/daemon/config_init.go).Options.ConfigFilePath()logic:
<data-dir>/daemon.config.yamlby default, or the daemon's--configpath if one was passed on the parent command.--output/-ooverrides the target path explicitly (same flag/shorthandas
dirctl network init).--forceallows overwriting an existing file; without it the commandrefuses to touch a file that already exists.
--force, the write goes through the existingfsutil.WriteAtomichelper (temp file in the same directory + rename), so a failed or
interrupted write never leaves a partial config file behind.
--force, the existence check and the write are a singlefilesystem operation, not a
Stat-then-write: the new content is stagedin a temp file and then attached to the target path with
os.Link, whichitself fails with
fs.ErrExistif the path already exists. This closesthe TOCTOU window a plain "check, then write" would have between a
concurrent process creating the file and this command overwriting it.
defaultConfigYAMLstring verbatim(comments included), not a re-serialized/effective config, so it stays
identical to what
dirctl daemon startuses when no--configis given.docs/content/dir/dir-cli-reference.md: a new### dirctl daemon config initsubsection under Daemon Operations, andconfig initadded to the command-groups summary table.Testing
go build ./...(cli module) — cleango vet ./...(cli module) — cleango test ./cmd/daemon/...— all passing (9/9), including new tests:--force--force--output--configset on the parentdaemoncommandwriteIfAbsentrejects an existing file with no partial/leftover tempfile, exercising the atomic no-force write path directly
loadConfig()— asserted withfull-struct equality (
require.Equal) between the config loaded fromthe embedded default and the config loaded from the dumped file, not
just a single field
gofmt -l/goimports -l— cleangolangci-lint run— could not run locally: the installed 2.5.0 binary isbuilt with go1.25 and refuses to lint a module targeting go1.26.5
(
cli/go.mod). This is a local toolchain/version mismatch, not specific tothis change — the same error occurs on unrelated, pre-existing packages in
the repo.
Open questions (from the issue, left for maintainer input)
<data-dir>/daemon.config.yamlwhen present,even without
--config? Not implemented here —loadConfig()behavior isunchanged, so a dumped file only takes effect once passed via
--config.daemon config initsubcommand from the issue'sproposal, not a
--dump-configflag ondaemon start. The acceptancecriteria only require one way to get the default config onto disk; happy
to add the flag too if maintainers want both entry points.