Skip to content

packages/ak-common/config: keep watching files that are replaced - #27833

Merged
BeryJu merged 2 commits into
goauthentik:mainfrom
dcoppa:fix/config-watcher-replaced-files
Nov 15, 2026
Merged

BeryJu merged 2 commits into
goauthentik:mainfrom
dcoppa:fix/config-watcher-replaced-files

Conversation

@dcoppa

@dcoppa dcoppa commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Details

What does this PR change?

The Rust config watcher (packages/ak-common/src/config) keeps detecting changes to file:// values whose files are replaced rather than written to.

  • After each detected change, it sets up a new watcher on the same paths, which follows them to the new files, and drops the previous watcher with all its watches. The new watcher only takes over if that loses none of the previous watcher's watches.
  • It also watches each file's directory, to catch files created after startup.
  • A file counts as changed when an event names it or its real path while it exists, or when it now resolves to a different file or to none: a deleted file reloads so that its ?fallback applies.
  • Failed watches are logged instead of stopping authentik (error! when the inotify watch limit is reached). Change notifications are coalesced into one pending reload.

Why is this change needed?

A file:// value is only reloaded the first time its file is replaced. This is the inotify behaviour described in https://ahmet.im/blog/kubernetes-inotify/: the kubelet updates mounted Secrets and ConfigMaps by repointing ..data and deleting the old directory, which takes the watch away with the old file. Deleting the old file also emits IN_ATTRIB, which notify reports as Modify(Metadata), so the first update is picked up and later ones are missed.

With AUTHENTIK_POSTGRESQL__PASSWORD=file://… from a rotated Secret, the Rust database pool kept the old password after a pod's second rotation, and the server's readiness check failed until the pod was restarted.

The motivation for this fix is to no longer need Reloader to restart the authentik pods after every database password rotation. authentik already re-reads file:// values when it opens a connection, so with a watcher that keeps working, the running processes pick up the new password on their own. For now we restart the pods with Reloader as a workaround.

Why the watcher is rebuilt instead of re-armed

Calling watch() again on the existing watcher looks simpler, but notify keys watches by path:

  • On Linux, re-adding a path that now resolves to a different file adds a watch for the new inode and keeps the old one whenever the old file still exists, e.g. a symlink repointed to a new target. Watches grow with every reload until the inotify limit is reached.
  • On macOS, the FSEvents backend appends the path to its stream again on every call, registering duplicates.
  • When notify drops a dead watch, it also removes every watch below that path by prefix. With nested Secret keys (items: [{key: password, path: sub/password}], where the kubelet only symlinks sub), a late DELETE_SELF for the old sub directory removed the watches that had just been added again below it.

A fresh watcher avoids all three: the previous watcher and its watches are released together when it is dropped, and its bookkeeping cannot affect the new one.

How the fallback preserves the existing watches

The new watcher is fully set up before the previous one is dropped, so no change goes unnoticed in between. The handover only happens if the new watcher watches every path the current one watches. A file that no longer exists is the exception, as long as the new watcher watches its directory, which notices the file coming back. Otherwise the current watch is the only one that can, for example after the file was renamed away inside a directory that cannot be listed:

  • If the new watcher cannot be created, for example because no inotify instance is left, the current watcher is kept.
  • If it cannot watch a path the current watcher watches, for example because the file is no longer readable, or inotify watches run out while both watchers exist, it is dropped first, releasing its watches, and the current watcher is kept.

In both cases the current watcher then adds the paths again. A watch it cannot set up again stays in place, since notify leaves an existing inotify watch untouched when re-adding it fails. Adding the paths again still follows replaced files, but keeps watching the files they replaced, so it is only a fallback. An FSEvents watcher (macOS) is left as is instead: notify stops and restarts its stream to add a path, so a failing restart would leave it stopped, and the path would be added a second time.

How was this tested?

Watcher tests, run against a real watcher:

  • kubelet updates (new timestamped directory, ..data repointed, old directory deleted), three times in a row, for a flat key (watcher_kubelet_atomic_write), a nested key (…_nested_key), and a nested key with a pause between deleting the old files and their directory (…_nested_key_slow_cleanup, which reliably triggers the prefix-removal case above)
  • a symlink into a kubelet volume (watcher_symlink_into_kubelet_volume)
  • replacing the file by renaming a new one over it (watcher_atomic_rename)
  • a directory that is traversable but not readable, written in place and then replaced twice (watcher_unreadable_dir)
  • a file made unreadable, then restored and written, which must not drop the watch that still works (watcher_file_temporarily_unreadable)
  • renaming the file away and back, then writing to it, in a readable directory and in one that cannot be listed (watcher_file_renamed_away_and_back, …_in_unreadable_dir)
  • a deleted file falling back to its ?fallback value and reloading once it is created again (watcher_file_removed_uses_fallback)
  • a file:// file created after startup (watcher_file_created_later)
  • the number of inotify watches stays constant across ten symlink switches whose old targets are kept (watcher_does_not_leak_watches)

Unit tests for the change detection rules (change_detector_*): reads and unrelated files are ignored; renaming the file away or deleting it reloads once, and again once it exists, but events in between do not; a symlink pointing elsewhere counts as a change; dropped events (queue overflow) count as a change; events reported by the file's or directory's real path are recognized.

Unit tests for the handover (hand_over_*), using a test double for the watcher: the new watcher replaces the current one; a missing file in a watched directory, or a path the current watcher could not watch either, does not block the handover; a missing file whose directory is not watched keeps the current watcher; the current watcher is kept and re-armed when the new one cannot watch a path the current one watches, runs out of inotify watches, or cannot be created; a watch the current watcher cannot set up again is kept; an FSEvents watcher kept as the fallback is not asked to watch the paths again.

Each new rule was also removed on purpose to confirm a test catches it.

Runtime validation was on Linux (inotify). macOS behaviour (real-path event reporting, duplicate registration, and leaving a kept FSEvents watcher untouched because re-adding a path restarts its stream) was reviewed against notify's FSEvents implementation but not run.

Commands: make all, plus cargo nextest run -p authentik-common (all 81 tests, including db::tests against a local PostgreSQL), the watcher tests repeated 10 times, cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --check.

When running the watcher tests in parallel on a workstation, low fs.inotify.max_user_watches / max_user_instances limits can make them fail spuriously, because creating a watcher or adding a watch fails.

Known limits, none of them regressions:

  • A symlinked directory repointed while its old target is kept (e.g. current -> releases/v2 with v1 left in place) produces no events on the watched paths, so it is not reloaded. Kubelet volumes are unaffected because the kubelet deletes the old directory.
  • If a file's parent directory is deleted and recreated, the watches are lost and are not set up again.
  • In a directory that cannot be listed, only the file itself can be watched, so a file deleted and then created again there is not noticed.
  • file:// paths introduced by a later config edit are still not watched (unchanged from main).

Linked issues

None.


Checklist

  • The project has been linted, built, and tested (make all)
  • The documentation has been updated and formatted (make docs)
  • I have read the AI usage policy.

AI disclosure: the investigation, the fix and the tests were done with Claude Code (Claude Opus 5.5), with several review rounds by a second AI agent. I reviewed the change and checked the behaviour against the kubelet and notify source.

The config watcher put an inotify watch on each file:// path and reacted
to Modify events only. A file that is replaced rather than written to
takes that watch away: the kubelet updates a mounted Secret or ConfigMap
by repointing the ..data symlink and deleting the old files. The first
replacement was still noticed (deleting the old file emits IN_ATTRIB),
but later changes were not, so the database pool kept a rotated
password's old value until the process restarted.

After each detected change, set up a new watcher, which follows the
paths to the new files, and drop the previous one with all its watches.
Adding the paths again to the same watcher would keep watching files
that were replaced but still exist, and on macOS registers duplicates.
The new watcher only takes over if it watches every path the current
one watches, apart from files that no longer exist in a directory it
watches; otherwise, or if it cannot be created, the current one is kept
and, unless it uses FSEvents, whose stream that would restart, watches
the paths again. Each file's directory is watched too, to catch files
created after startup. A file counts as changed when an event names it
or its real path while it exists, or when it now resolves to a
different file or to none, so a deleted file falls back to its
?fallback value. Failed watches are logged instead of stopping
authentik; running out of inotify watches is logged as an error.

With this fixed, a rotated database password no longer requires
restarting the pods, for example with Reloader.
@dcoppa
dcoppa requested a review from a team as a code owner November 15, 2026 20:47
@netlify

netlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

👷 Deploy request for authentik-storybook accepted.

Name Link
🔨 Latest commit af8919c
🔍 Latest deploy log https://app.netlify.com/projects/authentik-storybook/deploys/6afa1a754d21eb2ae3405956

@netlify

netlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

👷 Deploy request for authentik-integrations accepted.

Name Link
🔨 Latest commit af8919c
🔍 Latest deploy log https://app.netlify.com/projects/authentik-integrations/deploys/6afa1a75a31cc437c6c46c7a

@netlify

netlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

👷 Deploy request for authentik-docs accepted.

Name Link
🔨 Latest commit af8919c
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6afa1a750b3ffafc7546a1ef

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.04%. Comparing base (dd0a703) to head (ac0baf6).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #27833      +/-   ##
==========================================
- Coverage   93.07%   93.04%   -0.04%     
==========================================
  Files        1238     1238              
  Lines       86559    86559              
  Branches     4894     4894              
==========================================
- Hits        80564    80538      -26     
- Misses       5908     5934      +26     
  Partials       87       87              
Flag Coverage Δ
conformance 30.33% <ø> (+<0.01%) ⬆️
e2e 34.97% <ø> (+<0.01%) ⬆️
integration 27.51% <ø> (-0.32%) ⬇️
rust 51.12% <ø> (ø)
unit 94.60% <ø> (+<0.01%) ⬆️
unit-migrate 94.61% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

Signed-off-by: Jens Langhammer <[email protected]>
@BeryJu BeryJu added area:backend backport/version-2026.8 Add this label to PRs to backport changes to version-2026.8 labels Nov 15, 2026
@BeryJu
BeryJu merged commit 4aca875 into goauthentik:main Nov 15, 2026
164 checks passed
@authentik-cherry-pick

Copy link
Copy Markdown
Contributor

🍒 Cherry-pick to version-2026.8 created: #27834

dominic-r added a commit that referenced this pull request Nov 16, 2026
…rry-pick #27833 to version-2026.8) (#27834)

* packages/ak-common/config: keep watching files that are replaced (#27833)

* packages/ak-common/config: keep watching files that are replaced

The config watcher put an inotify watch on each file:// path and reacted
to Modify events only. A file that is replaced rather than written to
takes that watch away: the kubelet updates a mounted Secret or ConfigMap
by repointing the ..data symlink and deleting the old files. The first
replacement was still noticed (deleting the old file emits IN_ATTRIB),
but later changes were not, so the database pool kept a rotated
password's old value until the process restarted.

After each detected change, set up a new watcher, which follows the
paths to the new files, and drop the previous one with all its watches.
Adding the paths again to the same watcher would keep watching files
that were replaced but still exist, and on macOS registers duplicates.
The new watcher only takes over if it watches every path the current
one watches, apart from files that no longer exist in a directory it
watches; otherwise, or if it cannot be created, the current one is kept
and, unless it uses FSEvents, whose stream that would restart, watches
the paths again. Each file's directory is watched too, to catch files
created after startup. A file counts as changed when an event names it
or its real path while it exists, or when it now resolves to a
different file or to none, so a deleted file falls back to its
?fallback value. Failed watches are logged instead of stopping
authentik; running out of inotify watches is logged as an error.

With this fixed, a rotated database password no longer requires
restarting the pods, for example with Reloader.

* cleanup

Signed-off-by: Jens Langhammer <[email protected]>

---------

Signed-off-by: Jens Langhammer <[email protected]>
Co-authored-by: Jens Langhammer <[email protected]>

* Fix Spelling

Signed-off-by: Dominic Roy <[email protected]>

---------

Signed-off-by: Jens Langhammer <[email protected]>
Signed-off-by: Dominic Roy <[email protected]>
Co-authored-by: David Coppa <[email protected]>
Co-authored-by: Jens Langhammer <[email protected]>
Co-authored-by: Dominic Roy <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:backend backport/version-2026.8 Add this label to PRs to backport changes to version-2026.8

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants