Skip to content

fix(certreloader): re-check reload condition under write lock - #1994

Merged
toddbaert merged 2 commits into
open-feature:mainfrom
anxkhn:fix/certreloader-double-checked-reload
Jul 23, 2026
Merged

toddbaert merged 2 commits into
open-feature:mainfrom
anxkhn:fix/certreloader-double-checked-reload

Conversation

@anxkhn

@anxkhn anxkhn commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

This PR

GetCertificate in core/pkg/certreloader/certreloader.go uses a
double-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:

r.mu.RLock()
shouldReload := r.ReloadInterval != 0 && r.nextReload.Before(now)
r.mu.RUnlock()
if shouldReload {
    r.mu.Lock()
    defer r.mu.Unlock()
    cert, err := r.loadCertificate() // always runs, even if another caller just reloaded
    ...
    r.cert = &cert
    r.nextReload = now.Add(r.ReloadInterval)
    return r.cert, nil
}

The function's own comment states the intended behavior:

If a reload is in progress this will block and we will skip reloading in the
current call once we can continue

but nothing skips: after blocking on r.mu.Lock(), every caller that passed the
read-lock check calls loadCertificate() again.

GetCertificate is wired as tls.Config.GetCertificate, which the standard
library invokes per handshake and can run in parallel. So once ReloadInterval
has 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 reload
boundary 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:

r.mu.Lock()
defer r.mu.Unlock()
if r.ReloadInterval != 0 && r.nextReload.Before(now) {
    cert, err := r.loadCertificate()
    ...
    r.cert = &cert
    r.nextReload = now.Add(r.ReloadInterval)
}
return r.cert, nil

The re-check reuses now captured at the top of the function. The first caller
sets nextReload = now.Add(ReloadInterval); any caller that was blocked on the
write lock observes a now no earlier than the first caller's, so for any real
interval 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.LoadX509KeyPair is called through a
package-level variable (var loadX509KeyPair = tls.LoadX509KeyPair) so a test
can 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 concurrent
GetCertificate calls past the interval and asserts the cert is reloaded from
disk 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.

cd core
go build ./...
go test -race -covermode=atomic -cover -short ./pkg/certreloader/...

All green under -race (stable over repeated runs). Package coverage for
core/pkg/certreloader is 92.6%. golangci-lint (repo-pinned v2.7.2) reports 0
issues 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.

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]>
@anxkhn
anxkhn requested review from a team as code owners July 10, 2026 19:40
@netlify

netlify Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for polite-licorice-3db33c ready!

Name Link
🔨 Latest commit ce11c9b
🔍 Latest deploy log https://app.netlify.com/projects/polite-licorice-3db33c/deploys/6a625be9e4bd100008a13681
😎 Deploy Preview https://deploy-preview-1994--polite-licorice-3db33c.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1c293442-acfc-4f51-81d0-73e0a79a58b4

📥 Commits

Reviewing files that changed from the base of the PR and between 944d74b and ce11c9b.

📒 Files selected for processing (2)
  • core/pkg/certreloader/certreloader.go
  • core/pkg/certreloader/certreloader_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • core/pkg/certreloader/certreloader.go
  • core/pkg/certreloader/certreloader_test.go

📝 Walkthrough

Walkthrough

CertReloader.GetCertificate now prevents redundant concurrent certificate reloads by re-checking reload eligibility under the write lock. Certificate loading is injectable for tests, and a concurrent test verifies exactly one reload occurs.

Changes

Certificate reload protection

Layer / File(s) Summary
Reload guard and concurrency validation
core/pkg/certreloader/certreloader.go, core/pkg/certreloader/certreloader_test.go
GetCertificate re-checks ReloadInterval and nextReload after lock acquisition, uses the injectable loadX509KeyPair loader, and tests that concurrent callers trigger exactly one reload.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: re-checking certificate reload state under the write lock.
Description check ✅ Passed The description is detailed and directly matches the implemented certreloader concurrency fix and test seam.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
core/pkg/certreloader/certreloader.go (1)

45-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between d99a3e3 and 944d74b.

📒 Files selected for processing (2)
  • core/pkg/certreloader/certreloader.go
  • core/pkg/certreloader/certreloader_test.go

Signed-off-by: Todd Baert <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@toddbaert toddbaert 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.

Thanks again @anxkhn .

@toddbaert
toddbaert merged commit 86489da into open-feature:main Jul 23, 2026
17 of 18 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 20, 2026
toddbaert pushed a commit that referenced this pull request Jul 27, 2026
🤖 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants