Skip to content

feat(authbridge): mTLS between proxy-sidecar listeners via SPIRE X.509 SVIDs - #424

Merged
huang195 merged 3 commits into
rossoctl:mainfrom
huang195:feat/mtls-svid
May 20, 2026
Merged

huang195 merged 3 commits into
rossoctl:mainfrom
huang195:feat/mtls-svid

Conversation

@huang195

@huang195 huang195 commented May 20, 2026 •

Copy link
Copy Markdown
Member

Summary

mTLS between authbridge-enabled endpoints (agent ↔ agent, agent ↔ tool with authbridge) using SPIRE X.509 SVIDs. Closes the wire-encryption gap that existed when running without Istio ambient mesh.

A top-level mtls: block in authbridge-runtime turns it on. Schema borrows Istio's PeerAuthentication.mtls.mode vocabulary so operators familiar with Istio map their mental model 1:1.

mtls:
  mode: strict          # permissive (default) | strict
  # cert_file / key_file / bundle_file optional —
  # default to spiffe-helper paths /opt/svid*.pem
Mode Inbound (reverse proxy :8080) Outbound (forward proxy)
(no mtls block) Plaintext only. Today's behavior. Plaintext only.
permissive Byte-peek listener: TLS handshakes verified against the SPIRE trust bundle; plaintext callers (UI, curl, healthchecks) served on the same port. ⚠️ Plaintext requests carry their Authorization headers in the clear. Try TLS first; on handshake failure fall back to plain TCP (WARN log with mode=permissive for grep-friendly rollout monitoring).
strict TLS only — non-TLS first byte → connection closed. TLS or fail: handshake failure is a hard error, no fallback.

A successful TLS handshake that fails certificate verification is always a hard error in both modes.

Why

spiffe-helper already writes /opt/svid.pem, /opt/svid_key.pem, /opt/svid_bundle.pem on every authbridge pod with SPIRE_ENABLED=true. They've been written and ignored. This PR makes authbridge consume them.

Without Istio ambient, the wire between authbridge sidecars carries plaintext HTTP — including any Bearer tokens injected by token-exchange. With this PR, when both endpoints have mTLS enabled, the wire is encrypted and peer-authenticated via the SPIRE trust domain.

Architecture

mTLS is a transport-layer concern; the plugin pipeline is unaware. Two small additive surfaces let plugins opt into connection-level identity:

  • pctx.TLS *tls.ConnectionState — populated when the inbound connection went through TLS. pctx.PeerCertificate() returns the verified leaf cert. Plugins that want per-caller policy use authlib/tls.PeerSPIFFEID() to extract the URI SAN.
  • SessionEvent.TLS *EventTLS — version + cipher + peer SPIFFE ID per event. abctl renders it in the events detail pane.

Plugin contract is unchanged. Only cmd/authbridge-proxy and cmd/authbridge-lite wire mTLS up; cmd/authbridge-envoy stays untouched (Envoy handles its own TLS via SDS).

mTLS config changes require a pod restart, matching the existing listener.* config-reload boundary.

Trust model

Any peer with a valid cert from the SPIRE trust bundle can talk to this authbridge. No SPIFFE-ID allowlist, no per-caller policy — the trust bundle IS the policy. Per-caller decisions are a plugin concern (read pctx.PeerCertificate()).

Mixed deployments

  • Caller has authbridge with mTLS, callee doesn't speak TLS (legacy tool, ollama, internal service): permissive mode falls back to plain TCP on TLS handshake failure (with mode=permissive-tagged WARN log naming the destination); strict mode fails the request.
  • Callee has mTLS, caller doesn't speak TLS (UI, curl, healthchecks): permissive mode's byte-peek serves them plaintext on :8080; strict mode closes the connection.

Operators rolling out: start in permissive, watch the fallback WARN logs (grep mode=permissive), address them, then promote to strict. The MTLSConfig.CheckPathsReadable() startup check emits a clear WARN if cert paths are misconfigured (typo, wrong volume mount) without breaking cold-start before spiffe-helper has written.

Test plan

  • go build ./... from authbridge/authlib
  • go build ./... from each of cmd/authbridge-{proxy,envoy,lite}, cmd/abctl
  • go vet ./... clean across authlib
  • go test -race -count=1 ./... green across authlib + abctl
  • gofmt -l clean on all changed files
  • CodeQL go/disabled-certificate-check suppressed via .github/codeql/codeql-config.yml with documented justification
  • CI passes
  • Manual: authbridge/demos/mtls/Makefile deploys caller + callee with mtls.mode: strict, runs a request, asserts no TLS-fallback WARN was logged. Permissive + strict-rejects-plain variants also covered.

Files

New

  • authlib/spiffe/x509source.go (~150 LOC) + tests (~250 LOC) — file-based X509Source
  • authlib/tls/server.go + client.go + spiffe.go + metrics.go (~280 LOC total) + tests (~370 LOC) — TLS config builders, peer-SPIFFE extraction, atomic metrics
  • authlib/listener/internal/tlssniff/listener.go (~165 LOC) + tests (~270 LOC) — byte-peek listener
  • cmd/abctl/tui/detail_pane_test.go — locks the new TLS render path
  • demos/mtls/ — caller + callee pods, Makefile, three verify scripts
  • .github/codeql/codeql-config.yml — project-level CodeQL config with documented go/disabled-certificate-check exclusion

Modified

  • authlib/config/config.go — MTLSConfig + Validate + ResolvedMode + cert-path defaults + CheckPathsReadable() for startup typo detection
  • authlib/pipeline/context.go — TLS *tls.ConnectionState + PeerCertificate() accessor
  • authlib/pipeline/session.go — SessionEvent.TLS *EventTLS + wire round-trip + NewEventTLS helper
  • authlib/listener/reverseproxy/server.go — MTLSOptions + Listen() method + pctx.TLS population + SessionEvent.TLS on all 3 event sites
  • authlib/listener/forwardproxy/server.go — MTLSOptions + custom DialContext with try-TLS-fall-back / strict semantics; fallback WARN tagged with mode=permissive
  • cmd/authbridge-proxy/main.go + cmd/authbridge-lite/main.go — wire MTLSConfig from top-level config, emit early-warning WARN on missing paths
  • cmd/abctl/tui/detail_pane.go — render TLS section in events detail pane
  • CLAUDE.md + docs/framework-architecture.md — schema doc, shared-volume contract, framework integration §8a, plaintext-Authorization caveat
  • .github/workflows/security-scans.yaml — CodeQL action loads the new config file
  • Test files: existing NewServer callers in reverse/forward proxy tests gain a nil mtls argument

Out of scope (deferred to later phases)

  • Phase 2: observability surface for the metrics counters (currently constructed but not yet rendered through /stats); mtls.min_version knob; asymmetric inbound/outbound modes; expected-trust-domain pinning (per-caller trust-domain match) for clusters federating multiple SPIRE servers.
  • Phase 3: kagenti-operator webhook integration so SPIRE-enabled workloads auto-pick-up mtls.enabled.
  • Phase 4: kind + tcpdump CI verification job.
  • Phase 5: ambient detection / auto-disable.
  • Cut from Phase 1 after design review: per-route TLS policy, SPIFFE-ID allowlists, expected-SPIFFE-ID pinning. The trust bundle is the policy in v1.

Review feedback addressed (commit 07a4438)

# Severity Resolution
1 must-fix CodeQL go/disabled-certificate-check suppressed via project-level config + inline lgtm annotation
2 suggestion Plaintext-Authorization warning added to permissive-mode row in CLAUDE.md
3 suggestion Fallback WARN now includes mode=permissive for grep-friendly rollout monitoring
4 suggestion New tests: RejectsExpiredClient + PeerSPIFFEID_RejectsMultiURI (untrusted-CA was already covered by RejectsUntrustedClient)
5 suggestion MTLSConfig.CheckPathsReadable() + WARN-not-error startup logging
6 nit Comment in tlssniff dispatch about buffered-byte handling on peek timeout
7 observation Trust-domain pinning explicitly listed under Phase 2 deferred items above
8 observation No action needed — proxy-vs-lite symmetry confirmed

Assisted-By: Claude (Anthropic AI) [email protected]

…9 SVIDs

When the kagenti cluster runs without Istio ambient mesh, agent-to-
agent and agent-to-tool traffic between authbridge sidecars is
plaintext. spiffe-helper already writes /opt/svid.pem,
/opt/svid_key.pem, /opt/svid_bundle.pem on every authbridge pod with
SPIRE_ENABLED=true; this PR makes authbridge consume them.

A top-level mtls block in authbridge-runtime turns it on. The schema
borrows Istio's PeerAuthentication.mtls.mode vocabulary so operators
familiar with Istio map their mental model 1:1.

  mtls:
    mode: strict          # permissive (default when block present) | strict
    # cert_file / key_file / bundle_file optional —
    # default to spiffe-helper paths

Mode semantics:
  - (no mtls block) — today's plaintext behavior, both directions.
  - permissive — inbound byte-peek listener accepts both TLS and
    plaintext on :8080; outbound tries TLS first, falls back to
    plain TCP on handshake failure (one-line WARN log).
  - strict — inbound rejects non-TLS callers; outbound returns a
    hard error on TLS handshake failure (no fallback).

Trust model: any peer cert that validates against the SPIRE trust
bundle is accepted. No SPIFFE-ID allowlist, no per-caller policy in
v1 — the trust bundle IS the policy. Plugins that want per-caller
decisions read pctx.PeerCertificate() and check the URI SAN via
authtls.PeerSPIFFEID().

Architectural notes:
  - mTLS is a transport-layer concern; the plugin pipeline is unaware.
    Plugin contract (Plugin / Capabilities / Configurable / etc) is
    completely unchanged.
  - Two small additive surfaces let plugins opt into connection-level
    identity: pctx.TLS *tls.ConnectionState (with PeerCertificate()
    accessor) and SessionEvent.TLS *EventTLS (version + cipher + peer
    SPIFFE ID for the observability surface).
  - Only proxy-sidecar binaries (authbridge-proxy, authbridge-lite)
    wire mTLS. authbridge-envoy stays untouched — Envoy handles its
    own TLS via SDS independently.
  - mTLS config requires a pod restart (matches the existing
    listener.* config-reload boundary).

Implementation:
  - new authlib/spiffe/ — file-based X509Source with cert+key+bundle
    rotation handled via re-read on every TLS handshake. No go-spiffe
    dependency; <40 LOC of crypto/x509 stdlib code.
  - new authlib/tls/ — ServerConfig + ClientConfig builders, atomic
    metrics counters, PeerSPIFFEID URI-SAN extraction.
  - new authlib/listener/internal/tlssniff/ — byte-peek listener that
    routes 0x16 first byte to tls.Server and other to plain conn.
    Mode-aware (permissive passes plain through, strict closes the
    connection). 5s peek deadline so slow clients don't hold
    goroutines.
  - reverseproxy.NewServer accepts *MTLSOptions; new Listen() method
    returns the byte-peek listener when mTLS is on.
  - forwardproxy.NewServer accepts *MTLSOptions; custom DialContext
    does try-TLS-fall-back-to-plain (permissive) or TLS-or-fail
    (strict). Successful handshake with verification failure is
    always a hard error.
  - abctl detail-pane renders a TLS section with version + cipher +
    peer SPIFFE ID when SessionEvent.TLS is non-nil.

Counters surface through the existing /stats endpoint (Phase 2 will
expose them via the JSON output): inbound/outbound TLS accepted,
TLS failed, fell-back, plain accepted, plain rejected. Critical for
permissive rollouts so operators can tell when fallbacks have
reached zero and they're safe to promote to strict.

Demo: authbridge/demos/mtls/ has caller + callee pods both running
with mtls.mode: strict, plus verify scripts confirming the wire is
encrypted, that permissive serves both, and that strict actually
rejects plaintext.

Verified: go build ./... (all four cmd binaries), go vet ./...,
go test -race -count=1 ./authlib/... (all packages green); gofmt
clean on changed files.

Out of scope (deferred to later phases):
  - Per-route TLS policy / SPIFFE allowlists (cut after design review).
  - Operator-side webhook integration (kagenti-operator repo).
  - kind+tcpdump CI verification job.
  - Ambient detection / auto-disable.
  - Asymmetric inbound/outbound modes.
  - mtls.min_version knob.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Comment thread authbridge/authlib/tls/client.go Fixed
1. CodeQL go/disabled-certificate-check (must-fix). The
   InsecureSkipVerify: true in authlib/tls/client.go is the canonical
   stdlib idiom for plugging in a custom verifier — the
   VerifyPeerCertificate callback runs verifyPeerChain, which checks
   the chain against the rotation-aware trust bundle on every
   handshake. CodeQL can't follow the callback, so it sees a
   half-disabled config. Suppressed via:
   - new .github/codeql/codeql-config.yml that excludes the rule
     project-wide (with a justification comment that future readers
     can evaluate)
   - workflow updated to load the config-file
   - inline lgtm[...] annotation kept as in-source documentation

2. CLAUDE.md: added a one-line caveat to the permissive-mode row
   warning that plaintext callers carry their full headers in the
   clear, including any Authorization: Bearer ... token already
   injected by token-exchange. Loud during rollout.

3. forwardproxy fallback WARN now includes mode=permissive, so
   operators grepping aggregated logs across mixed-mode sidecars can
   correlate "this destination fell back" with "this caller is
   permissive" while watching fallbacks decay to zero.

4. Three new tests:
   - TestServerConfig_RejectsExpiredClient locks expiry checking so a
     future verifyPeerChain refactor can't drop it silently.
   - TestPeerSPIFFEID_RejectsMultiURI confirms PeerSPIFFEID returns ""
     on non-conformant certs with two SPIFFE URIs (defends against an
     attacker attaching a second URI for spoofing).
   - The existing TestServerConfig_RejectsUntrustedClient already
     covers the untrusted-CA case.

5. config.MTLSConfig.CheckPathsReadable() stats cert/key/bundle paths
   at startup; cmd binaries log a WARN (not error) when paths are
   missing. Demotion-not-failure preserves cold-start behavior — the
   X509Source's per-handshake re-read still handles the legitimate
   "spiffe-helper hasn't written yet" pattern. The WARN catches typos
   that otherwise wouldn't surface until first traffic.

6. Comment in tlssniff dispatch around the peek-timeout error path
   explaining buffered-byte handling: bufio.Reader holds no bytes
   when Peek failed, and even if it did they'd be GC'd. Helps future
   readers reason about resource accounting.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The 90s timeout on WaitForCredentialFile was tight for cluster
bootstrap scenarios. Sources of slowness:

- Fresh cluster: SPIRE controller-manager renders the workload
  entry, agent attests, server issues SVID — ~30-60s on a cold
  cluster, sometimes more.
- SPIRE agent crash + restart: agent re-bootstraps from scratch.
- Slow nodes (CI runners, kind on a constrained host).
- Many workloads racing for SPIRE entries simultaneously.

After 90s the pod fatals → kubelet restart-backoff (10s, 20s, 40s
... up to 5min) → eventually the next attempt succeeds when SPIRE
catches up. So nothing is lost, but operators see CrashLoopBackOff
which looks like a hard failure rather than "still waiting on
SPIRE."

Drop the timeout. Wait indefinitely with the existing 60s
heartbeat, let the kubelet readiness probe surface "not ready
yet." Same shape jwt-validation and token-exchange use for their
credential files — Init goroutines poll forever, OnRequest returns
503 until ready. mTLS can't use that exact pattern (the listener
itself can't bind without the cert) so we block startup, but the
visibility is the same: pod stays 1/2 Ready until SVIDs land, k8s
holds traffic accordingly.

Verified: full mtls demo passes end-to-end with unbounded wait
after operator PR rossoctl#367 lands the spire-agent-socket mount fix.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>

@pdettori pdettori 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.

Well-engineered mTLS implementation with strong test coverage (~1,400 lines of tests), proper security patterns (InsecureSkipVerify paired with custom VerifyPeerCertificate, CodeQL suppression documented), and thoughtful operational design (permissive→strict rollout path with observable metrics). The third commit's decision to remove the SVID startup timeout in favor of indefinite wait with heartbeat logging is well-justified — aligns with existing credential-wait patterns and lets kubelet readiness probes surface the state.

Areas reviewed: Go, Shell, YAML, CI/GitHub Actions, Security, Docs, Demo manifests
Commits: 3 commits, all signed-off ✓
CI status: All passing (17/17 green, spellcheck skipping)


Nits (non-blocking):

  1. The fixup(authbridge/mtls) commit should be squashed into the first before merge to keep branch history clean.
  2. Consider a brief doc comment on FileX509Source in authlib/spiffe/x509source.go noting the intentional per-handshake re-read design (no caching). The inline rationale further down is good but easy to miss for a dev scanning for "why isn't this cached?"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants