Skip to content

Authenticate clients with SPIFFE X.509-SVIDs - #7092

Merged
jhrozek merged 1 commit into
mainfrom
spiffe-v2-07-x509-client-auth
Nov 11, 2026
Merged

jhrozek merged 1 commit into
mainfrom
spiffe-v2-07-x509-client-auth

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Workloads could not authenticate to the auth server with an X.509-SVID. The certificate was read by middleware and never verified, and any SPIFFE trust configuration was rejected at startup as a placeholder. This PR makes X.509 client authentication work and turns SPIFFE client authentication on for the file bundle source.

  • The client-authentication strategy reads the peer certificate directly and verifies it against the live trust bundle on every request, so bundle rotation applies without a restart. A presented chain longer than four certificates is rejected before verification, which bounds the work a client can force per request.
  • The strategy picks the verifier from the requested client, not from the certificate. A SPIFFE JWT assertion selects the JWT arm and the certificate is ignored. The X.509 arm runs only when a client_id names an association that enables spiffe_x509, and it never falls back. Any other request uses the default strategy and a presented certificate is transport identity only. A workload can present an SVID as transport identity on any connection, so JWT-SVID, delegate and public clients must keep working on the same listener.
  • Both arms use one resolver, so an association gives the same result whichever credential a workload presents.
  • The "not yet enforced" startup gate is removed. Only the file source has a loader, so bundle_endpoint and workload_api are rejected at every validation point, including the operator's config resource.
  • Validation covers shapes that became reachable once the gate was removed: SPIFFE-only configs (no upstream, delegate client or trusted issuer) are accepted by the auth server and vMCP validators, and an http issuer, a SPIFFE client_id equal to a delegate client_id, and associations with token exchange disabled are rejected.
  • SPIFFE association clients are token-exchange only, so they are excluded from the ID-JAG jwt-bearer grant.
  • A changed association now replaces its stored placeholder and logs a WARN. Before, startup failed, so on Redis an edit such as narrowing scopes never rolled out.
  • A rejected bundle sequence number and a bundle going stale are logged once at WARN. Without it, a bundle rollback fails silently 24 hours later.
  • The unused exported helpers Middleware, ContextWithSPIFFEID and SPIFFEIDFromContext are removed. Nothing in the repo used them.

Part of #6202.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test): the full run on this branch rebased on main exited 0 and printed no failures. The packages this PR touches (./pkg/authserver/..., ./pkg/vmcp/config/, and the operator api/v1beta1, controllers and controllerutil packages) also passed in a separate run that reports the real go test exit code.
  • E2E tests (task test-e2e)
  • Linting (task lint-fix): ran over the whole repo after rebasing on main, 0 issues, no files changed. task docs, operator-manifests and crdref-gen produce no diff.
  • Manual testing (describe below)

New tests issue real tokens through the TLS listener for an X.509-SVID client and a JWT-SVID client and check client_id, scope, audience and act.sub. They also cover scope and audience rejection from the association's policy, the may_act consent check, delegate clients that present a stray certificate, and a SPIFFE-only server with no upstream. There is no kind e2e in this PR.

API Compatibility

The CRD changes are description-only: five type comments, regenerated into the CRD YAML, crd-api.md, swagger and the SDK. No schema, validation rule or default changed. The new reconcile-time checks apply only to SPIFFE configs, which could not start before this PR.

  • This PR does not break the v1beta1 API, OR the api-break-allowed label is applied and the migration guidance is described above.

Changes

Most of the diff is tests, generated CRD and SDK output, and docs. Code changes, by area:

Area Files
Routing and X.509 verification pkg/authserver/server/spiffe_client_auth.go, server/provider.go, spiffe/certificate.go, server/client_assertion_errors.go
Middleware removed spiffe/middleware.go, spiffe/context.go, runner/tls_listener.go
Validation pkg/authserver/config.go, spiffe_trust.go, runner/embeddedauthserver.go, pkg/vmcp/config/validator.go, operator mcpexternalauthconfig_types.go and virtualmcpserver_controller.go
Placeholder replace and bundle reload storage/types.go, storage/spiffe_decorator.go, spiffe_bundle_source.go
Wiring and ID-JAG exclusion server_impl.go, spiffe_association_registry.go, spiffe_preflight.go

Does this introduce a user-facing change?

Before:

  • A config with spiffeTrustDomains was rejected with "SPIFFE client authentication is not yet enforced by this build".
  • A MCPExternalAuthConfig with a bundle_endpoint or workload_api source reported valid, and the workload that used it failed at reconcile.

After:

  • A config with a file bundle source starts and enforces JWT-SVID and X.509-SVID client authentication.
  • A request whose client_id names a spiffe_x509 association authenticates with its client certificate only, at every client-authenticating endpoint on the 8443 listener (token and device authorization). A failure returns invalid_client (401), an ambiguous client_id returns invalid_request (400), and there is no fallback. Every other client ignores a presented certificate. A chain of more than four certificates is rejected.
  • The listener sends a CertificateRequest when any association enables spiffe_x509. No SPIFFE config could start before, so this is new behaviour in practice.
  • spiffe_x509 needs a tlsListener and an https issuer. An http issuer fails at validation, and the operator reports it as a condition.
  • bundle_endpoint and workload_api are rejected at validation: MCPExternalAuthConfig shows Valid=False and a VirtualMCPServer shows a failed spec.authServerConfig condition. The CRD schema still accepts them.
  • A server with no upstream, delegate client or trusted issuer is accepted when it has a SPIFFE association, and runs token-only. The zero-upstream error text now mentions SPIFFE client associations.
  • A SPIFFE client_id equal to a delegate client_id is rejected at validation.
  • SPIFFE association clients cannot redeem an ID-JAG. They get unauthorized_client.
  • Editing a SPIFFE association replaces its placeholder and logs configured client replaced with a different policy, with old_resources, new_resources or identity_changed when those changed. During a rolling update each replica serves its own configuration, and nothing marks when the rollout ends.
  • New WARN lines for a rejected bundle sequence, a failed bundle reload, and a stale bundle.
  • Breaking for Go embedders: spiffeauth.Middleware, ContextWithSPIFFEID and SPIFFEIDFromContext are removed. Nothing in this repo used them. NewAuthorizationServer now returns an error when SPIFFEClientResolver and SPIFFEX509BundleSource are set without the new SPIFFEX509ClientMatcher. Both fields have been in releases since v0.48.0 and the X.509 bundle source was documented as "not yet read", so a hand-built AuthorizationServerParams that sets them now needs the matcher too.
  • Added for embedders: SPIFFEIDFromCertificate, and the SPIFFEX509ClientMatcher field on AuthorizationServerParams and AuthorizationServerConfig. Embedders of authserver.New must terminate TLS and request client certificates themselves, and TLS must reach them end to end. A proxy or gateway that opens its own TLS connection is authenticated as itself, so association principal patterns must not match proxy or gateway identities.

Special notes for reviewers

  • Size and how to review it. 61 files, +3658 / -1327. Code is 22 files (+730 / -332), tests 23 files (+2683 / -790), docs 5 files, generated 11 files. It is one PR on purpose: removing the startup gate, excluding SPIFFE clients from the ID-JAG grant and the X.509 path only make sense together. Four passes work well: routing and X.509 verification (spiffe_client_auth.go), validation (config.go, spiffe_trust.go, the operator types), the placeholder and bundle-reload changes, and the docs.
  • The CRD schema is wider than what runs. The schema keeps accepting bundle_endpoint and workload_api so the API can be relaxed later without a schema change. Reconcile-time Go checks reject them until a loader exists. Until then the bundle_endpoint URL check is unreachable through MCPExternalAuthConfig admission.
  • Placeholder replace. Replacing instead of refusing means old and new replicas disagree briefly during a rollout, and two auth servers sharing one Redis keyspace by mistake now both start with a WARN. A placeholder and a non-placeholder client still never replace each other.
  • Chain cap. Measured on one machine with same-key RSA-8192 intermediates, each extra intermediate costs about 0.7 ms, so a chain at the cap costs about 2 ms and a legitimate chain about 0.2 ms.
  • Kind e2e. There is no kind e2e here. A SPIRE e2e is written later in this stack and needs the client_credentials grant from a later branch.
  • Not changed here:
    • X.509-SVIDs have no lifetime cap, where JWT-SVIDs are capped at 6 minutes.
    • Issued tokens are not bound to the certificate.
    • A JWT-SVID is accepted over a plaintext port and has no jti check.
    • A bundle emptied of authorities cannot revoke trust before the 24 hour cutoff, and re-reading an unchanged file counts as a fresh load, so staleness does not detect a publisher that stopped updating.
    • A SPIFFE-only server has no source for its first subject token unless another issuer shares its signing key.
    • inboundGrants: {tokenExchange: {}} passes CRD admission and fails at runtime.
    • A removed association's placeholder row is never cleaned up.
    • A mistyped bundle ConfigMap name or key shows up only as pod events.

@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 9, 2026
@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.56631% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.03%. Comparing base (d702679) to head (ccf41b8).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/spiffe_bundle_source.go 94.87% 2 Missing ⚠️
pkg/authserver/server_impl.go 90.00% 1 Missing ⚠️
pkg/authserver/spiffe_trust.go 90.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7092      +/-   ##
==========================================
+ Coverage   80.93%   81.03%   +0.10%     
==========================================
  Files         867      869       +2     
  Lines       88888    89081     +193     
==========================================
+ Hits        71939    72189     +250     
+ Misses      16944    16887      -57     
  Partials        5        5              

☔ 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.

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The X.509 design is right, but there are rollout and compatibility gaps, and CI is red. Leaving comments rather than approving.

Design: Checking the X.509-SVID inside the fosite client-authentication strategy is the right place for it. That strategy owns client auth for every endpoint that authenticates clients (token and device authorization), reads only r.TLS, and re-checks the chain against the live bundle on every request. Moving X.509 and JWT-SVID onto one resolver means an association gives the same answer whichever credential is used. Removing the startup gate is what turns this on in production, which makes several pre-existing SPIFFE gaps reachable for the first time. Most of the findings below come from that.

  1. pkg/authserver/server/spiffe_client_auth.go:77, :97 (with runner/tls_listener.go:86): any SPIFFE certificate takes over client auth on 8443. Once one association enables spiffe_x509, the listener asks every client for a certificate. Any leaf that has a spiffe:// URI SAN is then forced into the X.509 path. In SPIRE or Istio-style meshes, workloads usually present their SVID on every outbound TLS connection.

    • A JWT-SVID client whose association enables only spiffe_jwt gets invalid_client.
    • A delegate client using client_secret_post or private_key_jwt gets invalid_client from the mixed-credential check.
    • A delegate client using HTTP Basic gets invalid_request at :135.

    All of these worked on the same listener before the X.509 association was added. Suggested fix: use the X.509 path only when the request has no other client credential, or only when the leaf resolves to an association that enables spiffe_x509. Otherwise treat the certificate as transport identity only. If rejecting is the intended design, state it as a breaking constraint and add a test for it.

  2. docs/arch/18-spiffe-association-declarations.md:111 / pkg/authserver/storage/redis.go:877: editing an association stalls the rollout on Redis. With Redis storage, a policy-only edit to an association conflicts with the placeholder already stored, so NewSPIFFEStorageDecorator fails and new pods never become ready. Policy-only means scopes, audiences, resources or methods. Scenario: an operator narrows a SPIFFE client's scopes. The rollout hangs and the old pods keep serving the wider policy. The doc in this PR now says this "applies today" with no supported way out. Suggested fix: let policy-only edits update the placeholder so only a change of identity conflicts, or reject SPIFFE with Redis in validation until that works.

  3. SPIFFE-only configs pass the operator but fail at pod start. Take an MCPExternalAuthConfig or VirtualMCPServer with only spiffeTrustDomains and inboundGrants.spiffeClientAuth, and no upstreams, delegate clients or jwt-bearer issuer.

    • It passes the CRD rule (mcpexternalauthconfig_types.go:927 lists spiffeClientAuth), validateEmbeddedAuthServer, and the VirtualMCPServer reconcile check.
    • It is then rejected at runtime by validateZeroUpstreamMode (pkg/authserver/config.go:2349), which doesn't count SPIFFE associations.

    This gap was hidden while every SPIFFE config failed at startup. Suggested fix: count SPIFFE associations in validateZeroUpstreamMode, or reject this config at reconcile time.

  4. The path that actually gets enabled is not tested end to end. runner/spiffe_x509_listener_test.go:142-146 only shows a 400 caused by the missing subject_token. No test completes a token exchange through newServer with an X.509-SVID or a JWT-SVID. JWT-SVID is tested only in package server with a stubbed resolver. That leaves untested the may_act consent check, the scope and audience limits from registration.NewSPIFFEClient, the real file bundle, the registry and storage. Suggested fix: add runner-level tests that issue a real token for each SVID type, assert its client_id, scopes and audience, and cover one rejection caused by the association's policy.

  5. CI lint is red. The only non-test failure is gocyclo on (*RunConfig).Validate (pkg/authserver/config.go:507), pushed over the limit by the new loop at :558-564. Moving that loop into a validateRuntimeSPIFFEBundleSources() helper fixes it and matches the shape of the Config version at :1973. The other failures are in tests: exhaustive and unused wantOK, missing t.Helper(), deprecated ecdsa.PublicKey.X/Y, gci, and unparam.

  6. The PR body is missing user-facing changes and a test plan.

    • It deletes exported pkg/authserver/spiffe symbols (Middleware, ContextWithSPIFFEID, SPIFFEIDFromContext), which breaks embedders.
    • SPIFFE clients can no longer redeem ID-JAGs.
    • bundle_endpoint and workload_api are now rejected at reconcile.

    None of these are mentioned. No Test-plan box is checked. The PR also covers three logical changes across 13 non-test files: the X.509 path, the bundle-source gate, and the ID-JAG exclusion. Please list the breaking changes, and either split the PR or confirm that one PR is intended.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek force-pushed the spiffe-v2-07-x509-client-auth branch from a96d69d to 28aca47 Compare November 10, 2026 20:48
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 10, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-review of 28aca47: all six earlier findings are resolved. One new security finding is a docs and threat-model fix, and one breaking change is missing from the PR body.

  1. Any SPIFFE certificate taking over client auth on 8443: resolved. The X.509 path now runs only when a form client_id names an association that enables spiffe_x509 (checked by usesX509). Every other client uses the default strategy and ignores a presented certificate, and there are runner tests for delegates using HTTP Basic and client_secret_post.

  2. Redis rollout stalling on a policy-only edit: resolved. Two placeholders can now replace each other and a WARN is logged. A placeholder and a non-placeholder still never replace each other.

  3. SPIFFE-only configs failing at pod start: resolved. Both zero-upstream validators now count SPIFFE associations, and there is a runner test with no upstream.

  4. No end-to-end test of the enabled path: resolved. TestEmbeddedAuthServer_SPIFFETokenExchangeOverTLS issues tokens through the real TLS listener for an X.509-SVID and a JWT-SVID. It also covers the policy and may_act rejections.

  5. CI lint red: resolved.

  6. PR body missing breaking changes and test plan: resolved, except for the gap in 8 below.

  7. docs/arch/18-spiffe-association-declarations.md:21, pkg/authserver/server/spiffe_client_auth.go:189-212: a proxy that re-encrypts traffic to 8443 becomes a confused deputy, and the docs say the opposite.

    • What's wrong: the client identity is whichever peer completed the TLS handshake. The doc says a mesh or Ingress in front of the listener "cannot supply a client identity". That holds for forwarded headers, but a gateway that re-originates TLS presents its own SVID.
    • Scenario: an association client_id=X matches spiffe://td/ns/prod/*. A Gateway API or Envoy gateway in ns/prod re-originates TLS to the 8443 Service with its own SVID. The new appProtocol: https on that port invites gateways to do exactly that. An external caller then sends client_id=X with no credential of its own, the gateway's SVID verifies, and the caller authenticates as X.
    • Fix: say in the doc and in the New godoc that 8443 must receive TLS end to end from the workload. Any hop that re-originates TLS is authenticated as itself, so association patterns must not match proxy or gateway identities. Consider dropping appProtocol: https, or document that it must not be paired with a backend TLS policy.
  8. pkg/authserver/server/provider.go:622-631: a breaking change for direct callers is not listed. validateSPIFFEX509Wiring makes NewAuthorizationServer fail when SPIFFEClientResolver and SPIFFEX509BundleSource are set without the new SPIFFEX509ClientMatcher. An embedder that builds AuthorizationServerParams itself gets that error after upgrade, and the bundle source was previously documented as "not yet read". Add this to the breaking-changes list next to the removed spiffe symbols.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek force-pushed the spiffe-v2-07-x509-client-auth branch 2 times, most recently from bbfd2fb to 325dfc8 Compare November 10, 2026 22:39
@jhrozek

jhrozek commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review. On 7 and 8:

  1. Agreed. The doc line you quoted only held for headers, so I fixed it. The X.509 section now says TLS has to reach 8443 end to end from the workload, that a hop which opens its own TLS connection is authenticated as itself, and that principal patterns must not match proxy or gateway identities (exact SPIFFE IDs or per-service-account paths, not a namespace wildcard). The godoc on authserver.New says the same. The doc also says what limits the damage: token exchange still needs a subject token that passes the delegation consent check, but the protection against a stolen subject token is gone in that setup.

On appProtocol: https: it comes from the operator ports change that already merged, not from this PR. I checked what gateways do with it. On its own it does not make a gateway present a client certificate. Gateway API only starts TLS to a backend when a BackendTLSPolicy applies, and GKE Gateway is the one implementation I found that starts TLS because of the field, but it presents no certificate unless you configure one. The exposed setups need an extra setting that gives the hop an SVID, for example Istio ISTIO_MUTUAL with SPIRE-issued certificates, or a backend client certificate Secret that holds an SVID. So I'm keeping the field. The doc already says not to pair it with a setting that makes a gateway re-originate TLS to this port.

  1. Fair point. It is now its own "Breaking for Go embedders" bullet in the PR body, next to the removed symbols, with the detail that both fields have been in releases since v0.48.0 and the X.509 bundle source was documented as "not yet read".

I also rebased onto main after the clock skew change landed. The only conflict was where the SPIFFE strategy is installed in provider.go, and I kept the clock skew wrapper as the default strategy.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 10, 2026
rdimitrov
rdimitrov previously approved these changes Nov 10, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-review of 325dfc8: approve. Both open findings are resolved, and the rebase conflict resolution is correct.

  1. Confused deputy via a TLS-terminating hop to 8443: resolved. The arch doc and the New godoc now say TLS must reach the listener end to end, that a hop opening its own TLS is authenticated as itself, and that principal patterns must not match gateway identities. Keeping appProtocol: https is fine: it predates this PR and is now documented with the right warning.
  2. validateSPIFFEX509Wiring breaking change not listed: resolved. The PR body lists the SPIFFEX509ClientMatcher requirement under "Breaking for Go embedders".

The rebase merge in pkg/authserver/server/provider.go keeps main's #7088 chain unchanged on the non-SPIFFE path (guard, error mapping, clock-skew wrapper, fosite). Both SPIFFE arms return before the clock-skew layer, so SVID clients get no extra leniency, and delegate private_key_jwt clients that present a stray certificate still reach the skew wrapper.

🤖 Reviewed with Claude Code

Clients on the auth-server TLS listener can now authenticate with an
X.509-SVID, the same way they can with a JWT-SVID. The certificate
identity was previously extracted by middleware and never verified, so
the server could not safely accept it.

The client-authentication strategy now reads the peer certificate
directly and verifies it against the live trust bundle on every request.
It picks the verifier from the requested client, not from the
certificate. A SPIFFE JWT assertion selects the JWT arm and the
certificate is ignored. Otherwise the X.509 arm runs only when a
client_id names an association that enables spiffe_x509, and it fails
closed without a valid certificate. Any other request uses the default
strategy, where a presented certificate is transport identity only, so
JWT-SVID, delegate and public clients that merely present an SVID keep
working on the same listener. Both arms share one resolver, so an
association gives the same outcome whichever credential a workload
presents. A presented chain is capped at four certificates before
verification, which bounds the work a client can force per request.

Only the file bundle source has a loader, so bundle_endpoint and
workload_api are rejected at every validation point, including the
operator's config resource. The "not yet enforced" startup gate is
removed. Validation now also rejects an http issuer when an association
enables spiffe_x509, a SPIFFE client_id that equals a delegate
client_id, and SPIFFE associations with token exchange disabled. It
accepts SPIFFE-only configs, with no upstream, delegate client or
trusted issuer, in the auth server and vMCP validators. The unused
exported helpers Middleware, ContextWithSPIFFEID and SPIFFEIDFromContext
are removed.

SPIFFE association clients are token-exchange only, so they are excluded
from the ID-JAG jwt-bearer grant. A changed association now replaces its
stored placeholder and logs a WARN instead of failing startup, so an
edit rolls out on Redis. A rejected bundle sequence number and a stale
bundle are logged once at WARN, so a bundle rollback no longer fails
silently after 24 hours.

Part of #6202.

Co-authored-by: Mecatl <[email protected]>
@jhrozek
jhrozek force-pushed the spiffe-v2-07-x509-client-auth branch from 325dfc8 to ccf41b8 Compare November 11, 2026 08:49
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 11, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-review of ccf41b8: still approve. The push only rebases the approved commit onto current main.

The production code is unchanged from 325dfc8. The rebase changed only tests and comments, to fit main's #7104 (the auth server no longer closes storage the caller passed in) and #7096 (the DCR store is now found by type assertion):

  • The SPIFFE tests now close their own storage.
  • The authserver.New godoc merges main's wording with this PR's.

Neither main change undoes anything the approval relied on:

  • DCR store lookup: it runs on the unwrapped storage before the SPIFFE decorator wraps it.
  • Close: server.Close still releases the bundle source, and owned storage is still closed exactly once on error paths.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek merged commit 9d6328e into main Nov 11, 2026
48 checks passed
@jhrozek
jhrozek deleted the spiffe-v2-07-x509-client-auth branch November 11, 2026 11:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants