Skip to content

connect: serve Connect leaf certificates over SDS so rotation is hitless (sidecars + terminating gateways) - #23938

Merged
bharath-k1999 merged 10 commits into
mainfrom
bharath/support-sds-for-connect-proxy-leaf-certs
Sep 28, 2026
Merged

bharath-k1999 merged 10 commits into
mainfrom
bharath/support-sds-for-connect-proxy-leaf-certs

Conversation

@bharath-k1999

@bharath-k1999 bharath-k1999 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

connect: serve Connect leaf certificates over SDS so rotation is hitless

Covers sidecar proxies and terminating gateways.

Problem

Every Connect leaf-certificate rotation terminates all established connections on the affected proxy.

makeCommonTLSContext() embedded the leaf cert, private key and CA roots directly into the DownstreamTlsContext as DataSource_InlineString — on the sidecar's public listener, and on every per-service filter chain of a terminating gateway:

"transport_socket": {
  "typed_config": {
    "@type": ".../DownstreamTlsContext",
    "common_tls_context": {
      "tls_certificates": [{
        "certificate_chain": { "inline_string": "-----BEGIN CERTIFICATE-----\n..." },
        "private_key":      { "inline_string": "[redacted]" }
      }],
      "validation_context": {
        "trusted_ca": { "inline_string": "-----BEGIN CERTIFICATE-----\n..." }
      }
    }
  }
}

Because the certificate bytes are part of the listener proto, every rotation produces a different listener, which changes Envoy's filter-chain hash. Envoy then drains the old filter chain, and every established connection is closed with a clean FIN once the drain elapses:

use in place update filter chain update path ... hash=3583037857224565708
draining 1 filter chains in listener public_listener:192.168.242.242:20000
lds: add/update listener 'public_listener:192.168.242.242:20000'
draining filter chains ... complete

This is invisible to short-lived HTTP requests, but fatal to long-lived TCP workloads. It was reported against an AMQP/RabbitMQ deployment carrying 250–500 concurrent long-lived connections, which saw a full disconnect wave once per LeafCertTTL (once per day in production). The disconnect interval scaled linearly with LeafCertTTL, confirming cert rotation rather than a network event.

SecretsConfigDump was empty on affected proxies, confirming SDS was not in use anywhere on this path.

A terminating gateway holds one leaf per linked service, and each linked service gets its own filter chain on the shared :8443 listener, so the same defect drains every connection transiting the gateway for that service.

Solution

Deliver the leaf certificate and CA roots as ADS-backed SDS secrets instead of inlining them, the same way we already do for the API gateway's own certificates.

The listener now references the material by name and is byte-identical across rotations, so only the Secret resources change. Envoy hot-swaps the certificate in place — no listener rebuild, no filter-chain hash change, no drain.

"common_tls_context": {
  "tls_certificate_sds_secret_configs": [
    { "name": "connect-leaf", "sds_config": { "ads": {}, "resource_api_version": "V3" } }
  ],
  "validation_context_sds_secret_config":
    { "name": "connect-root", "sds_config": { "ads": {}, "resource_api_version": "V3" } }
}

Secret naming:

Proxy kind Leaf secret Roots secret
Sidecar / mesh gateway connect-leaf connect-root
Terminating gateway <service>-connect-leaf (one per linked service) connect-root (shared)

The terminating gateway needs per-service names because it holds a distinct leaf for every linked service. ServiceName.String() is used, so the name carries partition/namespace under Enterprise and cannot collide across them. Subset chains for the same service share a single leaf secret.

Changes

File Change
agent/xds/secrets.go New secretsFromSnapshotConnectProxy() emitting connect-leaf (TlsCertificate) and connect-root (ValidationContext). ServiceKindConnectProxy and ServiceKindMeshGateway route to it; ServiceKindIngressGateway still returns nil.
agent/xds/secrets.go secretsFromSnapshotTerminatingGateway() additionally emits one <service>-connect-leaf per linked service (iterating ValidServices() + ValidDestinations(), deduped) plus the shared connect-root.
agent/xds/listeners.go createDownstreamTransportSocketForConnectTLS() and makeFilterChainTerminatingGateway() both build their context via makeCommonConnectTLSContext() / makeADSSecretConfig() instead of makeCommonTLSContext().
agent/xds/listeners.go injectSpiffeValidatorConfigForPeers() converts the SDS validation context back to an inline one before running the existing SPIFFE-validator logic.
agent/xds/config/config.go Doc comment for XDSFetchTimeoutMs updated to record that it now also applies to SDS.

No xDS plumbing changes were needed — SecretType was already registered in delta.go, already included in AllResourcesFromSnapshot, and xDSUpdateOrder already pushes secret upserts before listeners and removals last.

initial_fetch_timeout on SDS configs

Per review feedback, the new SDS ConfigSources set InitialFetchTimeout from xds_fetch_timeout_ms, matching what EDS and RDS already do. fetchTimeout is threaded through makeADSSecretConfig → makeCommonConnectTLSContext → the two call sites, which read cfgSnap.GetXDSCommonConfig(s.Logger).GetXDSFetchTimeout().

Behaviour is unchanged unless the operator opts in: the field is a *int, so unset omits it entirely and Envoy's built-in 15s default applies; 0 means wait indefinitely. Only the 4 xds-fetch-timeout-ms-* goldens changed as a result, confirming the narrow blast radius.

I verified end-to-end against a live agent + Envoy 1.38 that xds_fetch_timeout_ms set via proxy-defaults reaches Envoy as initial_fetch_timeout: "30s" on both connect-leaf and connect-root, and that removing the entry drops the field. Note this option is currently undocumented on the website (it only appears in CHANGELOG.md from GH-19871); a docs ticket is being filed separately.

Notes on scope and design

Peered chains keep an inline validation context. injectSpiffeValidatorConfigForPeers hard-asserts *CommonTlsContext_ValidationContext, and the SPIFFE validator has to carry the per-trust-domain roots itself. Without the conversion the assertion fails, finalizePublicListenerFromConfig propagates the error, and the listener is dropped entirely for any exported/peered proxy. For these chains the leaf still uses SDS, which is what makes rotation hitless — roots rotate far less often than leaves.

Upstream/outbound cluster TLS is deliberately unchanged. clusters.go still uses inline makeCommonTLSContext, so leaf rotation continues to churn CDS. This is intentional: I verified during E2E that the client sidecar's outbound cluster is modified on rotation (cluster_manager.cluster_modified: 2) yet the long-lived session survives. Only the listener drain closes connections, so the downstream-only change is sufficient to fix the reported issue.

This is distinct from #23288. That change put the gateway → external service leg (CDS, makeUpstreamTLSContext, operator-supplied cert files) on SDS. This change is the downstream client → gateway leg (LDS, the auto-rotating Connect leaf). Before this PR the terminating gateway clusters golden had 3 sdsConfig / 0 private keys while its listeners golden had 0 sdsConfig / 8 private keys.

Secrets are only sent if referenced. Secret emission and listener generation are intentionally guarded independently — for example a mesh gateway with no exported services cancels its leaf watch and has Leaf == nil while still holding valid CA roots, so it emits roots only. xDSDeltaType.subscribed() (delta.go:1011) filters every resource against Envoy's subscription at send time, so an unreferenced secret never reaches the wire and there is no NACK or churn risk.

Listener generation is deliberately not gated on certificate material. The listener carries only secret names; gating it would rewrite the listener proto on root-watch transitions, changing the hash and draining connections — precisely the bug this PR removes. This also converts a pre-existing fail-open into fail-closed: the old inline path returned a nil transport socket when roots were empty, yielding a plaintext public listener with no mTLS, and panicked outright on a nil leaf.

Testing

Unit tests

  • TestSecretsFromSnapshot_ConnectProxyReturnsLeafAndRootSecrets — asserts the two secrets and their PEM contents.
  • TestSecretsFromSnapshot_ConnectProxyEmitsEachSecretIndependently — a nil leaf still emits the root, absent roots still emit the leaf, neither emits nothing, and a nil leaf does not panic.
  • TestCreateDownstreamTransportSocketForConnectTLS_UsesSDSSecrets — the transport socket carries SDS references (over ADS, V3) and no inline cert or validation context.
  • TestCreateDownstreamTransportSocketForConnectTLS_StableWhileMaterialMissing — the transport socket is byte-identical with and without material present, making the no-drain property a test invariant so the gating cannot be silently reintroduced.
  • TestSecretsFromSnapshotTerminatingGateway_EmitsDownstreamConnectSecrets — walks the generated listeners and asserts every SDS name referenced by a filter chain is backed by an emitted secret.
  • TestSecretsFromSnapshot_NonTerminatingGatewayKindsReturnNil — retargeted to ServiceKindIngressGateway, since connect-proxy now returns secrets.

Golden files

Connect proxy: 259 goldens regenerated, with an exactly symmetric and purely mechanical diff:

Removed Added
115 × inline tlsCertificates 115 × tlsCertificateSdsSecretConfigs
104 × inline validationContext / trustedCa 104 × validationContextSdsSecretConfig

Terminating gateway: a further 38 goldens (18 listeners, 18 secrets, 2 builtin_extension). Across all 20 terminating-gateway listener goldens there are now 0 inline private keys, and the only 3 remaining BEGIN CERTIFICATE occurrences are all in terminating-gateway-with-peer-trust-bundle, i.e. the SPIFFE validator case described above.

Regenerating is idempotent — a second -update run produces no further changes.

Integration tests

Two tests, one per proxy kind, sharing helpers in the new test/integration/consul-container/libs/certs package:

  • TestConnectProxyLeafCertRotationIsHitless (test/basic/)
  • TestTerminatingGatewayLeafCertRotationIsHitless (test/gateways/)

Each asserts the listener references the leaf and roots by SDS name and carries no inline material, then opens a single long-lived TCP connection through the mesh, forces a CA root rotation, waits for Envoy to serve a new leaf serial, and keeps reusing that same connection afterwards. Each also asserts Envoy never drained a filter chain.

Details worth noting:

  • The probe deliberately does not use http.Client — its connection pooling would silently redial and mask the very drain the test is looking for.
  • Both proxies are started with --drain-time-s 5. Without this a regression keeps the connection alive past the end of the test and looks like a pass; I hit exactly that trap during manual E2E against stock Envoy's 600s default.
  • GatewayConfig gains an optional CustomContainerConfig hook, since gateways previously had no way to customise their container.
  • The gateway test compares the lds: add/update listener count before and after the rotation rather than requiring exactly 1. A gateway listener can legitimately be programmed more than once while config entries settle, so the regression being guarded is "rotation added an update", not an absolute count.
  • Rotation is forced by toggling the CA's PrivateKeyType/PrivateKeyBits. Lowering LeafCertTTL does not re-issue already-issued leaves, and the minimum LeafCertTTL is 1h, so waiting for a natural rotation is not viable in a test.

Local testing steps

1. Unit tests and goldens

go test ./agent/xds/ -run 'TestCreateDownstreamTransportSocketForConnectTLS|TestSecretsFromSnapshot' -v
go test ./agent/xds/...

# Confirm the goldens are in sync: this must produce NO new changes
go test ./agent/xds/ -run 'TestAllResourcesFromSnapshot|TestEnvoyExtenderWithSnapshot' -update
git status --porcelain agent/xds/testdata/ | wc -l    # unchanged from before the run

Confirm no downstream listener retains inline certificate material:

cd agent/xds/testdata/listeners

# terminating gateways: no inline private keys anywhere
grep -c privateKey terminating-gateway*.golden | grep -v ':0'
# expected: no output

# the only inline certs left are the peered SPIFFE validator case
grep -c 'BEGIN CERTIFICATE' terminating-gateway*.golden | grep -v ':0'
# expected: terminating-gateway-with-peer-trust-bundle.latest.golden:3

2. Integration tests

Build the images the container suite expects (ENVOY_VERSION must be listed in envoyextensions/xdscommon/ENVOY_VERSIONS):

make dev-docker

DOCKER_BUILDKIT=0 docker build -t consul-envoy:target-version \
  --build-arg CONSUL_IMAGE=hashicorp/consul:local \
  --build-arg ENVOY_VERSION=1.38.2 \
  -f ./test/integration/consul-container/assets/Dockerfile-consul-envoy \
  ./test/integration/consul-container/assets

Run both tests:

cd test/integration/consul-container
go test -count=1 ./test/basic/    -run TestConnectProxyLeafCertRotationIsHitless       -v -timeout 20m
go test -count=1 ./test/gateways/ -run TestTerminatingGatewayLeafCertRotationIsHitless -v -timeout 20m

Expected:

--- PASS: TestConnectProxyLeafCertRotationIsHitless (41.46s)
    --- PASS: .../public_listener_uses_SDS_instead_of_inline_certificates (0.01s)
    --- PASS: .../leaf_rotation_does_not_drain_established_connections (28.14s)

3. Confirming the tests actually catch the bug

To prove the assertions are not vacuous, point the same test at a pre-fix build:

git worktree add /tmp/consul-baseline HEAD~1
(cd /tmp/consul-baseline && make dev-docker && docker tag consul:local consul:baseline)

docker tag consul:baseline hashicorp/consul:local
DOCKER_BUILDKIT=0 docker build -t consul-envoy:target-version \
  --build-arg CONSUL_IMAGE=hashicorp/consul:local \
  --build-arg ENVOY_VERSION=1.38.2 \
  -f ./test/integration/consul-container/assets/Dockerfile-consul-envoy \
  ./test/integration/consul-container/assets

cd test/integration/consul-container
go test -count=1 ./test/basic/ -run TestConnectProxyLeafCertRotationIsHitless -v -timeout 20m

git worktree remove /tmp/consul-baseline --force

Both sub-tests fail, with the expected messages:

--- FAIL: .../public_listener_uses_SDS_instead_of_inline_certificates
    the public listener does not reference the leaf certificate over SDS

--- FAIL: .../leaf_rotation_does_not_drain_established_connections
    long-lived connection was terminated by the leaf certificate rotation (exchange 5)
    read on long-lived connection failed: unexpected EOF

4. Manual verification against a live proxy

# Listener must reference the secrets by name and contain no inline certs.
# Note config_dump uses snake_case, unlike the camelCase goldens.
curl -s localhost:19000/config_dump | grep -c inline_string
curl -s localhost:19000/config_dump | grep -o 'connect-leaf\|connect-root' | sort | uniq -c

# SecretsConfigDump must be populated (it was empty before this change)
curl -s localhost:19000/config_dump | python3 -c "
import json, sys
for c in json.load(sys.stdin)['configs']:
    if 'Secrets' in c['@type']:
        for k in ('dynamic_active_secrets', 'static_secrets'):
            for s in c.get(k, []):
                print(s['name'], s.get('version_info'))
"

# Force a rotation. Lowering LeafCertTTL alone does NOT re-issue existing
# leaves, and the minimum LeafCertTTL is 1h, so toggle the CA key params.
curl -s -X PUT http://127.0.0.1:8500/v1/connect/ca/configuration -d '{
  "Provider":"consul",
  "Config":{"LeafCertTTL":"72h","PrivateKeyType":"rsa","PrivateKeyBits":2048,
            "RotationPeriod":"2160h","IntermediateCertTTL":"8760h"}
}'

# The secret version changes, but no filter chain is ever drained.
docker logs <proxy> 2>&1 | grep -c 'filter chains in listener'   # 0

Results

Sidecar proxy

A/B run on identical stacks (Consul dev agent, Envoy 1.38.2 sidecars, --drain-time-s 10, forced CA root rotation), with a long-lived TCP probe held open across the rotation:

Before After
Leaf rotated 0b → 11 0a → 10
Inline certs in listener yes no
SecretsConfigDump empty populated (connect-leaf, connect-root)
lds: add/update listener 3 (startup + 2 rotations) 1 (startup only)
draining ... filter chains yes 0
Long-lived TCP probe DISCONNECTED after 22.0s: clean EOF (FIN) STILL CONNECTED after 120.0s (60 exchanges)

Terminating gateway

Same harness, same Envoy flags (--drain-time-s 10), same forced CA rotation — only the Consul binary differs (HEAD vs HEAD~1):

Before After
Listener SDS refs 0 2
Inline cert / private key in listener yes 0 / 0
dynamic_active_secrets empty external-echo-connect-leaf, connect-root
Listener proto across rotation cert bytes changed byte-identical (1924 → 1924 bytes)
listener_modified 2 0
lds.update_success 7 1 (startup only)
Long-lived TCP probe DISCONNECTED after 25.0s: clean EOF (FIN) STILL CONNECTED after 75.1s (15 keepalives on the SAME socket)

The secrets genuinely rotated in the "after" run (33221e83… → fe7395e2… for the leaf, adf35f53… → 3adc13c8… for the roots) while the listener stayed byte-identical — which is precisely the mechanism. A longer run with 3 back-to-back rotations held the same socket for 110s.

The "before" column reproduces the reported symptom exactly, including the clean FIN rather than an RST, and the empty SecretsConfigDump.

Out of scope

Ingress gateways (listeners_ingress.go) and API gateways (listeners_apigateway.go) still inline the Connect leaf into their listeners and carry the same defect — 13 and 6 goldens respectively. Those are left for a follow-up so this change stays reviewable.

@bharath-k1999 bharath-k1999 added the backport/ent/1.21 changes are backported to 1.21 ent label Sep 24, 2026
@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Go Test Coverage: 70.4%

See the workflow run for the full per-package breakdown and downloadable HTML report.

@codecov-commenter

codecov-commenter commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.54545% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.87%. Comparing base (668c758) to head (21d73b1).

Files with missing lines Patch % Lines
agent/xds/secrets.go 94.80% 2 Missing and 2 partials ⚠️
agent/xds/listeners.go 93.93% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #23938      +/-   ##
==========================================
+ Coverage   64.83%   64.87%   +0.04%     
==========================================
  Files         977      977              
  Lines      121817   121917     +100     
==========================================
+ Hits        78974    79089     +115     
+ Misses      35464    35442      -22     
- Partials     7379     7386       +7     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bharath-k1999
bharath-k1999 marked this pull request as ready for review September 24, 2026 09:48
@bharath-k1999
bharath-k1999 requested review from a team as code owners September 24, 2026 09:48
@rashmirathi-2
rashmirathi-2 requested a lite review from Copilot September 24, 2026 16:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Align listener generation with SDS secret emission when root material is unavailable.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity

Open (1)
What changed in this PR

This PR moves Connect proxy and mesh gateway downstream TLS certificates and roots from inline listener data to ADS-backed SDS, enabling hitless certificate rotation.

Changes:

  • Adds connect-leaf and connect-root SDS resources.
  • Updates downstream TLS contexts to use stable SDS references.
  • Adds tests and regenerates listener and secret fixtures.
  • A critical issue remains: listeners may reference SDS secrets that are not emitted when root material is temporarily unavailable.
File Summary
agent/​xds/​xds_protocol_helpers_test.go Updates protocol test fixtures for SDS.
agent/​xds/​testdata/​secrets/​transparent-proxy.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​transparent-proxy-destination.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​telemetry-collector.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​listener-bind-port.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​listener-bind-address.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​listener-bind-address-port.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​http2-public-listener.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​http-upstream.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​http-public-listener.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​http-listener-with-timeouts.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​grpc-public-listener.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​expose-checks.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​expose-checks-http.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​expose-checks-grpc.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​defaults.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-upstream.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-upstream-default-chain.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-trace-listener.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-timeouts.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-public-listener.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-public-listener-http.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-passive-healthcheck.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-max-inbound-connections.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-local-app.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-limits.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​custom-limits-set-to-zero.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​connect-proxy-with-http-chain.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​connect-proxy-with-chain.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​access-logs-json-file.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​secrets/​access-logs-defaults.latest.golden Updates secret golden for SDS output.
agent/​xds/​testdata/​listeners/​transparent-proxy.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​telemetry-collector.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​mesh-gateway-with-exported-peered-services-http-with-router.latest.golden Updates listener golden while preserving peer validation.
agent/​xds/​testdata/​listeners/​http2-public-listener.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​http-upstream.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​http-public-listener.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​http-public-listener-no-xfcc.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​http-listener-with-timeouts.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​grpc-public-listener.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​expose-checks.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​expose-checks-http.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​defaults.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-upstream.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-trace-listener.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-timeouts.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-public-listener.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-public-listener-http.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-public-listener-http-missing.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-public-listener-http-2.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-local-app.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​custom-limits.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​connect-proxy-exported-to-peers.latest.golden Updates listener golden while preserving peer validation.
agent/​xds/​testdata/​listeners/​access-logs-json-file.latest.golden Updates listener golden for SDS references.
agent/​xds/​testdata/​listeners/​access-logs-defaults.latest.golden Updates listener golden for SDS references.
agent/​xds/​secrets.go Generates Connect SDS resources; emission must remain synchronized with listener readiness.
agent/​xds/​secrets_test.go Tests generated Connect SDS resources.
agent/​xds/​listeners.go Configures downstream TLS with SDS and preserves peer validation.
agent/​xds/​listeners_test.go Tests SDS-backed listener configuration.
.changelog/​23938.txt Documents the SDS improvement.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread agent/xds/secrets.go Resolved
@bharath-k1999
bharath-k1999 requested a lite review from Copilot September 28, 2026 05:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟢 Approval recommended

The only remaining finding is a minor test-description nit; no blocking issues remain.

Review effort: Lite
Findings: 1 Low severity

Open (1)
Resolved since last review (1)

Comment thread agent/xds/secrets_test.go Resolved
Clarified comments regarding secret emission behavior in tests.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Comment thread agent/xds/listeners.go
func makeADSSecretConfig(name string) *envoy_tls_v3.SdsSecretConfig {
return &envoy_tls_v3.SdsSecretConfig{
Name: name,
SdsConfig: &envoy_core_v3.ConfigSource{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@bharath-k1999 I think we should set the InitialFetchTimeout similar to EDS and RDS (XDSFetchTimeoutMs is defined in agent/xds/config/config.go) to ensure that there is sufficient timeout window ?

suggested code change, add input param fetchTimeout and pass that value from the callers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

added xds fetch timeouts as suggested

…ment

Thread the xds_fetch_timeout_ms value through to the connect-leaf and
connect-root SdsSecretConfigs so SDS honours the same operator-configured
initial fetch timeout as EDS and RDS. The value is derived from static proxy
config rather than cert material, so it stays stable across leaf rotations and
does not affect filter chain hashes.

Also update the doc comment on
TestSecretsFromSnapshot_ConnectProxyEmitsEachSecretIndependently, which still
described the earlier all-or-nothing gating instead of the independent
per-secret guards the test now asserts.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread agent/xds/listeners.go
},
ResourceApiVersion: envoy_core_v3.ApiVersion_V3,
ResourceApiVersion: envoy_core_v3.ApiVersion_V3,
InitialFetchTimeout: fetchTimeout,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for adding the InitialFetchTimeout. Few more comments.

  1. Should we validate the fetchTimeout before consuming it ?
  2. We should update the comments and documentation around XDSCommonConfig.XDSFetchTimeoutMs to reflect that this timeout is configurable one for SDS along with the existing EDS, RDS. Please create a doc jira follow-up ticket.
    cc @bharath-k1999

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we dont need an exclusive check for for fetch timeouts if we dont set them they will be omitted and fallback envoy defaults

i have tested it by adding the fetch timeouts via proxy-defaults
{
"Kind": "proxy-defaults",
"Name": "global",
"Config": { "xds_fetch_timeout_ms": 30000 }
}

i can see its getting reflected whatever is configured but i dont see any documentation in official site will add a jira to track it

Comment thread agent/xds/listeners.go Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The terminating gateway has the same problem: makeFilterChainTerminatingGateway (listeners.go:2100) still builds its per-service TLS context with makeCommonTLSContext, so each linked service's leaf is inlined in the listener (LDS), and every rotation drains that service's filter chains. Could we move it to SDS in this PR as well? cc @bharath-k1999

More generally, no listener should embed the Connect leaf inline, and that applies to HTTP listeners as well as TCP.
A filter-chain drain also closes upgraded WebSockets and long-running gRPC streams, and it forces every client to reconnect. The remaining listener call sites are

  1. the API gateway (listeners_apigateway.go:593, :851), which can be a follow-up,
  2. the ingress gateway (listeners_ingress.go:218), which is deprecated and can stay as it is.
  3. The upstream-cluster call sites (clusters.go, failover_policy.go) don't drop connections on rotation. However, every rotation still resends every upstream cluster and its endpoints, and Envoy rebuilds them all. Moving them to SDS is a worthwhile efficiency follow-up, but it's out of scope for this PR.
    cc @bharath-k1999

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Can we create the tickets for these so that we can track and fix in the next cycle

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Separate tickets. yes for 1, 2 and 3.
But for Terminating Gateway, we can have the changes in this PR itself !

The XDSFetchTimeoutMs doc comment listed only EDS and RDS. Connect leaf
certificates and CA roots are now delivered as SDS secrets, so the timeout
applies there too. Also record the concrete Envoy default (15s) and spell out
that a zero value means Envoy waits indefinitely rather than disabling the
fetch.

Comment-only change; no behaviour difference.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread agent/xds/listeners.go Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Separate tickets. yes for 1, 2 and 3.
But for Terminating Gateway, we can have the changes in this PR itself !

bharath-k1999 and others added 2 commits September 28, 2026 17:44
The gateway public listener built each linked service filter chain with
makeCommonTLSContext, inlining that service Connect leaf and the CA roots
into the listener proto. Because those leaves rotate on an automatic timer,
every rotation changed the filter chain hash and drained the affected service
established connections, the same failure already fixed for connect proxies.

Each chain now refers to its leaf and the shared roots by SDS name, so a
rotation updates only Secret resources and leaves the listener bytes untouched.
Leaf secrets are per-service because a terminating gateway holds one leaf per
linked service; the roots are common to every chain so a single shared secret
backs them. Names are derived from ServiceName.String() to stay unique across
namespaces and partitions, and use a -connect-leaf suffix so they cannot
collide with the -cert/-ca secrets carrying the operator-supplied files used
for the gateway upstream connections.

The SDS configs honour xds_fetch_timeout_ms, matching EDS, RDS and the connect
proxy path.

Peered chains still swap in an inline SPIFFE validator, since that validator
has to carry per-trust-domain roots itself. The leaf keeps using SDS there, so
rotation stays hitless for those chains too.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Mirrors TestConnectProxyLeafCertRotationIsHitless for terminating
gateways: it asserts the gateway listener references the linked
service's leaf and the CA roots by SDS name with no inline certificate
material, then holds a long-lived TCP connection open across a forced CA
root rotation and asserts it survives and that Envoy never drained a
filter chain.

The rotation helpers are extracted into libs/certs so both tests share
one implementation rather than duplicating the connection, rotation and
config-dump plumbing.

Gateways had no way to customise their container, so GatewayConfig gains
an optional CustomContainerConfig hook. The test uses it to shorten
Envoy's drain time; without that a regression keeps the connection alive
past the end of the test and looks like a pass.

Unlike the sidecar test, the LDS assertion compares the update count
before and after the rotation instead of requiring exactly one. A
gateway listener can legitimately be programmed more than once while
config entries settle, so the regression being guarded is "rotation
added an update", not an absolute count.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@bharath-k1999 bharath-k1999 changed the title support: implement SDS for Connect proxy leaf certificates connect: serve Connect leaf certificates over SDS so rotation is hitless (sidecars + terminating gateways) Sep 28, 2026
@bharath-k1999
bharath-k1999 enabled auto-merge (squash) September 28, 2026 13:32

@santoshpulluri santoshpulluri left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM.

@bharath-k1999 bharath-k1999 added backport/2.1 Changes are backported to 2.1 backport/ent/2.1 Changes are backported to 2.1 ent labels Sep 28, 2026
@bharath-k1999
bharath-k1999 merged commit 892451c into main Sep 28, 2026
274 of 298 checks passed
@bharath-k1999
bharath-k1999 deleted the bharath/support-sds-for-connect-proxy-leaf-certs branch September 28, 2026 14:16
bharath-k1999 added a commit that referenced this pull request Sep 29, 2026
…on is hitless (sidecars + terminating gateways) (#23938) (#23950)

connect: serve Connect leaf certificates over SDS so rotation is hitless (sidecars + terminating gateways) (#23938)

* support: implement SDS for Connect proxy leaf certificates

* support: deliver sidecar proxy's leaf certificate and CA roots to Envoy over SDS

* support: enhance SDS handling for Connect proxy leaf and root certificates

* Update comments in secrets_test.go for clarity

Clarified comments regarding secret emission behavior in tests.



* Set InitialFetchTimeout on Connect SDS configs and fix stale test comment

Thread the xds_fetch_timeout_ms value through to the connect-leaf and
connect-root SdsSecretConfigs so SDS honours the same operator-configured
initial fetch timeout as EDS and RDS. The value is derived from static proxy
config rather than cert material, so it stays stable across leaf rotations and
does not affect filter chain hashes.

Also update the doc comment on
TestSecretsFromSnapshot_ConnectProxyEmitsEachSecretIndependently, which still
described the earlier all-or-nothing gating instead of the independent
per-secret guards the test now asserts.



* Document that xds_fetch_timeout_ms also applies to SDS

The XDSFetchTimeoutMs doc comment listed only EDS and RDS. Connect leaf
certificates and CA roots are now delivered as SDS secrets, so the timeout
applies there too. Also record the concrete Envoy default (15s) and spell out
that a zero value means Envoy waits indefinitely rather than disabling the
fetch.

Comment-only change; no behaviour difference.



* Deliver terminating gateway downstream leaf certs over SDS

The gateway public listener built each linked service filter chain with
makeCommonTLSContext, inlining that service Connect leaf and the CA roots
into the listener proto. Because those leaves rotate on an automatic timer,
every rotation changed the filter chain hash and drained the affected service
established connections, the same failure already fixed for connect proxies.

Each chain now refers to its leaf and the shared roots by SDS name, so a
rotation updates only Secret resources and leaves the listener bytes untouched.
Leaf secrets are per-service because a terminating gateway holds one leaf per
linked service; the roots are common to every chain so a single shared secret
backs them. Names are derived from ServiceName.String() to stay unique across
namespaces and partitions, and use a -connect-leaf suffix so they cannot
collide with the -cert/-ca secrets carrying the operator-supplied files used
for the gateway upstream connections.

The SDS configs honour xds_fetch_timeout_ms, matching EDS, RDS and the connect
proxy path.

Peered chains still swap in an inline SPIFFE validator, since that validator
has to carry per-trust-domain roots itself. The leaf keeps using SDS there, so
rotation stays hitless for those chains too.



* Add terminating gateway leaf cert rotation integration test

Mirrors TestConnectProxyLeafCertRotationIsHitless for terminating
gateways: it asserts the gateway listener references the linked
service's leaf and the CA roots by SDS name with no inline certificate
material, then holds a long-lived TCP connection open across a forced CA
root rotation and asserts it survives and that Envoy never drained a
filter chain.

The rotation helpers are extracted into libs/certs so both tests share
one implementation rather than duplicating the connection, rotation and
config-dump plumbing.

Gateways had no way to customise their container, so GatewayConfig gains
an optional CustomContainerConfig hook. The test uses it to shorten
Envoy's drain time; without that a regression keeps the connection alive
past the end of the test and looks like a pass.

Unlike the sidecar test, the LDS assertion compares the update count
before and after the rotation instead of requiring exactly one. A
gateway listener can legitimately be programmed more than once while
config entries settle, so the regression being guarded is "rotation
added an update", not an absolute count.



---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
joec4i pushed a commit to bigcommerce/consul that referenced this pull request Oct 16, 2026
Backport of hashicorp/consul PR hashicorp#23938
(hashicorp#23938), also on release/2.1.x as
hashicorp#23950.

Sidecar, mesh gateway and terminating gateway listeners inlined the Connect
leaf cert and CA roots, so every leaf renewal changed the filter chain and
Envoy drained it, closing established connections. The listeners now
reference connect-leaf/connect-root SDS secrets over ADS, so a renewal only
updates the secrets. Outbound cluster TLS stays inline, as upstream.

Conflict resolution for 1.20.x:
- Drop the terminating gateway -cert/-ca file secrets and their tests, which
  come from upstream PR hashicorp#23288 and aren't in 1.20.x.
- Keep 1.20.x createDownstreamTransportSocketForConnectTLS (no multiport ALPN).
- secrets_test.go is new here and carries only this PR's tests.
- Regenerate the xDS goldens.

(cherry picked from commit 892451c)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
joec4i pushed a commit to bigcommerce/consul that referenced this pull request Oct 16, 2026
Backport of hashicorp/consul PR hashicorp#23938
(hashicorp#23938), also on release/2.1.x as
hashicorp#23950.

Sidecar, mesh gateway and terminating gateway listeners inlined the Connect
leaf cert and CA roots, so every leaf renewal changed the filter chain and
Envoy drained it, closing established connections. The listeners now
reference connect-leaf/connect-root SDS secrets over ADS, so a renewal only
updates the secrets. Outbound cluster TLS stays inline, as upstream.

Conflict resolution for 1.22.x:
- Drop the terminating gateway -cert/-ca file secrets and their tests, which
  come from upstream PR hashicorp#23288 and aren't in 1.22.x.
- Keep 1.22.x createDownstreamTransportSocketForConnectTLS (no multiport ALPN).
- secrets_test.go is new here and carries only this PR's tests.
- Regenerate the xDS goldens.

(cherry picked from commit 892451c)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
joec4i pushed a commit to bigcommerce/consul that referenced this pull request Oct 19, 2026
Backport of hashicorp/consul PR hashicorp#23938
(hashicorp#23938), also on release/2.1.x as
hashicorp#23950.

Sidecar, mesh gateway and terminating gateway listeners inlined the Connect
leaf cert and CA roots, so every leaf renewal changed the filter chain and
Envoy drained it, closing established connections. The listeners now
reference connect-leaf/connect-root SDS secrets over ADS, so a renewal only
updates the secrets. Outbound cluster TLS stays inline, as upstream.

Conflict resolution for 2.0.x:
- makeMeshGatewayListeners declares peeredTransportSocket at first use.
- Add the envoy_tls_v3 import to listeners_test.go.
- Drop the transparent-proxy-http-upstream-with-recursors goldens; that test
  case isn't in 2.0.x.

(cherry picked from commit 892451c)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport/ent/1.21 changes are backported to 1.21 ent backport/ent/2.1 Changes are backported to 2.1 ent backport/2.1 Changes are backported to 2.1

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants