Skip to content

feat(dirctl): embed zot into daemon subcommand - #1422

Merged
arpad-csepi merged 4 commits into
mainfrom
feat/embed-zot-to-daemon
Apr 29, 2026
Merged

arpad-csepi merged 4 commits into
mainfrom
feat/embed-zot-to-daemon

Conversation

@arpad-csepi

@arpad-csepi arpad-csepi commented Apr 27, 2026 •

Copy link
Copy Markdown
Member

This PR switch daemon local OCI storage solution to Zot by adding an optional embedded Zot registry to the dir daemon flow, configured with server.store.oci.local_dir, server.store.oci.registry_address, server.store.oci.repository_name.

When defined, the daemon starts Zot as an daemon process and based on the apiserver OCI store config values.

The k8s.io go packages required to be downgraded because zot go package has older version than latest.

These changes enables to provide sync operation and federation in local development environments which detailed here: #1353

Resolves: #1352

@arpad-csepi arpad-csepi added this to the DIR v1.3 milestone Apr 27, 2026
@arpad-csepi arpad-csepi self-assigned this Apr 27, 2026
@arpad-csepi
arpad-csepi requested a review from a team as a code owner April 27, 2026 17:06
@github-actions github-actions Bot added the size/M Denotes a PR that changes 200-999 lines label Apr 27, 2026
@github-actions

github-actions Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

The latest Buf updates on your PR. Results from workflow Buf CI / verify-proto (pull_request).

BuildFormatLintBreakingUpdated (UTC)
✅ passed⏩ skipped⏩ skipped✅ passedApr 29, 2026, 1:38 PM

@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch 9 times, most recently from c51efbe to 1072454 Compare April 28, 2026 11:28
Comment thread cli/cmd/daemon/config.go Resolved
@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch 9 times, most recently from eabef5c to 5321446 Compare April 28, 2026 15:05
Comment thread server/store/local/local.go Resolved
Comment thread server/store/local/local.go Resolved
Comment thread server/store/oci/config/config.go Resolved
Comment thread server/store/store.go Resolved
Comment thread cli/cmd/daemon/README.md Resolved
@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch 4 times, most recently from 161a3fb to 54762b4 Compare April 29, 2026 12:34
@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch from 54762b4 to 867c98d Compare April 29, 2026 12:37
Comment thread cli/cmd/daemon/start.go Resolved
Comment thread cli/cmd/daemon/start.go Resolved
@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch 2 times, most recently from c15cf03 to 534ce13 Compare April 29, 2026 13:29
@arpad-csepi
arpad-csepi force-pushed the feat/embed-zot-to-daemon branch from 534ce13 to f1bba96 Compare April 29, 2026 13:37

@paralta paralta left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@paralta paralta removed this from the DIR v1.3 milestone Apr 29, 2026
@arpad-csepi
arpad-csepi merged commit 3d9ce74 into main Apr 29, 2026
34 checks passed
@arpad-csepi
arpad-csepi deleted the feat/embed-zot-to-daemon branch April 29, 2026 15:05
keraron pushed a commit to keraron/dir that referenced this pull request May 5, 2026
* chore(dir): format tests taskfile

Signed-off-by: Árpád Csepi <[email protected]>

* feat(dirctl): add embedded zot into daemon

Signed-off-by: Árpád Csepi <[email protected]>

* test(dirctl): add embedded zot test case to daemon

Signed-off-by: Árpád Csepi <[email protected]>

* fix(dir): downgrade k8s packages version to match zot

Signed-off-by: Árpád Csepi <[email protected]>

---------

Signed-off-by: Árpád Csepi <[email protected]>
Signed-off-by: Aron Kerekes <[email protected]>
conorbronsdon added a commit to conorbronsdon/dir that referenced this pull request Jul 31, 2026
Test / Unit failed on cmd/daemon. Not this branch's doing:

  - TestEmbeddedZot predates the branch (added in agntcy#1422); no commit
    here touches daemon_test.go.
  - It passes locally both alone and after the config-init tests, so
    the new tests in this 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.

The job had never run on this branch before now -- it gates on Lint,
which was red until the previous commit -- so this is its first
execution rather than a regression from it.

Signed-off-by: Conor Bronsdon <[email protected]>
conorbronsdon added a commit to conorbronsdon/dir that referenced this pull request Jul 31, 2026
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]>
tkircsi pushed a commit that referenced this pull request Aug 1, 2026
* 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 #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 #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 (#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]>
markpmarton pushed a commit to markpmarton/dir that referenced this pull request Aug 3, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Denotes a PR that changes 200-999 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Implement embedded Zot integration in daemon startup

3 participants