Skip to content

fix(agent): make SPIRE bridge SDS publication monotonic; never publish an empty trust-bundle set (#772) - #784

Merged
bpalermo merged 2 commits into
mainfrom
fix/772-a6a-sds-push-ordering
Sep 16, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/772-a6a-sds-push-ordering

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Phase A6a of #772 (inside the #638 blast radius; validated on talos-main with the #638 discriminator counters flat across a proxy roll).

fix(agent): make SPIRE bridge SDS publication monotonic (#772) (A6a)

pushSecrets was build-then-publish with no serialisation: it snapshotted
b.secrets under mu, released it, and called store.SetSecrets — a
whole-map replace. Four independent goroutines reach it (the bundle stream,
every per-pod SVID stream, the node-SVID refresher, and UnsubscribePod off
the CNI DEL path), so two overlapping pushes — an SVID rotation racing a
bundle update, or a Updated() wake from #740's bridge changes — could land
the older set on top of the newer one. Last writer wins, and a just-arrived
secret disappears from the SDS snapshot until something else pushes. That is
the "Secret is not supplied by SDS" / secret-absent WARN family, squarely
inside the still-open #638 blast radius. (races report S10.)

S11, same file: handleBundleUpdate deleted every validation-context
secret and then re-added them one trust domain at a time, returning early on
a conversion error. One malformed bundle mid-loop left the map with no trust
bundles at all and no push — and the next push from any other goroutine then
served Envoy a secret set with nothing to verify peers against.

Design choice — a mutex plus a monotonic generation stamp, not a
single-writer goroutine fed by a dirty signal:

  • pushSecrets keeps its synchronous error return. UnsubscribePod
    propagates it to the CNI DEL caller and the SVID/bundle handlers log it; a
    background writer would strand those errors with nowhere to go.
  • No new goroutine lifecycle to get right. refreshNodeSVID pushes from
    Start before the bundle loop is running, and UnsubscribePod pushes
    from the CNI server — a writer goroutine would have to outlive Start's
    window or silently drop those pushes.
  • The generation stamp delivers the coalescing the single-writer shape was
    wanted for: overlapping wakes collapse, because a pusher that finds the
    store already holding its generation returns without a redundant
    SetSecrets (each one regenerates the whole node snapshot).

Changes:

  • bridge.go: gen (guarded by mu, bumped by every secret mutation) and
    pushMu + publishedGen. pushSecrets holds pushMu across BOTH the
    build and the publish, so publishes happen in generation order and each
    carries the newest state at build time; gen == publishedGen is skipped as
    already-served and gen < publishedGen is rejected as stale. publishedGen
    advances only on a successful SetSecrets, so a failed push is retried by
    the next one.
  • bridge.go handleBundleUpdate: build the complete validation-context map
    in a local and swap it in under mu only once every trust domain
    converted; a conversion error now leaves the served bundles untouched. A
    response carrying zero trust bundles while non-empty contexts are already
    served is never a legitimate instruction to stop verifying peers: keep the
    previous ones, WARN, and count it. Bundles are keyed by the canonical secret
    name rather than the raw response key (they differ when SPIRE reports a bare
    trust domain).
  • bridge.go handleSVIDUpdate: convert before mutating, so a malformed SVID
    mid-response leaves the served set untouched instead of half-applied.
  • metrics.go: aether.agent.sds_push.stale_rejected and
    aether.agent.sds_push.empty_bundle_skipped, both seeded with Add(ctx, 0)
    at registration — the fix(agent): seed the #638 identity mismatch counters at zero (false-zero in Prometheus) #717 lesson: the OTel SDK exports a counter only after
    its first Add, and both of these are zero in a healthy agent, so without
    seeding "never registered" and "zero" are indistinguishable to a grading
    query.

Tests (bridge_push_ordering_test.go), all under --config=race:

  • TestPushSecretsPublishesMonotonically drives 150 rounds each of two
    concurrent SVID rotations and a bundle update against a store that records
    every published set in publish order, then asserts over the whole sequence:
    no identity's SVID version ever goes backwards or vanishes, no set is
    published without a validation context once one has been served, and the
    final publication carries the newest inputs with publishedGen == gen.
  • TestHandleBundleUpdateKeepsBundlesOnConversionError and
    TestHandleBundleUpdateSkipsEmptyBundleSet cover S11 from both sides.
  • TestBridgeMetricsSDSPushCountersSeededAtZero pins the seeding.

Proof the old code fails these, measured by reverting each hunk in place:
with the pre-fix pushSecrets, TestPushSecretsPublishesMonotonically failed
3 out of 3 --runs_per_test under --config=race ("push 61 regressed SVID
.../sa/svc-b from v27 to v26", "push 16 ... v8 to v7", "push 13 ... v5 to
v4"). With the pre-fix handleBundleUpdate, both S11 tests failed ("the
previously served trust bundle must survive a failed update"; "an empty bundle
update must not publish anything").

Verification: bazel build //... //test/e2e:e2e_test; bazel test //...
(100 pass); bazel test //agent/internal/spire/... //agent/internal/xds/... --config=race --runs_per_test=3 (9 targets, 27 runs, all pass);
bazel test //test/envoy_validate/...; bazel run //:format.check;
bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //agent/...; bazel run //:gazelle no churn; bazel mod tidy idempotent;
scripts/go-deps-audit.sh exit 0.

Data-plane change: needs a hitless-rollout validation on talos-main with the
#638 discriminator counters (aether_agent_identity_{inbound,outbound}_binding_mismatch_total)
flat across a proxy roll, plus the two new counters reading 0.

Refs #772, #638, #717, #740.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 2 commits September 15, 2026 20:29
`pushSecrets` was build-then-publish with no serialisation: it snapshotted
`b.secrets` under `mu`, released it, and called `store.SetSecrets` — a
whole-map replace. Four independent goroutines reach it (the bundle stream,
every per-pod SVID stream, the node-SVID refresher, and `UnsubscribePod` off
the CNI DEL path), so two overlapping pushes — an SVID rotation racing a
bundle update, or a `Updated()` wake from #740's bridge changes — could land
the older set on top of the newer one. Last writer wins, and a just-arrived
secret disappears from the SDS snapshot until something else pushes. That is
the "Secret is not supplied by SDS" / secret-absent WARN family, squarely
inside the still-open #638 blast radius. (races report S10.)

S11, same file: `handleBundleUpdate` deleted *every* validation-context
secret and then re-added them one trust domain at a time, returning early on
a conversion error. One malformed bundle mid-loop left the map with no trust
bundles at all and no push — and the next push from any other goroutine then
served Envoy a secret set with nothing to verify peers against.

Design choice — a mutex plus a monotonic generation stamp, not a
single-writer goroutine fed by a dirty signal:

- `pushSecrets` keeps its synchronous error return. `UnsubscribePod`
  propagates it to the CNI DEL caller and the SVID/bundle handlers log it; a
  background writer would strand those errors with nowhere to go.
- No new goroutine lifecycle to get right. `refreshNodeSVID` pushes from
  `Start` *before* the bundle loop is running, and `UnsubscribePod` pushes
  from the CNI server — a writer goroutine would have to outlive `Start`'s
  window or silently drop those pushes.
- The generation stamp delivers the coalescing the single-writer shape was
  wanted for: overlapping wakes collapse, because a pusher that finds the
  store already holding its generation returns without a redundant
  `SetSecrets` (each one regenerates the whole node snapshot).

Changes:

- `bridge.go`: `gen` (guarded by `mu`, bumped by every secret mutation) and
  `pushMu` + `publishedGen`. `pushSecrets` holds `pushMu` across BOTH the
  build and the publish, so publishes happen in generation order and each
  carries the newest state at build time; `gen == publishedGen` is skipped as
  already-served and `gen < publishedGen` is rejected as stale. `publishedGen`
  advances only on a successful `SetSecrets`, so a failed push is retried by
  the next one.
- `bridge.go` `handleBundleUpdate`: build the complete validation-context map
  in a local and swap it in under `mu` only once every trust domain
  converted; a conversion error now leaves the served bundles untouched. A
  response carrying zero trust bundles while non-empty contexts are already
  served is never a legitimate instruction to stop verifying peers: keep the
  previous ones, WARN, and count it. Bundles are keyed by the canonical secret
  name rather than the raw response key (they differ when SPIRE reports a bare
  trust domain).
- `bridge.go` `handleSVIDUpdate`: convert before mutating, so a malformed SVID
  mid-response leaves the served set untouched instead of half-applied.
- `metrics.go`: `aether.agent.sds_push.stale_rejected` and
  `aether.agent.sds_push.empty_bundle_skipped`, both seeded with `Add(ctx, 0)`
  at registration — the #717 lesson: the OTel SDK exports a counter only after
  its first Add, and both of these are zero in a healthy agent, so without
  seeding "never registered" and "zero" are indistinguishable to a grading
  query.

Tests (`bridge_push_ordering_test.go`), all under `--config=race`:

- `TestPushSecretsPublishesMonotonically` drives 150 rounds each of two
  concurrent SVID rotations and a bundle update against a store that records
  every published set in publish order, then asserts over the whole sequence:
  no identity's SVID version ever goes backwards or vanishes, no set is
  published without a validation context once one has been served, and the
  final publication carries the newest inputs with `publishedGen == gen`.
- `TestHandleBundleUpdateKeepsBundlesOnConversionError` and
  `TestHandleBundleUpdateSkipsEmptyBundleSet` cover S11 from both sides.
- `TestBridgeMetricsSDSPushCountersSeededAtZero` pins the seeding.

Proof the old code fails these, measured by reverting each hunk in place:
with the pre-fix `pushSecrets`, `TestPushSecretsPublishesMonotonically` failed
3 out of 3 `--runs_per_test` under `--config=race` ("push 61 regressed SVID
.../sa/svc-b from v27 to v26", "push 16 ... v8 to v7", "push 13 ... v5 to
v4"). With the pre-fix `handleBundleUpdate`, both S11 tests failed ("the
previously served trust bundle must survive a failed update"; "an empty bundle
update must not publish anything").

Verification: `bazel build //... //test/e2e:e2e_test`; `bazel test //...`
(100 pass); `bazel test //agent/internal/spire/... //agent/internal/xds/...
--config=race --runs_per_test=3` (9 targets, 27 runs, all pass);
`bazel test //test/envoy_validate/...`; `bazel run //:format.check`;
`bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation
//agent/...`; `bazel run //:gazelle` no churn; `bazel mod tidy` idempotent;
`scripts/go-deps-audit.sh` exit 0.

Data-plane change: needs a hitless-rollout validation on talos-main with the
#638 discriminator counters (`aether_agent_identity_{inbound,outbound}_binding_mismatch_total`)
flat across a proxy roll, plus the two new counters reading 0.

Refs #772, #638, #717, #740.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 508064e into main Sep 16, 2026
20 checks passed
@bpalermo
bpalermo deleted the fix/772-a6a-sds-push-ordering branch September 16, 2026 00:40
bpalermo added a commit that referenced this pull request Sep 18, 2026
…Broker API (#800) (036) (#802)

Proposal 036, phase 1: a hard switch, not an opt-in. The node agent no longer
mints per-pod SVIDs through SPIRE's proprietary Delegated Identity API on the
agent admin socket with a selector set it builds by hand; it presents a
KubernetesObjectReference over the standard SPIFFE Broker Endpoint and SPIRE
resolves and attests the referenced pod itself. The delegated client, the
admin-socket plumbing and the spire-api-sdk dependency are deleted.

What that buys: every selector SPIRE's Kubernetes attestor can produce (pod
labels, container image, sigstore) becomes usable in a registration entry —
under the delegated path an entry keyed on anything other than the four
selectors the agent supplied could never match, because SPIRE never attested
the pod. The all-or-nothing admin socket and its authorizedDelegates allow-list
disappear, and the agent speaks a SPIFFE standard rather than a SPIRE API.

agent/internal/spire/client.go is now a Broker client: it dials
unix://<broker socket> with mutual TLS built from the agent's own WaitingSource
identity, authorises the server as a SPIFFE ID in our OWN trust domain under
/spire/agent/ (the endpoint spec requires the broker to authenticate the
provider, and "any member of the trust domain" would let any workload that can
bind the socket path hand us poisoned SVIDs), and adds the mandatory
broker.spiffe.io: true metadata on every unary and streaming call via
interceptors. #740 semantics carry over unchanged: no SVID yet simply means the
handshake cannot complete, the subscribe fails, and the bridge retries — the
agent never exits.

Two things the delegated path never had to handle:

- A reference resolves at REQUEST time, so a CNI ADD routinely beats the pod
  into the kubelet's pod list and gets NotFound. SubscribePod therefore never
  blocks on the broker: it registers the subscription and hands the first
  subscribe to the subscription's own goroutine, which retries on the existing
  jittered backoff. The gRPC codes are mapped per the proposal's Errors bullet
  (NotFound/FailedPrecondition retry, PermissionDenied retries slowly,
  Unauthenticated retries — go-spiffe re-reads the SVID per handshake, so a
  plain retry IS the credential refresh —, InvalidArgument never retries), with
  new counters aether.agent.spire.broker.{reference_not_found,permission_denied}
  seeded at zero (#717) and an INFO->WARN escalation once one reference has been
  unresolved for 30s.
- SPIRE blocks inside its own cache subscription before the handler sends
  anything, so a reference that resolves to an entry whose SVID never lands
  leaves Recv blocked forever with no error, no log line and no retry. The first
  receive is synchronous (that is where NotFound/PermissionDenied arrive at all)
  and bounded by firstResponseTimeout, which turns that silent hang into an
  ordinary retry that also re-resolves the reference.

Trust bundles needed rebuilding, because the Broker API has no node-wide bundle
stream — SubscribeToX509Bundles also takes a workload reference, and a node with
zero managed pods has none. Validation contexts are now DERIVED from two inputs:
the agent's own Workload API bundle (available as soon as SPIRE attests the
agent itself, strictly earlier than any pod's) and the union of the
federated_bundles each live pod stream carries, dropped when that pod
unsubscribes. #784's guarantees are unchanged and re-tested: single-writer
monotonic publication under pushMu with the generation stamp, and never
replacing a non-empty validation-context set with an empty one.

The converter takes the Broker X509SVID, whose chain is ONE concatenated ASN.1
DER byte string (leaf first) rather than a repeated field — the boundaries are
not given, so the chain must be parsed to be split, and a chain Envoy could not
load is now rejected where the error names the SVID.

Call sites, flags and chart: the CNI server passes namespace/name/UID instead of
selectors (the UID was already in the ADD path and in storage);
--spire-broker-socket replaces --spire-admin-socket (added to
TestRetiredFlagsGone); spire.adminSocket.* becomes spire.brokerSocket.* pointing
at /run/spire/agent/sockets/csi.spiffe.io/broker, where the spiffe/spire chart
puts the socket directory on the node. The socket is mode 0770 owned by the
spire-agent uid:gid, which the agent's existing runAsUser:0 + DAC_OVERRIDE
already covers, so no securityContext change and the same read-only hostPath
mount shape (verified on all five talos-main nodes under k8s-talos-main#79).

Proposal 036 is corrected in one place while its Status moves to implemented:
the access policy ships as an EXPLICIT permissive, never the chart's `auto`.
The chart's broker-access-policy helper escalates `auto` to `enforced` for any
allowed reference type other than WorkloadPIDReference — i.e. for the
KubernetesObjectReference this design uses — and `enforced` needs an
impersonation RBAC grant the chart only renders when the broker also sets
impersonation.clusterWidePodsOnly. `auto` alone therefore fails CLOSED with
PermissionDenied on every pod. Phasing item 3 now says the hardening step must
flip both at once.

Tests. A fake SPIFFE Broker Endpoint in common/spire/spiretest serves real mTLS
from a test CA, rejects any call missing the security header with
InvalidArgument, resolves references from a table and can return NotFound-then-
success, PermissionDenied, an early stream close and federated bundles — so the
bridge tests exercise the production client, a real UDS, a real handshake and
the real interceptors rather than a stub. Every existing test is ported, none
dropped: the push-ordering/S10/S11 suite (now driven through per-pod federated
bundles, with certificate serials carrying the SVID generation because the
converter parses the chain), the reconnect suite, the late-identity #740 test
and the node-SVID converter tests. New: the security header and the full
key+UID reference on every call, the server authorizer rejecting both a
non-SPIRE-agent path and a foreign trust domain, NotFound retrying to success,
the PermissionDenied counter, federated-bundle union add/remove, a zero-pod node
still serving validation contexts, a rotation on a live stream, and the error
classification table.

A second flag-contract test mirrors //agent/internal/supervisorcmd for the agent
DaemonSet: every --flag the chart passes must exist on the command. Without it a
half-migrated chart is invisible until a rollout leaves every node's agent
exiting on "unknown flag".

e2e harnesses move from SPIRE chart 0.28.4 (SPIRE 1.14.5, no Broker API) to
0.30.2 with crds 0.6.1, drop authorizedDelegates + sockets.admin, and register
the broker in both required blocks.

Verification: bazel build //... //test/e2e:e2e_test; bazel test //... (106
tests, all pass); bazel test --config=race --runs_per_test=3
//agent/internal/spire/... //common/spire/... //agent/internal/cni/... ;
//:format.check; --config=lint --@aspect_rules_lint//lint:fail_on_violation
//... ; gazelle no churn; bazel mod tidy idempotent; scripts/go-deps-audit.sh
OK after pruning spire-api-sdk's ten go.sum lines.

Not verifiable without a live SPIRE >= 1.15.2: the on-wire interop itself.
Validated on talos-main by the orchestrator.


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.

1 participant