Repository navigation
feat(authbridge): mTLS between proxy-sidecar listeners via SPIRE X.509 SVIDs - #424
Conversation
…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]>
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
left a comment
There was a problem hiding this comment.
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):
- The
fixup(authbridge/mtls)commit should be squashed into the first before merge to keep branch history clean. - Consider a brief doc comment on
FileX509Sourceinauthlib/spiffe/x509source.gonoting 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?"
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 inauthbridge-runtimeturns it on. Schema borrows Istio'sPeerAuthentication.mtls.modevocabulary so operators familiar with Istio map their mental model 1:1.:8080)mtlsblock)permissiveAuthorizationheaders in the clear.mode=permissivefor grep-friendly rollout monitoring).strictA successful TLS handshake that fails certificate verification is always a hard error in both modes.
Why
spiffe-helperalready writes/opt/svid.pem,/opt/svid_key.pem,/opt/svid_bundle.pemon every authbridge pod withSPIRE_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 useauthlib/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-proxyandcmd/authbridge-litewire mTLS up;cmd/authbridge-envoystays 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
permissivemode falls back to plain TCP on TLS handshake failure (withmode=permissive-tagged WARN log naming the destination);strictmode fails the request.permissivemode's byte-peek serves them plaintext on:8080;strictmode closes the connection.Operators rolling out: start in
permissive, watch the fallback WARN logs (grepmode=permissive), address them, then promote tostrict. TheMTLSConfig.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 ./...fromauthbridge/authlibgo build ./...from each ofcmd/authbridge-{proxy,envoy,lite},cmd/abctlgo vet ./...clean across authlibgo test -race -count=1 ./...green across authlib + abctlgofmt -lclean on all changed filesgo/disabled-certificate-checksuppressed via.github/codeql/codeql-config.ymlwith documented justificationauthbridge/demos/mtls/Makefiledeploys caller + callee withmtls.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 X509Sourceauthlib/tls/server.go+client.go+spiffe.go+metrics.go(~280 LOC total) + tests (~370 LOC) — TLS config builders, peer-SPIFFE extraction, atomic metricsauthlib/listener/internal/tlssniff/listener.go(~165 LOC) + tests (~270 LOC) — byte-peek listenercmd/abctl/tui/detail_pane_test.go— locks the new TLS render pathdemos/mtls/— caller + callee pods, Makefile, three verify scripts.github/codeql/codeql-config.yml— project-level CodeQL config with documentedgo/disabled-certificate-checkexclusionModified
authlib/config/config.go—MTLSConfig+ Validate + ResolvedMode + cert-path defaults +CheckPathsReadable()for startup typo detectionauthlib/pipeline/context.go—TLS *tls.ConnectionState+PeerCertificate()accessorauthlib/pipeline/session.go—SessionEvent.TLS *EventTLS+ wire round-trip +NewEventTLShelperauthlib/listener/reverseproxy/server.go—MTLSOptions+Listen()method +pctx.TLSpopulation +SessionEvent.TLSon all 3 event sitesauthlib/listener/forwardproxy/server.go—MTLSOptions+ customDialContextwith try-TLS-fall-back / strict semantics; fallback WARN tagged withmode=permissivecmd/authbridge-proxy/main.go+cmd/authbridge-lite/main.go— wireMTLSConfigfrom top-level config, emit early-warning WARN on missing pathscmd/abctl/tui/detail_pane.go— render TLS section in events detail paneCLAUDE.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 fileNewServercallers in reverse/forward proxy tests gain anilmtls argumentOut of scope (deferred to later phases)
/stats);mtls.min_versionknob; asymmetric inbound/outbound modes; expected-trust-domain pinning (per-caller trust-domain match) for clusters federating multiple SPIRE servers.mtls.enabled.Review feedback addressed (commit
07a4438)go/disabled-certificate-checksuppressed via project-level config + inline lgtm annotationmode=permissivefor grep-friendly rollout monitoringRejectsExpiredClient+PeerSPIFFEID_RejectsMultiURI(untrusted-CA was already covered byRejectsUntrustedClient)MTLSConfig.CheckPathsReadable()+ WARN-not-error startup loggingAssisted-By: Claude (Anthropic AI) [email protected]