Skip to content

fix(agent): give the certificate selector its own SDS stream (#842) - #865

Merged
bpalermo merged 2 commits into
mainfrom
fix/842-cert-selector-own-sds-stream
Sep 20, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/842-cert-selector-own-sds-stream

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Reopens and fixes #842. Do not merge without a validation pass — see Before redeploying.

rev228 (0.93.0-297db48) stopped every mesh upstream mTLS connection on talos-main within seconds of the new proxies taking the config, and rolled back at 16:13Z. This is the root cause, the fix, and the test that would have caught it.

Root cause: the certificate selector fetched over ads: {}

agent/internal/xds/proxy/transportsocket.go:252,272 (at 297db48) passed the same config.XDSConfigSourceADS() to both the transport socket and upstreamCertSelector.

Envoy keys a secret provider on hash(ConfigSource) + "." + name + warm (secret_manager_impl.h:90-91). The on-demand selector always asks with warm=false (cert_selectors/on_demand/config.cc:15-26); every statically named SDS reference asks with warm=true. One secret name therefore gets two independent SdsApi objects with two independent watches — and on a node proxy that is the invariant case, not an edge case:

  • every local pod's SVID is already named statically by that pod's own inbound listener (DownstreamTransportSocket), and
  • the node SVID — the selector's default_value and its prefetch_secret_names — by every inboundready_<pod> probe cluster.

The selector is always the second subscriber. On the delta-ADS mux the second watch loses: Envoy's WatchMap deduplicates subscription interest per (type_url, resource name) across watches, so it contributes nothing to resource_names_subscribe, no request goes out, and the control plane — correctly, for delta — resends nothing. The watch burns its 15 s initial_fetch_timeout, and then nothing else happens: SdsApi::onConfigUpdateFailed (sds_api.cc:183-188) only calls init_target_.ready(); it never notifies the parked certificate-selection callback. doSelectTlsContext's Pending is never resolved.

So the handshake is suspended, not failed — no ssl_connection_error, no ssl_fail_verify_san, an empty upstream_transport_failure_reason, upstream_host selected — until the cluster connect_timeout, or until the downstream gives up first (DC at ~1980 ms).

The fleet metrics said this, once read correctly

Queried over 16:00–16:20Z:

signal during the outage
envoy_cluster_on_demand_secret_cert_requested_total 95 → 196
envoy_cluster_on_demand_secret_cert_updated_total absent (= 0)
envoy_sds_spiffe_..._sa_aether_agent_init_fetch_timeout_total 2 → 6
..._sa_prober_init_fetch_timeout_total 1 → 6
..._sa_authz_canary_/..._sa_uds_client_init_fetch_timeout_total 0 → 1

Two corrections to the issue's own framing:

  • cert_updated does exist. The deploy record concluded it did not; it was zero, and Envoy does not export a counter that never incremented. It is bumped only by the completion callback of the selector's setContext, reachable only from a secret actually arriving — so zero proves no SDS payload ever reached the selector. It is the only success signal the selector has.
  • cert_requested == cert_active is not a health signal. cert_active counts live secret subscriptions and is incremented on the same line as cert_requested (config.cc:105-106); equality only means nothing was removed. It read equal on four of five nodes while the mesh was entirely down.

The fix

One config source. The selector gets its own api_config_source to agent_xds — its own mux, its own watch map — so its subscription can no longer be deduplicated against a static one.

SotW rather than delta on purpose: a SotW response carries every requested resource and GrpcMuxImpl::addWatch queues a request unconditionally, so the failure is structurally impossible on that stream even if a static reference ever lands on it. The agent already serves SecretDiscoveryService on the same socket as ADS (common/xds/xds.go:68), so there is no new bootstrap cluster and no new listener.

⚠ Perturbing the ConfigSource hash is not a fix. Adding an initial_fetch_timeout to ads: {} gives a different provider key while leaving the mux — and therefore the deduplicating watch map — shared. The stream has to be separate.

Cost, measured rather than reasoned: Envoy builds a mux per non-ADS subscription, so this is one gRPC stream per secret name the selector resolves — per identity actually originating traffic on the node, lazily on first use, one resource each. Confirmed in the harness (streams 1, 2, 3, each with its own version/nonce sequence). The chart's max_concurrent_streams: 10 does not cap them: on an upstream cluster that field is what Envoy advertises for peer-initiated streams. The governing limit is the agent's grpc.MaxConcurrentStreams(1000).

The zero-warm property is preserved

The thing #842 exists for, and the one measurement that passed on rev228 (a brand-new-ServiceAccount pod ADD warmed zero clusters, 120/120 samples across five nodes), is untouched. The selector's config source is a constant, so a mesh cluster's bytes still carry no workload input at all. TestServiceClusterBytesChangeOnFirstAndLastPodOfServiceAccount, TestCachedMTLSClusterInvalidatedOnWorkloadChange and TestNoNetnsPathInServiceClusterBytes — the inverted tests that pin it — are unchanged and green.

The test that would have caught it

//test/mtlspool proved pool partitioning against a real Envoy, but rewrote every SDS config source to a bespoke api_config_source because it had no control plane. That substitution, documented as "the ONLY place the harness diverges from the config the agent emits", accidentally was the fix — which is why this passed review and CI.

The harness now also runs the pinned proxy against a real delta-ADS control plane (go-control-plane over a Unix socket, serving CDS/LDS/SDS, api_type: DELTA_GRPC, cds_config/lds_config ads: {}), with the selector's config source left exactly as the agent emits it.

TestOnDemandCertificateResolvesWhenAlreadyStaticallyReferenced adds the one ingredient the harness could not express: the source pod's SVID is referenced both ways, as on any real node. The assertion is completion within a bound, not the absence of errors — the absence of errors is the failure mode.

Red against 297db48:

[ads-delta]  SUBSCRIBE add=[spiffe://aether.internal spiffe://aether.internal/node/test-node] remove=[] nonce=""
[ads-delta]  RESPOND   resources=[spiffe://aether.internal spiffe://aether.internal/node/test-node] removed=[]
[ads-delta]  SUBSCRIBE add=[] remove=[] nonce="2"
[ads-delta]  SUBSCRIBE add=[spiffe://aether.internal/ns/demo/sa/source-a spiffe://aether.internal/ns/demo/sa/source-b] remove=[] nonce=""
[ads-delta]  RESPOND   resources=[spiffe://aether.internal/ns/demo/sa/source-a spiffe://aether.internal/ns/demo/sa/source-b] removed=[]
[ads-delta]  SUBSCRIBE add=[] remove=[] nonce="4"
[envoy] [warning][config] grpc_subscription_impl.cc:130] gRPC config: initial fetch timed out for
        type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret
source-a: request did not complete in 2.00161679s: status 503
        The upstream mTLS handshake PAUSED: the on-demand certificate
        selector returned Pending and no SDS response ever resumed it.
        Expect NO ssl_connection_error and NO transport failure reason --
        the absence of errors is the failure mode, not evidence against it.
--- FAIL: TestOnDemandCertificateResolvesWhenAlreadyStaticallyReferenced (17.14s)

Note what is absent: there is no third SUBSCRIBE. The selector's request never reached the wire — which is the whole defect, and which no amount of control-plane-side logging would have revealed.

Green with the fix, on a separate stream, in 10 ms:

[ads-delta]  SUBSCRIBE add=[.../node/test-node .../sa/source-a .../sa/source-b] remove=[] nonce=""
[ads-delta]  RESPOND   resources=[.../node/test-node .../sa/source-a .../sa/source-b] removed=[]
[sds-sotw]   stream=2 REQUEST names=[spiffe://aether.internal/ns/demo/sa/source-a] version="" nonce=""
[sds-sotw]   RESPOND   count=1 version="1"
first request completed in 10.399118ms: destination verified spiffe://aether.internal/ns/demo/sa/source-a
  cluster.mesh_echo.on_demand_secret.cert_requested: 2
  cluster.mesh_echo.on_demand_secret.cert_updated: 3
--- PASS

Also added:

  • TestMeshCertSelectorSDSSourceIsNotSharedWithAnyStaticSecret (agent/internal/xds/proxy) — the separation checked from both ends, over every builder that names a secret statically. Pointing one at the selector's stream would put a warm=true and a warm=false provider back on one mux and restore the starvation, silently.
  • //test/envoy_validate asserts over the serialised node bootstrap that the selector does not ride ads, that it names exactly one explicit gRPC source, and that the backing cluster resolves against a cluster the bootstrap defines — a dangling-reference check that the lazy on-demand subscription would otherwise hide from envoy --mode validate.
  • The harness control plane now registers SecretDiscoveryService alongside ADS, as the agent does; and xdsTrace logs subscribe/respond on both transports, which is what distinguishes "Envoy never asked" from "the control plane never answered".

docs/runbook.md gains a "The rev228 outage" section under "#842" with the diagnosis order: cert_updated flat while cert_requested climbs → sds.<name>.init_fetch_timeout → /config_dump?resource=dynamic_warming_secrets.

Verification

  • bazel test //... — 107/107 pass.
  • bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //... — clean.
  • make deps-audit — OK, no new modules.
  • make format, make gazelle — clean.
  • Chart bumped 0.93.0 → 0.93.1 (the agent_xds comment now documents both stream kinds and corrects the max_concurrent_streams reading).

Before redeploying

This has not been on a cluster; talos-main is on the rolled-back build with a soak pending. The harness reproduces the exact failure and the fix clears it against the pinned proxy, but two things are unverified on real hardware:

  1. Stream count at fleet scale. One SDS stream per originating identity per node is measured in a two-identity harness, not at talos-main's density.
  2. Behaviour across a secret version bump. The harness serves a static snapshot; SVID rotation over the selector's SotW stream is untested here.

Suggested gate on redeploy: watch envoy_cluster_on_demand_secret_cert_updated_total become non-zero (that is the signal whose absence was the outage), envoy_sds_spiffe_*_init_fetch_timeout_total stay flat, and re-run the new-ServiceAccount zero-warm sample to confirm the property survives.

Finally: AetherClusterIdentityNoMatch (k8s-talos-main GitOps #109) is still a vacuous gate from #863 and still needs repointing — unchanged by this PR.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-Authored-By: Claude Opus 5 [email protected]

rev228 took every mesh upstream mTLS connection on talos-main down within
seconds of the new proxies taking the config. The handshakes PAUSE rather than
fail, so nothing you would normally check moved: no ssl_connection_error, no
ssl_fail_verify_san, an empty upstream_transport_failure_reason, and an
upstream_host duly selected on every hung request.

Root cause: the on-demand certificate selector fetched over `ads: {}`.

Envoy keys a secret provider on hash(ConfigSource) + "." + name + warm. The
selector always asks with warm=false; every statically named SDS reference asks
with warm=true. So one secret name gets two independent SdsApi objects with two
independent watches — and on a node proxy that is the normal case: every local
pod's SVID is already named statically by that pod's own inbound listener, and
the node SVID (the selector's default_value AND its prefetch) by every
inboundready_<pod> probe cluster. The selector is always the second subscriber.

On the delta-ADS mux the second watch loses. Envoy's WatchMap deduplicates
subscription interest per (type_url, resource name) across watches, so it
contributes nothing to resource_names_subscribe; no request goes out; the
control plane — correctly, for delta — resends nothing. The watch burns its 15s
initial_fetch_timeout and then does nothing else, because
SdsApi::onConfigUpdateFailed only calls init_target_.ready(): it never notifies
the parked certificate-selection callback. doSelectTlsContext's Pending is
never resolved and the connection hangs until connect_timeout, or until the
downstream gives up first (DC at ~1980ms on the fleet).

The fleet metrics say exactly this, once read correctly:
cert_requested climbed to 196 while cert_updated stayed ABSENT (i.e. zero — the
only thing that increments it is a secret actually arriving), and
envoy_sds_spiffe_<name>_init_fetch_timeout_total climbed for the node SVID and
for workload SVIDs. cert_requested == cert_active is NOT a health signal:
cert_active counts live subscriptions and is incremented on the same line as
cert_requested.

The fix is one config source. The selector gets its own api_config_source to
agent_xds — its own mux, its own watch map — so its subscription can no longer
be deduplicated against a static one. SotW rather than delta on purpose: a SotW
response carries every requested resource and GrpcMuxImpl::addWatch queues a
request unconditionally, so the failure is structurally impossible there even if
a static reference ever lands on it. The agent already serves
SecretDiscoveryService on the same socket as ADS, so no new bootstrap cluster.

Perturbing the ConfigSource hash is not a fix: that changes the provider key
while leaving the mux, and therefore the deduplicating watch map, shared.

Cost, measured: Envoy builds a mux per non-ADS subscription, so this is one gRPC
stream per secret name the selector resolves — per identity actually originating
traffic on the node, lazily on first use, one resource each. The chart's
max_concurrent_streams: 10 does not cap them (on an upstream cluster that field
is what Envoy advertises for peer-initiated streams); the agent's
grpc.MaxConcurrentStreams(1000) does.

The zero-warm property #842 exists for is untouched: the selector's config
source is a constant, so a mesh cluster's bytes still carry no workload input.

Tests:

//test/mtlspool gains the half it shipped without. It proved pool partitioning
against a real Envoy but rewrote every SDS config source to a bespoke
api_config_source, because it had no control plane — which accidentally WAS the
fix, and is why this passed review and CI. It now also runs the pinned proxy
against a real delta-ADS control plane serving CDS/LDS/SDS over a Unix socket,
with the selector's source left exactly as the agent emits it.

TestOnDemandCertificateResolvesWhenAlreadyStaticallyReferenced is the gate: the
source pod's SVID is referenced BOTH ways, as it is on any real node, and the
assertion is completion within a bound rather than the absence of errors — the
absence of errors is the failure mode. Red against the shipped configuration:

    [ads-delta] SUBSCRIBE add=[.../node/test-node] remove=[] nonce=""
    [ads-delta] RESPOND   resources=[.../node/test-node] removed=[]
    [ads-delta] SUBSCRIBE add=[.../sa/source-a .../sa/source-b] remove=[]
    [ads-delta] RESPOND   resources=[.../sa/source-a .../sa/source-b]
    [envoy] warning: gRPC config: initial fetch timed out for
            type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret
    source-a: request did not complete in 2.001705182s: status 503
    --- FAIL: TestOnDemandCertificateResolvesWhenAlreadyStaticallyReferenced (17.15s)

Note what is absent from that trace: no third SUBSCRIBE. The selector's request
never reached the wire.

Also added: TestMeshCertSelectorSDSSourceIsNotSharedWithAnyStaticSecret, which
checks the separation from both ends over every builder that names a secret
statically — pointing one at the selector's stream would restore the starvation
silently; and //test/envoy_validate now asserts, over the serialised node
bootstrap, that the selector does not ride ads and that its backing cluster
actually resolves.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…#842)

Moving the certificate selector off `ads: {}` fixes the COLD fetch. It says
nothing about the second thing that stream has to do: deliver a new version of a
secret it has already resolved.

That gap is not theoretical and it is badly timed. SPIRE rotates SVIDs on a ~4h
TTL, so a 60-75 minute deploy validation crosses no rotation while an 8h soak
crosses about two. If rotation were broken here, the first thing to notice would
be a soak four hours in — and because this subsystem fails by PAUSING, it would
present as the soak going quiet rather than as an error. It is also precisely
the shape of mistake that produced rev228: a path nobody exercised, shipped on
the strength of reasoning about a path that was.

TestRotatedSVIDIsPickedUpOverTheSelectorStream republishes every SVID under a new
snapshot version — the same shape as the agent's SetSecrets, secrets only, so
the listeners are not withdrawn — and requires that:

  - the destination verifies a different certificate SERIAL for the same SPIFFE
    ID (the SAN cannot change; that is what a rotation is);
  - it happens within a bound, not merely eventually;
  - cert_updated moves, read as a positive obligation;
  - every request throughout completes. A rotation that resolved correctly but
    stalled a request mid-flight is still a data-plane outage, and with this
    failure mode a stall is what it would look like.

The identity is also statically referenced, as in the reproduction, because that
is the shape of a real node and rotation has to work in it.

Result: the rotated certificate is picked up on the FIRST post-rotation request,
4.7ms after publication, cert_updated 2 -> 4, SAN unchanged and serial changed.

    pre-rotation:  SAN=spiffe://aether.internal/ns/demo/sa/source-a serial=...134652448
    [sds-sotw]   RESPOND   count=1 version="2"
    rotated: generation 2 of every SVID published at snapshot version 2
    post-rotation: SAN=spiffe://aether.internal/ns/demo/sa/source-a serial=...256300227 after 1 request(s) in 4.734934ms
    cert_updated: 2 -> 4 across the rotation
    --- PASS: TestRotatedSVIDIsPickedUpOverTheSelectorStream (0.16s)

Proven non-vacuous: with the rotation call removed the test polls 78 times over
20s and fails on the serial assertion, so the gate bites rather than passing
because nothing was ever checked.

Mechanics: the destination now reports the verified leaf's SERIAL alongside its
URI SAN, because a rotated SVID carries the same SPIFFE ID and the serial is the
only thing that distinguishes "still using the certificate resolved at startup"
from "picked up the new one". Secrets are generation-tagged so a re-issue lands
on its own files — the resources are file data sources, and re-issuing over the
same path would mutate what the previous generation pointed at and pass without
anything having been delivered. The mesh cluster takes
max_requests_per_connection: 1 in this test only, so the observation is the next
request rather than whenever a pooled connection is reclaimed; a pooled
connection legitimately keeps its certificate and that is not under test.

Also documents in the runbook the hot-restart stat trap that produced the w05
anomaly: two live Envoy epochs both export, and when the parent's series goes
away the summed GAUGE (cert_active) drops to the child's alone while the COUNTER
(cert_requested) keeps the merged total, since StatMerger transfers gauges
absolute and counters as deltas. w05's requested=55/active=28 looked like 27
secret removals and was nothing of the kind — consistent with cert_updated == 0,
and no independent defect.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo

Copy link
Copy Markdown
Owner Author

Update: SVID rotation gate added (was the last open gap), and the w05 anomaly is resolved

Rotation over the selector's own stream — works, and is now gated

Moving the selector off ads: {} fixes the cold fetch. It says nothing about the second thing that stream has to do: deliver a new version of a secret it has already resolved. With a ~4 h SVID TTL, a 60–75 minute deploy validation crosses no rotation while an 8 h soak crosses about two — so a rotation defect would first surface as a soak going quiet several hours in, with no error anywhere. That is the worst possible place to find it, and it is the same shape of mistake as rev228: a path nobody exercised.

TestRotatedSVIDIsPickedUpOverTheSelectorStream republishes every SVID under a new snapshot version (secrets only, the same shape as the agent's SetSecrets) and requires the destination to verify a different certificate serial for the same SPIFFE ID — the SAN cannot change, that is what a rotation is — within a bound, with cert_updated moving, and with every request throughout completing.

pre-rotation:  SAN=spiffe://aether.internal/ns/demo/sa/source-a serial=...134652448
[sds-sotw]   RESPOND   count=1 version="2"
rotated: generation 2 of every SVID published at snapshot version 2
post-rotation: SAN=spiffe://aether.internal/ns/demo/sa/source-a serial=...256300227 after 1 request(s) in 4.734934ms
cert_updated: 2 -> 4 across the rotation
--- PASS: TestRotatedSVIDIsPickedUpOverTheSelectorStream (0.16s)

Picked up on the first post-rotation request, 4.7 ms after publication.

Proven non-vacuous. With the rotation call removed, the test polls 78 times over 20 s and fails on the serial assertion:

post-rotation: SAN=.../sa/source-a serial=1789924242859349035 after 78 request(s) in 20.002948181s
Messages: the selector never picked up the rotated SVID within 20s: the destination still
          verifies certificate serial 1789924242859349035. ...
--- FAIL: TestRotatedSVIDIsPickedUpOverTheSelectorStream (20.15s)

The identity is statically referenced here too, as in the reproduction, because that is the shape of a real node and rotation has to work in it.

Three mechanics worth knowing, all commented at their call sites:

  • the destination now reports the verified leaf's serial alongside its URI SAN, since the SPIFFE ID is unchanged across a rotation and the serial is the only discriminator;
  • secrets are generation-tagged on disk — they are file data sources, so re-issuing over the same path would mutate what the previous generation's resource points at and the test would pass without anything having been delivered;
  • the mesh cluster takes max_requests_per_connection: 1 in this test only, so the observation is the next request rather than whenever a pooled connection is reclaimed. A pooled connection legitimately keeps the certificate it handshook with; that is correct and is not under test.

The w05 anomaly is resolved — and it is not an independent finding

requested=55, active=28 with cert_updated == 0 was internally inconsistent by my own decoding. It is a hot-restart accounting artefact. Per-node series:

16:05:30Z 16:06:00Z onward
cert_active 55 28
cert_requested 55 55

with envoy_server_live = 2 and envoy_server_hot_restart_epoch 0 → 1 at 16:05:00Z. Two Envoy epochs were live and both exporting; when the parent's series went away the summed gauge fell to the child's alone while the counter kept the merged total, because StatMerger transfers gauges absolute and counters as deltas. No doRemoveCertificateConfig ran — exactly consistent with cert_updated == 0. Nothing to file.

Corollary, now in the runbook: cert_requested and cert_active cannot be compared across a hot restart at all. Check envoy_server_live and envoy_server_hot_restart_epoch before reading anything into the pair.

Record corrected

The cert_updated claim is corrected on #842 (it exists; it was absent because it was zero, and that absence was the proof rather than a gap). The rev228 memory record carries the same correction.

Remaining unverified

Down to one: stream count at fleet density. One SDS stream per originating identity is measured in a two-or-three-identity harness, not at talos-main's density, and neither is its Envoy RSS cost. Everything else in the earlier "before redeploying" list is now covered by a test.

Verification re-run after these changes: bazel test //... 107/107, lint clean, make deps-audit OK.

@bpalermo
bpalermo merged commit 8d0d5da into main Sep 20, 2026
22 checks passed
@bpalermo
bpalermo deleted the fix/842-cert-selector-own-sds-stream branch September 20, 2026 17:34
bpalermo added a commit that referenced this pull request Sep 27, 2026
…not the originator SDS version gauges (#992) (#1010)

The per-connection cert selector's own SotW SDS stream (#865) re-serves an
originating identity's secret on every snapshot bump, and Envoy keys SDS stats
by secret name, so envoy_sds_*_version over-reads rotations ~50x for those
identities. Name aether_agent_spire_svid_updates_total{update="rotated"} as the
signal in the soak README and runbook, with the PromQL and the why.


Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make the source-identity filter state Hashable so the mesh can drop connection_pool_per_downstream_connection

1 participant