Repository navigation
fix(certreloader): re-check reload condition under write lock - #1994
Conversation
GetCertificate read the reload condition under a read lock, released it, then took the write lock and reloaded unconditionally. The function's own comment promises callers will "skip reloading in the current call once we can continue", but the second check of the double-checked locking pattern was missing, so every caller that passed the read-lock check reloaded. GetCertificate is wired as tls.Config.GetCertificate and runs in parallel per handshake, so once ReloadInterval elapsed a burst of concurrent handshakes each grabbed the write lock in turn and re-read/parsed the key pair from disk, even though the first reload had already advanced nextReload. Re-check ReloadInterval/nextReload under the write lock so only the first caller reloads and the rest return the already-loaded certificate. Adds a regression test that fires many concurrent GetCertificate calls past the interval and asserts exactly one reload. Signed-off-by: Anas Khan <[email protected]>
✅ Deploy Preview for polite-licorice-3db33c ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthrough
ChangesCertificate reload protection
Estimated code review effort: 2 (Simple) | ~15 minutes Sequence Diagram(s)sequenceDiagram
participant Callers
participant GetCertificate
participant loadX509KeyPair
Callers->>GetCertificate: concurrent certificate requests
GetCertificate->>GetCertificate: acquire write lock and re-check reload eligibility
GetCertificate->>loadX509KeyPair: load certificate once when eligible
loadX509KeyPair-->>GetCertificate: certificate and key pair
GetCertificate-->>Callers: shared certificate
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies" Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
core/pkg/certreloader/certreloader.go (1)
45-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the duplicated reload predicate.
The reload condition
r.ReloadInterval != 0 && r.nextReload.Before(now)now appears at both the initial read-lock check (Line 45) and the write-lock re-check (Line 54). Extracting it into a single helper keeps the two halves of the double-checked lock in sync and avoids a subtle divergence if the predicate is ever changed in only one place.♻️ Proposed helper
// caller must hold r.mu (read or write). func (r *CertReloader) reloadDue(now time.Time) bool { return r.ReloadInterval != 0 && r.nextReload.Before(now) }- shouldReload := r.ReloadInterval != 0 && r.nextReload.Before(now) + shouldReload := r.reloadDue(now)- if r.ReloadInterval != 0 && r.nextReload.Before(now) { + if r.reloadDue(now) {Also applies to: 54-54
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@core/pkg/certreloader/certreloader.go` at line 45, Extract the duplicated reload predicate into a CertReloader method named reloadDue(now time.Time), documenting that callers must hold r.mu, and return the existing ReloadInterval/nextReload condition from it. Replace the predicate at both the initial read-lock check and write-lock re-check with this helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@core/pkg/certreloader/certreloader.go`:
- Line 45: Extract the duplicated reload predicate into a CertReloader method
named reloadDue(now time.Time), documenting that callers must hold r.mu, and
return the existing ReloadInterval/nextReload condition from it. Replace the
predicate at both the initial read-lock check and write-lock re-check with this
helper.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c24433d0-12a2-4ee9-ae82-41335195bca8
📒 Files selected for processing (2)
core/pkg/certreloader/certreloader.gocore/pkg/certreloader/certreloader_test.go
Signed-off-by: Todd Baert <[email protected]>
|
🤖 I have created a release *beep* *boop* --- <details><summary>flagd: 0.16.1</summary> ## [0.16.1](flagd/v0.16.0...flagd/v0.16.1) (2026-07-27) ### 🐛 Bug Fixes * add server ReadTimeouts, update security deps ([#1980](#1980)) ([0e1e8b3](0e1e8b3)) * handle invalid selector errors ([#1976](#1976)) ([409a62e](409a62e)) * **security:** update module google.golang.org/grpc to v1.82.1 [security] ([#2005](#2005)) ([4281adf](4281adf)) * **security:** update vulnerability-updates [security] ([#1984](#1984)) ([2a5a6b6](2a5a6b6)) ### ✨ New Features * **sync:** configurable gRPC keepalive enforcement on sync server ([#1999](#1999)) ([19e57b9](19e57b9)) </details> <details><summary>flagd-proxy: 0.9.7</summary> ## [0.9.7](flagd-proxy/v0.9.6...flagd-proxy/v0.9.7) (2026-07-27) ### 🐛 Bug Fixes * add server ReadTimeouts, update security deps ([#1980](#1980)) ([0e1e8b3](0e1e8b3)) * **security:** update module google.golang.org/grpc to v1.82.1 [security] ([#2005](#2005)) ([4281adf](4281adf)) * **security:** update vulnerability-updates [security] ([#1984](#1984)) ([2a5a6b6](2a5a6b6)) </details> <details><summary>core: 0.16.1</summary> ## [0.16.1](core/v0.16.0...core/v0.16.1) (2026-07-27) ### 🐛 Bug Fixes * **certreloader:** re-check reload condition under write lock ([#1994](#1994)) ([86489da](86489da)) * handle invalid selector errors ([#1976](#1976)) ([409a62e](409a62e)) * readyz never true of multiple gRPC syncs are used ([#1985](#1985)) ([29833e8](29833e8)) * **security:** update module google.golang.org/grpc to v1.82.1 [security] ([#2005](#2005)) ([4281adf](4281adf)) * **security:** update vulnerability-updates [security] ([#1984](#1984)) ([2a5a6b6](2a5a6b6)) * **sync:** avoid send on closed channel in fileinfo watcher Close ([#1992](#1992)) ([a7339ea](a7339ea)) * **sync:** handle non-string YAML map keys in config parsing ([#1990](#1990)) ([3c72e6f](3c72e6f)) * **sync:** re-establish file watch after delete and restore ([#2001](#2001)) ([d434adf](d434adf)) * **sync:** synchronize readiness state ([#2006](#2006)) ([317a7e0](317a7e0)) ### ✨ New Features * improve ETag and body hash support to blob/http sync ([#1991](#1991)) ([1e210d4](1e210d4)) ### 🧹 Chore * fix flaky test ([7ff137d](7ff137d)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). Signed-off-by: OpenFeature Bot <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>



This PR
GetCertificateincore/pkg/certreloader/certreloader.gouses adouble-checked-locking pattern, but the second check is missing. It reads the
reload condition under the read lock, releases it, takes the write lock, and then
reloads the key pair from disk unconditionally:
The function's own comment states the intended behavior:
but nothing skips: after blocking on
r.mu.Lock(), every caller that passed theread-lock check calls
loadCertificate()again.GetCertificateis wired astls.Config.GetCertificate, which the standardlibrary invokes per handshake and can run in parallel. So once
ReloadIntervalhas elapsed, a burst of concurrent handshakes all pass the read-lock check, then
each grabs the write lock in turn and re-reads and re-parses the cert/key pair
from disk, even though the first caller already reloaded and advanced
nextReload. That is a thundering herd of redundant disk reads at every reloadboundary on a busy TLS listener.
This is not a correctness/crash bug: access is serialized by the lock and the
served certificate is always valid. It defeats the single-reload optimization the
code is clearly trying to implement.
The fix
Add the missing second check inside the write-locked critical section, so only
the first caller past the interval reloads and the rest return the
already-loaded certificate:
The re-check reuses
nowcaptured at the top of the function. The first callersets
nextReload = now.Add(ReloadInterval); any caller that was blocked on thewrite lock observes a
nowno earlier than the first caller's, so for any realinterval its re-check is false and it correctly skips. Production behavior is
otherwise unchanged: a single caller past the interval still reloads exactly as
before.
To make the behavior testable,
tls.LoadX509KeyPairis called through apackage-level variable (
var loadX509KeyPair = tls.LoadX509KeyPair) so a testcan count reloads. Production always uses the stdlib function; this is a one-line
seam plus one changed call site, and the runtime path is byte-identical.
Testing
Adds
TestConcurrentCertificateReload, which fires 50 concurrentGetCertificatecalls past the interval and asserts the cert is reloaded fromdisk exactly once. It parks all callers on the read lock, releases them together
so they evaluate the reload condition concurrently, and counts reloads via the
seam.
All green under
-race(stable over repeated runs). Package coverage forcore/pkg/certreloaderis 92.6%.golangci-lint(repo-pinned v2.7.2) reports 0issues on the package.
Red/green: with only the new write-lock re-check reverted, the test reports 50
reloads for 50 concurrent callers and fails; with the fix it reports exactly 1.