Skip to content

providers/ldap: fix memory leak in the cached searcher - #26028

Merged
BeryJu merged 2 commits into
goauthentik:mainfrom
dfpc-coe:outposts/ldap-memory-searcher-snapshot
Sep 11, 2026
Merged

BeryJu merged 2 commits into
goauthentik:mainfrom
dfpc-coe:outposts/ldap-memory-searcher-snapshot

Conversation

@cheesegrits

@cheesegrits cheesegrits commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

My knowledge of Go is not great, so I leaned on Claude (Fable) hard for this. I have reviewed the code to the best of my ability, but cannot be sure it introduces no side effects. If you would rather take a different approach, please treat this PR as a demonstration of the bug and a proof-of-concept fix.

Our production environment is the statewide TAK service for all of Colorado's first responders, so reliability and uptime are critical. We simply had to get something into production now, as the leak was killing our LDAP outposts on a daily basis.

Details

What does this PR change?

The cached (memory) searcher stored &ms.users[i] on a bind DN's UserFlags.UserInfo the first time a non-searching user searched, and nothing ever cleared it. Each fetch() replaces ms.users, so every stored pointer kept an entire superseded copy of the directory alive for the life of the process.

This replaces the two bare slices with an immutable snapshot (users, groups and a pk-to-index map) behind an atomic.Pointer. fetch() builds a new snapshot and swaps it; Search() loads the snapshot once per request, resolves the bound user by pk against the current one and copies the value for the duration of the request. The memory searcher no longer writes to the per-DN flags at all.

Side effects of the same change: a non-searching user's own entry (memberOf) now follows the cache across refreshes instead of being frozen at its first-search state; the per-request linear scan over all users becomes a map lookup; and the unsynchronised replacement of ms.users while searches are running is gone.

UserFlags.UserInfo is left in place because the direct searcher still uses it as a one-user cache; that has the same staleness (one object per DN, not a slice copy) and could be a follow-up.

Why is this change needed?

On a directory of ~5.8k users / 2.2k groups / 68k memberships, each distinct password-authenticated user's first search after an outpost start pinned a ~100–160 MB copy of the users slice until the process was killed. With TAK Server as the LDAP client (every password login and every per-client poll is a base-scope self-read bound as the user), our two outposts climbed from ~5% to their memory limit and were OOM-killed roughly daily.

Measured on a lab outpost (2026.5.0, same protocol before and after): resting live heap after one ordinary user's first search went from +105 MB / +1.30 M objects to +1.1 MB / +10.7 k objects, and stayed flat over the following refreshes. Superusers (search_full_directory) were never affected, which is consistent with the branch they take.

In production (two outposts, ~5.8k users / 2.2k groups, TAK Server + CloudTAK as the clients), this change has been running since 2026-09-09. Before it, task memory climbed from ~10% to the limit and was OOM-killed roughly daily; since the deploy it has stayed flat at ~12% (charts below). CPU maximum on the tasks also dropped by roughly half, which matches removing the per-request scan over every user. I will update this PR as the production soak continues.

[3-day ECS TaskMemoryUtilization and TaskCpuUtilization for the 8gb memory outpost service, deploy marker 2026-09-09]

image (2) image (3)

How was this tested?

  • New test TestMemorySearcherRefreshesUserEntry (internal/outpost/ldap/search_memory_test.go): a fake core over httptest serves users and groups; a non-searching user's self-read must reflect a group change after the searcher is re-initialised the way Refresh() does, and the DN's flags must hold no user pointer afterwards. It fails on the previous code on both counts and passes with this change (go test -race clean).
  • go test ./internal/outpost/ldap/..., go vet, gofmt clean.
  • Lab reproduction: patched outpost image built from version/2026.5.0 plus this commit, driven by the same LDAP client sequence as the unpatched run, sampled via the Prometheus endpoint every 10 s (numbers above).
  • Production: the same commit cherry-picked onto version/2026.8.1, built with the release toolchain and flags, deployed 2026-09-09; memory and CPU charts above, login failure rate unchanged.

Linked issues


Checklist

  • The project has been linted, built, and tested (make all) — Go side: golangci-lint 2.13 clean over the whole module, go test -race, go vet and gofmt clean on ./internal/outpost/ldap/..., and the outpost image builds with the release Dockerfile. The web and docs halves of make all are untouched by this change and were not run
  • The documentation has been updated and formatted (make docs) — no docs change
  • I have read the AI usage policy.

AI usage disclosure: as stated at the top, the investigation, the change and the test were worked with Claude (Anthropic); the root-cause analysis was verified by hand against the source and reproduced on a lab outpost before any code was written.

…lice

The memory searcher stored `&ms.users[i]` on a non-searching bind DN's
flags the first time that user searched, and never cleared it. Every
refresh replaces `ms.users`, so each stored pointer kept an entire
superseded copy of the directory alive for the life of the process. On
a directory of ~6k users with ~70k memberships, each distinct password
login after a restart pinned ~100-160 MB until the outpost was killed
for memory. The same pointer also froze the user's own entry (memberOf)
at its first-search state.

Replace the two bare slices with an immutable snapshot (users, groups
and a pk index) behind an atomic pointer. fetch() builds a new snapshot
and swaps it; Search() loads the snapshot once per request, resolves
the bound user by pk against the current one and copies the value for
the duration of the request. Nothing is written to the per-DN flags.

This also removes the unsynchronised slice replacement during a refresh
and the per-request linear scan over all users.

The regression test drives the searcher against a fake core: a
non-searching user's self-read must reflect a group change after the
searcher is re-initialised the way Refresh() does, and the DN's flags
must not carry a user pointer afterwards. It fails on the previous
code on both counts.
@cheesegrits
cheesegrits requested a review from a team as a code owner September 10, 2026 17:40
@netlify

netlify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-storybook ready!

Name Link
🔨 Latest commit d2509ba
🔍 Latest deploy log https://app.netlify.com/projects/authentik-storybook/deploys/6aa3d719e2104d000893fb10
😎 Deploy Preview https://deploy-preview-26028--authentik-storybook.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-integrations ready!

Name Link
🔨 Latest commit d2509ba
🔍 Latest deploy log https://app.netlify.com/projects/authentik-integrations/deploys/6aa3d719ad808e000899df81
😎 Deploy Preview https://deploy-preview-26028--authentik-integrations.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit d2509ba
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6aa3d719433ac00008721802
😎 Deploy Preview https://deploy-preview-26028--authentik-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.84%. Comparing base (02cc2a6) to head (d2509ba).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #26028      +/-   ##
==========================================
- Coverage   91.87%   91.84%   -0.04%     
==========================================
  Files        1170     1170              
  Lines       75514    75514              
  Branches     4054     4054              
==========================================
- Hits        69381    69355      -26     
- Misses       6091     6117      +26     
  Partials       42       42              
Flag Coverage Δ
conformance 33.75% <ø> (ø)
e2e 38.43% <ø> (+<0.01%) ⬆️
integration 30.01% <ø> (-0.45%) ⬇️
rust 42.92% <ø> (ø)
unit 93.43% <ø> (+<0.01%) ⬆️
unit-migrate 93.45% <ø> (+<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.

@BeryJu BeryJu changed the title internal/outpost/ldap: fix serious memory leak in the cached searcher providers/ldap: fix memory leak in the cached searcher Sep 11, 2026
@BeryJu
BeryJu merged commit def9ac7 into goauthentik:main Sep 11, 2026
138 checks passed
@BeryJu BeryJu added the backport/version-2026.8 Add this label to PRs to backport changes to version-2026.8 label Sep 11, 2026
@authentik-cherry-pick

Copy link
Copy Markdown
Contributor

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

BeryJu added a commit that referenced this pull request Sep 11, 2026
…26028 to version-2026.8) (#26050)

* providers/ldap: fix memory leak in the cached searcher (#26028)

internal/outpost/ldap: stop retaining pointers into the cached user slice

The memory searcher stored `&ms.users[i]` on a non-searching bind DN's
flags the first time that user searched, and never cleared it. Every
refresh replaces `ms.users`, so each stored pointer kept an entire
superseded copy of the directory alive for the life of the process. On
a directory of ~6k users with ~70k memberships, each distinct password
login after a restart pinned ~100-160 MB until the outpost was killed
for memory. The same pointer also froze the user's own entry (memberOf)
at its first-search state.

Replace the two bare slices with an immutable snapshot (users, groups
and a pk index) behind an atomic pointer. fetch() builds a new snapshot
and swaps it; Search() loads the snapshot once per request, resolves
the bound user by pk against the current one and copies the value for
the duration of the request. Nothing is written to the per-DN flags.

This also removes the unsynchronised slice replacement during a refresh
and the per-request linear scan over all users.

The regression test drives the searcher against a fake core: a
non-searching user's self-read must reflect a group change after the
searcher is re-initialised the way Refresh() does, and the DN's flags
must not carry a user pointer afterwards. It fails on the previous
code on both counts.

Co-authored-by: Dewi Roberts <[email protected]>

* spellcheck

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

---------

Signed-off-by: Jens Langhammer <[email protected]>
Co-authored-by: Hugh Messenger <[email protected]>
Co-authored-by: Dewi Roberts <[email protected]>
Co-authored-by: Jens Langhammer <[email protected]>
@dewi-tik

Copy link
Copy Markdown
Contributor

Thank you for this. Great PR and write-up. We appreciate it!

@cheesegrits

Copy link
Copy Markdown
Contributor Author

@dewi-tik you are most welcome, thanks for getting it merged so quick. It's still rock solid in prod here, btw.

I just hope you read the bit about "I'm not a Go guy". :)

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

Labels

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.

3 participants