fix: fall back to last successful OIDC discovery when refetch fails #10020
<span aria-hidden="true">✅</span> Deploy Preview for cerulean-figolla-1f9435 ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 88e846fb5c996399a56c17bfc4925fe222aa49e2 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/cerulean-figolla-1f9435/deploys/6aeb08b8fa9df580771a3471 |
|<span aria-hidden="true">😎</span> Deploy Preview | https://deploy-preview-10020--cerulean-figolla-1f9435.netlify.app |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />!QR Code<br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- cerulean-figolla-1f9435 Preview -->
_To edit notification comments on pull requests, go to your Netlify project configuration._
@KR-Ravindra, can you submit this PR for review?
@sadovnikov rebased on current main in 5fdc4c6 and marked ready for review. (Experimented and verified with an AI agent.)
<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"88e846fb5c996399a56c17bfc4925fe222aa49e2","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->
Codex Review Summary
This comment shows the latest Codex review activity on this pull request.
| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-04T10:33:30.736443Z">2026-11-04T10:33:30.736443Z</relative-time> | 88e846f | New commits |
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.
</details>
<sub><sub>!P2 Badge</sub></sub> Do not mask local TLS configuration errors
When an issuer was discovered successfully before and its Backend/EnvoyProxy client-certificate configuration is later changed to an invalid PEM/key pair, discoverEndpointsFromIssuer returns the local providerTLS.ToTLSConfig() error before sending any request. This branch nevertheless returns the issuer-only fallback as a success, so the SecurityPolicy continues translating with unusable TLS settings instead of surfacing the configuration error; restrict fallback to remote fetch/response failures or otherwise distinguish HTTP-client construction errors.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5fdc4c6c8f
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
Addressed the finding in 8a5ecb0: issuer-URL and TLS client construction errors are now typed as local configuration errors and never fall back to the retained discovery result, with a test for the invalid client-certificate case. @codex review (Experimented and verified with an AI agent.)
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8a5ecb0856
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
<sub><sub>!P2 Badge</sub></sub> Bind fallback entries to the TLS settings used
When an existing policy's Backend/EnvoyProxy TLS settings change to a valid-but-nontrusting CA or SNI, HTTP client construction succeeds and the resulting TLS handshake error is returned from client.Get as an ordinary transport error, so this condition still selects the old discovery document. The new invalid-key-pair test only exercises constructor failure; malformed CA PEM is also silently accepted because TLSUpstreamConfig.ToTLSConfig ignores AppendCertsFromPEM's result at internal/ir/xds.go:4160. The SecurityPolicy therefore remains translated even though its current token-endpoint TLS configuration cannot connect; retain a fingerprint of providerTLS with each cache entry and only fall back when it matches.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
Thank you, @KR-Ravindra 👍
@sadovnikov thanks. Codex raised one more point after that push, addressed in 0f3cbbc: each retained discovery result now carries a fingerprint of the TLS settings it was fetched with and is only reused while those match, with a test for the changed-settings case. @codex review (Experimented and verified with an AI agent.)
<!-- codex-review-receipt:v1 -->
Codex Review: Didn't find any major issues. :rocket:
Reviewed commit: 0f3cbbcf5d
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
Rebased on main and switched the two ptr.To calls in the test to new() for the forbidigo rule in 3b19a88. The coverage-test failure on the rerun was TestProvider/gateway_scheduled_status in internal/provider/kubernetes, which this PR does not touch, and osv-scan reports the same go-jose finding on main.
(Experimented and verified with an AI agent.)
<sub><sub>!P2 Badge</sub></sub> Include TLS settings in the per-translation cache key
When two SecurityPolicies in one translation share an issuer but use different TLS settings, the first fallback stored here is returned to the second by the issuer-only Get before tlsFingerprint is computed. During an issuer outage, TLS B can therefore reuse a document retained under TLS A even when B's CA or SNI cannot connect. Fresh evidence after the fingerprint fix is that the newly added fallback is inserted into the old issuer-only per-translation cache; key that cache by both issuer and fingerprint (or recheck the fingerprint on lookup).
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<sub><sub>!P2 Badge</sub></sub> Validate discovered endpoints before replacing the fallback
When a previously valid issuer next returns HTTP 200 metadata with a nonempty token URL that validateTokenEndpoint rejects (for example, an IP-literal URL), discoverEndpointsFromIssuer reports success because OpenIDConfig.validate only checks for empty fields, so this call replaces the usable fallback before buildOIDCProvider rejects the endpoint. A subsequent 503 then retrieves the invalid entry and the protected routes continue returning 500 instead of falling back to the last usable configuration; validate the discovered endpoint before calling Set, or preserve the old entry when downstream validation fails.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b19a88fa2
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
Pushed 6c70f5a: a discovery result whose token endpoint fails validateTokenEndpoint is no longer stored as the fallback (second Codex thread), with a test. The first thread is about the per-translation cache being keyed by issuer only, which is main's existing behaviour and unchanged here; the TLS fingerprint guards the cross-translation fallback.
(Experimented and verified with an AI agent.)
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6c70f5a666
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
<sub><sub>!P2 Badge</sub></sub> Retain discoveries usable with explicit token endpoints
When a SecurityPolicy explicitly sets provider.tokenEndpoint but leaves authorizationEndpoint to discovery, buildOIDCProvider replaces the discovered token URL and validates only the explicit URL. If the discovery document has a nonempty token URL that this helper rejects (for example, an IP literal), the current translation succeeds using the explicit endpoint, but this gate does not retain the discovered authorization endpoint. A later issuer outage therefore has no fallback (or uses an older authorization endpoint) and returns the protected route to HTTP 500 even though the last resolved provider was usable; retention needs to account for the final selected endpoints or which fields the policy overrides.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
Codecov Report
:x: Patch coverage is
92.30769% with 3 lines in your changes missing coverage. Please review.:white_check_mark: Project coverage is 82.67%. Comparing base (
c267eaa) to head (88e846f).:warning: Report is 10 commits behind head on main.
| Files with missing lines | Patch % | Lines |
|---|---|---|
| internal/gatewayapi/securitypolicy.go | 92.30% | 3 Missing :warning: |
<details><summary>Additional details and impacted files</summary>
@@ Coverage Diff @@
## main #10020 +/- ##
==========================================
+ Coverage 82.53% 82.67% +0.13%
==========================================
Files 277 277
Lines 44270 44328 +58
==========================================
+ Hits 36540 36649 +109
+ Misses 7729 7678 -51
Partials 1 1
</details>
:umbrella: View full report in Codecov by Harness.
:loudspeaker: Have feedback on the report? Share it here.
<details><summary> :rocket: New features to boost your workflow: </summary>
</details>
Non-blocking, fine as a follow-up: the per-translation cache is still keyed by issuer only, so when two policies share an issuer, the second one gets the first one's fallback without its own TLS fingerprint check. Adding the fingerprint to that cache key would fix it.
Should we only check the discovered token endpoint when the policy doesn't set its own tokenEndpoint?
Fine as a follow-up since this is an edge case.
Non-blocking: Could we add a warning condition to make that visible? It's fine as a follow-up.
@zhaohuabing done in bc353f7: the per-translation cache is now keyed by issuer plus the TLS fingerprint, and the discovered token endpoint is only checked before retaining the result when the policy does not set its own tokenEndpoint (buildOIDCProvider passes the override through). Tests for both are included. Could you take another look?
(Experimented and verified with an AI agent.)
<sub><sub>!P2 Badge</sub></sub> Separate override-only discovery fallbacks
Fresh evidence after adding override-sensitive retention is that this branch still writes an override-only document into the issuer/TLS-wide fallback. If two policies share those settings, a previously valid fallback can be replaced when the issuer advertises an IP-literal token URL and the policy being translated supplies its own valid token endpoint; on the next issuer outage, a policy without an override receives that retained IP URL, fails validateTokenEndpoint in buildOIDCProvider, and returns its protected routes to 500. Keep override-only discoveries separate from fallback entries usable by non-overriding policies.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<sub><sub>!P2 Badge</sub></sub> Apply override retention on translation-cache hits
Fresh evidence after making retention depend on tokenEndpointOverridden is that a per-translation hit returns before that decision. If a non-overriding policy first fetches a document with an IP-literal token URL, it caches the document here but correctly does not retain it globally; a later policy sharing issuer/TLS but supplying a valid token override succeeds from this cache hit without retaining the discovered authorization endpoint, so its next reconciliation during an issuer outage has no fallback and its protected routes return 500. Reapply retention on cached successes or include override mode in this cache key.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc353f7012
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
The fallback cache is keyed by issuer only, so with the per-translation cache now split by TLS settings, policies that share an issuer overwrite each other's fallback and only the last one is covered during an outage. Keying the fallback by issuer plus fingerprint as well would fix it.
@zhaohuabing done in f81e6ca: the fallback cache is now keyed by issuer plus the TLS fingerprint as well, so policies sharing an issuer each keep their own entry (the TLS-change test now checks both are retained), and the unparam lint failure is fixed. I've left the warning condition for a follow-up as you suggested. Could you take another look?
(Experimented and verified with an AI agent.)
<sub><sub>!P2 Badge</sub></sub> Reject token ports that downstream translation cannot encode
Fresh evidence after adding this validation gate is that, on 64-bit builds and for a policy with neither a token override nor provider BackendRefs, a discovered URL such as https://idp.example.com:4294967296/token passes validateTokenEndpoint because strconv.Atoi accepts the port, so this branch replaces the last usable fallback. url2Cluster then rejects that same port via ParseUint(..., 32) (internal/xds/translator/utils.go:60-63), and a later discovery outage reuses the invalid entry instead of restoring the working document; validate against the downstream port range before Set.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<sub><sub>!P2 Badge</sub></sub> Bound the fallback cache by retained byte size
When an issuer returns very large strings in the decoded token, authorization, or end-session fields, this line retains those bytes process-wide, while the 128-entry limit bounds only count and the decoder at securitypolicy.go:2934 has no body-size limit. Cycling through 128 such issuers can therefore retain gigabytes even after their policies are removed, whereas the prior translation cache was collectible after each run; reject oversized discovery responses or make eviction account for retained bytes.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc657cfde3
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
LGTM thanks!
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ebd886202
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
<sub><sub>!P2 Badge</sub></sub> Memoize TLS fingerprints across route targets
When an OIDC SecurityPolicy with an inline CA or client certificate is applied through a selector to many routes, buildOIDCProvider invokes this path for every target; although all but the first lookup are served from oidcDiscoveryCache, this line first JSON-marshals and SHA-256-hashes the entire TLS config on every call. A 1 MiB bundle and 1,000 matched routes therefore add roughly a gigabyte of serialization and allocation to each reconciliation, so cache the fingerprint per translated TLS source/config rather than recomputing it before every per-route cache lookup.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
Thinking about this more, I'd drop the TLS fingerprint from both caches. The discovery document depends only on the issuer, not on the TLS settings used to fetch it, so one entry per issuer is enough. cc @KR-Ravindra
@zhaohuabing done in 88e846f: dropped the TLS fingerprint from both caches, so they are keyed by issuer only again, and removed the two tests that covered the per-TLS entries. Could you take another look?
(Experimented and verified with an AI agent.)
Approved these changes.
Approved these changes.
Thank you, @KR-Ravindra and @zhaohuabing
zirain
KR-Ravindra
What this PR does / why we need it:
OIDC discovery runs on every translation with a cache that is re-created each time. If
/.well-known/openid-configurationis unreachable or non-2xx during a reconciliation, the SecurityPolicy fails and every route it protects answers 500 until a later reconciliation succeeds.This keeps the last successfully discovered
OpenIDConfigper issuer in a process-wide, mutex-guarded LRU cache (128 entries) and falls back to it, logging the error, when discovery fails. Discovery is still retried every translation; an issuer that never succeeded still fails, and local issuer/TLS configuration errors are never masked. Follows the guidance on #9239 (size cap + LRU, no TTL).Tests: fallback, none without prior success or on a local TLS config error, LRU eviction, concurrency under
-race.Which issue(s) this PR fixes:
Fixes #9235
---
PR Checklist
gofmt,go vetandgo test -race ./internal/gatewayapi/pass locallyrelease-notes/current/bug_fixes/9235-oidc-discovery-fallback.mdExperimented and verified with an AI agent.