Repository navigation
Description
Plan: Modular Token Exchange Library
Context
We have three approaches to token exchange (AuthBridge, Klaviger, Waypoint) that all implement the same core logic independently — JWT validation, RFC 8693 exchange, token caching, bypass paths. The code analysis (docs/code-analysis.md) shows 80%+ overlap across all three codebases. This refactor extracts the shared logic into a Go library that all three approaches import, with thin adapter layers for each interface and interception mechanism.
Architecture
┌─────────────────────────────────────────────────┐
│ pkg/tokenexchange │
│ │
│ core/ - evaluateAuth(), authDecision │
│ jwt/ - JWKS cache, JWT validation │
│ exchange/ - RFC 8693 client, token cache │
│ bypass/ - path matching │
│ identity/ - agent identity resolution │
│ │
├─────────────────────────────────────────────────┤
│ pkg/adapter │
│ │
│ extauthz/ - Envoy ext_authz gRPC v3 │
│ extproc/ - Envoy ext_proc gRPC v3 │
│ httpproxy/ - HTTP forward proxy │
│ reverseproxy/ - HTTP reverse proxy │
│ │
├─────────────────────────────────────────────────┤
│ cmd/ │
│ │
│ waypoint/ - ext_authz │
│ authbridge/ - ext_proc │
│ klaviger/ - httpproxy + reverseproxy │
│ │
└─────────────────────────────────────────────────┘
Package Design
pkg/tokenexchange/core
The single decision function, shared by all adapters:
type AuthDecision struct {
Action Action // Allow, AllowWithToken, Deny
Token string // exchanged token (if AllowWithToken)
DenyReason string
DenyCode int
}
type Config struct {
// JWT validation
JWKSProvider jwt.Provider
IssuerURL string
// Token exchange
ExchangeClient exchange.Client
// Bypass
BypassPaths []string
// Agent identity (optional)
IdentityResolver identity.Resolver
}
type Engine struct { ... }
func NewEngine(cfg Config) *Engine
func (e *Engine) Evaluate(ctx context.Context, req *Request) *AuthDecisionRequest is adapter-neutral:
type Request struct {
AuthHeader string // Authorization header value
Host string // destination hostname
Path string // request path
SourceIP string // caller IP (for agent identity in proxy mode)
SourcePrincipal string // SPIFFE ID (for agent identity in waypoint mode)
}pkg/tokenexchange/jwt
JWKS fetching and JWT validation. Abstracts the differences:
type Provider interface {
Validate(ctx context.Context, tokenStr string) (*Claims, error)
}
type Claims struct {
Subject string
Issuer string
Audience []string
ClientID string // azp
Scopes []string
ExpiresAt time.Time
Extra map[string]any
}
// Implementations:
func NewKeycloakProvider(jwksURL, issuerURL string) Provider // JWKS + issuer check
func NewK8sProvider(apiServer string) Provider // TokenReview API
func NewIntrospectionProvider(endpoint string) Provider // RFC 7662Uses lestrrat-go/jwx (already used by AuthBridge and Klaviger) instead of manual RSA parsing. Supports RSA + EC keys.
pkg/tokenexchange/exchange
RFC 8693 token exchange client:
type Client interface {
Exchange(ctx context.Context, req *ExchangeRequest) (*ExchangeResponse, error)
}
type ExchangeRequest struct {
SubjectToken string
Audience string
Scope string // optional
ActorToken string // optional (RFC 8693 delegation)
}
type ExchangeResponse struct {
AccessToken string
ExpiresIn int
TokenType string
}
type ClientAuth interface {
Apply(form url.Values, headers http.Header)
}
// Client auth implementations:
func NewClientSecretAuth(clientID, clientSecret string) ClientAuth
func NewJWTBearerAuth(tokenSource func() (string, error)) ClientAuth // K8s SA token
func NewSPIFFEAuth(socketPath string, audience []string) ClientAuth // SPIFFE JWT-SVIDIncludes token cache (SHA-256 keys, TTL, periodic eviction).
pkg/tokenexchange/bypass
Path matching (identical in Waypoint and AuthBridge, hardcoded in Klaviger):
func NewMatcher(patterns []string) *Matcher
func (m *Matcher) Match(path string) bool // strips query, path.Clean, path.Matchpkg/tokenexchange/identity
Agent identity resolution for the shared service model:
type Resolver interface {
Resolve(ctx context.Context, req *Request) (string, error) // returns agent identity string
}
func NewSPIFFEResolver() Resolver // from ext_authz source principal
func NewSourceIPResolver(k8sClient) Resolver // source IP → pod → service account
func NewStaticResolver(identity string) Resolver // for sidecar (always the pod's identity)pkg/adapter/extauthz
Envoy ext_authz gRPC v3 adapter (for waypoint mode):
func NewServer(engine *core.Engine) auth.AuthorizationServerTranslates CheckRequest → core.Request, calls engine.Evaluate(), translates AuthDecision → CheckResponse.
pkg/adapter/extproc
Envoy ext_proc gRPC v3 adapter (for AuthBridge sidecar mode):
func NewServer(engine *core.Engine, cfg ExtProcConfig) ext_proc.ExternalProcessorServerHandles bidirectional streaming. Detects direction from x-authbridge-direction header. Inbound → validate. Outbound → exchange.
pkg/adapter/httpproxy
HTTP forward proxy adapter (for shared proxy and Klaviger outbound):
func NewHandler(engine *core.Engine) http.HandlerReceives proxied HTTP requests, calls engine.Evaluate(), replaces Authorization header, forwards to destination.
pkg/adapter/reverseproxy
HTTP reverse proxy adapter (for Klaviger inbound and potential shared proxy inbound):
func NewHandler(engine *core.Engine, backend string) http.HandlerReceives inbound requests, calls engine.Evaluate() for validation, forwards to backend on localhost.
What each binary assembles
cmd/waypoint (current token-exchange-service)
engine := core.NewEngine(core.Config{
JWKSProvider: jwt.NewKeycloakProvider(jwksURL, issuerURL),
ExchangeClient: exchange.NewClient(tokenURL, exchange.NewClientSecretAuth(clientID, clientSecret)),
BypassPaths: defaultBypassPaths,
IdentityResolver: identity.NewSPIFFEResolver(),
})
extauthz.Serve(engine, ":9090")cmd/authbridge (go-processor replacement)
engine := core.NewEngine(core.Config{
JWKSProvider: jwt.NewKeycloakProvider(jwksURL, issuerURL),
ExchangeClient: exchange.NewClient(tokenURL, exchange.NewSPIFFEAuth(socketPath, audience)),
BypassPaths: bypassPaths,
IdentityResolver: identity.NewStaticResolver(agentID),
})
extproc.Serve(engine, ":8081")cmd/klaviger (klaviger replacement)
engine := core.NewEngine(core.Config{
JWKSProvider: jwt.NewKeycloakProvider(jwksURL, issuerURL),
ExchangeClient: exchange.NewClient(tokenURL, exchange.NewJWTBearerAuth(k8sTokenSource)),
BypassPaths: bypassPaths,
IdentityResolver: identity.NewStaticResolver(agentID),
})
// Two listeners, same engine
go httpproxy.Serve(engine, ":8081") // outbound
go reverseproxy.Serve(engine, backend, ":8080") // inboundRepo structure
This repo becomes the single home for all token exchange code. Each approach is a cmd/ binary:
authbridge-waypoint/
├── pkg/
│ ├── tokenexchange/ # shared library (core, jwt, exchange, bypass, identity)
│ └── adapter/ # interface adapters (extauthz, extproc, httpproxy, reverseproxy)
├── cmd/
│ ├── waypoint/ # ext_authz (replaces current cmd/token-exchange-service)
│ ├── authbridge/ # ext_proc (replaces kagenti-extensions go-processor)
│ └── klaviger/ # httpproxy + reverseproxy (replaces grs/klaviger token exchange)
├── deploy/ # existing deploy scripts and YAMLs
└── docs/ # analysis, comparison, research
AuthBridge and Klaviger repos would import the binaries from here rather than maintaining their own token exchange implementations. The webhook/operator in kagenti-extensions continues to handle sidecar injection and Keycloak client registration — this repo only owns the token exchange runtime.
Migration strategy
-
Phase 1: Extract
pkg/tokenexchangefrom currentcmd/token-exchange-service/main.go. Buildcmd/waypointthat imports it. Verify existing 4 E2E tests pass. -
Phase 2: Add
pkg/adapter/extprocand buildcmd/authbridge. Test against AuthBridge's E2E tests. -
Phase 3: Add
pkg/adapter/reverseproxyand buildcmd/klaviger. Test against Klaviger's E2E tests. -
Phase 4: Propose to kagenti-extensions and Klaviger repos to use binaries from this repo instead of their own implementations.
Files
| Path | Description |
|---|---|
pkg/tokenexchange/core/engine.go |
Core evaluation logic |
pkg/tokenexchange/jwt/provider.go |
JWKS + JWT validation interface + implementations |
pkg/tokenexchange/exchange/client.go |
RFC 8693 client + token cache |
pkg/tokenexchange/exchange/auth.go |
Client authentication methods |
pkg/tokenexchange/bypass/matcher.go |
Bypass path matching |
pkg/tokenexchange/identity/resolver.go |
Agent identity resolution |
pkg/adapter/extauthz/server.go |
ext_authz gRPC adapter |
pkg/adapter/extproc/server.go |
ext_proc gRPC adapter |
pkg/adapter/httpproxy/handler.go |
HTTP forward proxy adapter |
pkg/adapter/reverseproxy/handler.go |
HTTP reverse proxy adapter |
cmd/waypoint/main.go |
Waypoint binary (ext_authz) |
cmd/authbridge/main.go |
AuthBridge binary (ext_proc) |
cmd/klaviger/main.go |
Klaviger binary (httpproxy + reverseproxy) |
Verification
make test— existing 4 E2E tests pass with refactoredcmd/waypoint- Unit tests for each
pkg/tokenexchange/*package - Integration test: same
engineinstance used by ext_authz and httpproxy produces identical decisions
Activity
maia-iyer commentedon Apr 8, 2026
Thanks for writing this up, @huang195! This is a really great idea. Couple comments at first glance:
pkg/tokenexchangeis a surprising name because it encapsulates all the core logic including other features like token validation or identity obtainingcmdcomponents - IMO those components can live separately and be consumers of the library - otherwise we'll be responsible for building many container images for this libraryakram commentedon Apr 8, 2026
@huang195 really great proposal and detailed issue. I think that this really captures and encompasses very widely the cases and implementations that we already have.
I second the comment of @maia-iyer regarding the naming: should we keep the first level's package's name more generic instead? And the separate by each covered domain:
Also:
I am not sure to understand this naming for this repo. Would the authentication library repo named
authbridge-waypoint?huang195 commentedon Apr 9, 2026
Revised Design: AuthBridge — Single Binary, Three Modes, Shared
authlib/After two adversarial design reviews (8 total rounds) grounded in code review of all three implementations — Waypoint, AuthBridge go-processor, and Klaviger — here is the consolidated design.
Core insight
AuthBridge, Waypoint, and Klaviger are the same product — an auth proxy that validates inbound JWTs and exchanges outbound tokens via RFC 8693. They differ only in the interception mechanism. This design unifies them into a single binary with three modes and a shared auth library.
Three modes
Every mode provides both inbound validation and outbound exchange. No half-solutions.
envoy-sidecarwaypointproxy-sidecarNote: a "proxy-shared" mode was considered and rejected — a shared forward proxy has no mechanism for inbound token validation (requests reach agents directly, bypassing the proxy).
Mode = preset
Mode locks in valid configuration. Users configure what (credentials, endpoints) but not how (listeners, routing strategy, fallback behavior). Invalid combinations are impossible.
identity.client_idserviceNameFromHost(host)identity.client_idStartup validation rejects invalid combinations (e.g., waypoint + ext-proc listener) and warns on unusual ones (e.g., envoy-sidecar + client-secret identity).
Architecture
(authHeader, host, path, audience)and call the auth layer.auth/composesauthlib/building blocks intoHandleInboundandHandleOutbound. This is the only application logic (~150 lines). It can evolve to a middleware pipeline later (for guardrails, rate limiting) without changingauthlib/or listeners.authlib/contains pure, reusable building blocks. No application logic, no mode awareness.Repo layout
Package:
authlib/validation/Unifies three divergent JWT implementations into one, built on
lestrrat-go/jwx. Replaces waypoint-mode's manual RSA key parsing (RSA-only, no EC support) and custom-proxy-mode's mixed two-library approach.Audience is a required parameter to
Verify()— prevents confused deputy attacks:Each listener passes the appropriate audience:
identity.client_id(fixed per agent)serviceNameFromHost(host)(derived per-request from destination)Package:
authlib/exchange/RFC 8693 token exchange with pluggable client authentication:
Returns typed errors with HTTP status + OAuth error/error_description fields.
Package:
authlib/cache/SHA-256 keyed token cache. Fixes Klaviger's collision-prone first-16-chars approach:
Package:
authlib/bypass/Path matching with query strip and
path.Clean:Package:
authlib/spiffe/Unified SPIFFE credential management. JWT-SVID for client auth during token exchange, X.509-SVID for mTLS:
Replaces envoy-mode's file-based SVID reading (spiffe-helper dependency) with Workload API.
Package:
authlib/routing/Unified host-to-audience routing. All three routing models are the same with different defaults:
serviceNameFromHost(host)default_action: exchangewith no rules, audience auto-derivedroutes.yamlrules:with per-host audience + actionhostRulesrules:with per-host actionThe auth layer
HandleInbound: bypass check → validate JWT with audience → allow/denyHandleOutbound: resolve route → cache check → exchange token → cache result → allow/deny/replace~150 lines total. All listeners call these two functions.
User-facing config per mode
envoy-sidecar— most config injected by webhook:waypoint— simplest config:proxy-sidecar:What existing code replaces
Process()ext-proc streaminglistener/extproc/(~50 lines)resolver/authlib/routing/evaluateAuth,validateJWT,parseRSAPublicKey, cachesCheck(),handleProxy()listener/extauthz/andlistener/forwardproxy/internal/auth/,tokeninjector/oauth_exchange,util/token_cache,internal/spiffe/internal/forwardproxy/,internal/reverseproxy/listener/(~50 lines each)internal/observability/Migration plan
authlib/— 6 packages (validation, exchange, cache, bypass, spiffe, routing) + unit testsauth/+config/— auth layer + mode presets + startup validationlistener/+cmd/authbridge/— four listeners + single binaryFuture evolution
The architecture supports future capabilities without restructuring:
auth/evolves from two functions to a middleware pipeline.authlib/and listeners unchanged.auth/(the choke point all requests flow through).listener/grpc-interceptor/or similar — calls sameauth.HandleInbound/HandleOutbound.authlib/injection/when the abstraction is clear.Consolidated decision record
--modeflagauthlib/= pure building blocksauth/= application compositionVerify()lestrrat-go/jwxauth/is the seam point for future evolutionmaia-iyer commentedon Apr 10, 2026
@huang195 I like the introduction of a pluggable pipeline. I'm curious how that will get configured for different platform configurations (say I want to use vault instead of token exchange when that gets implemented? or say I want to use k8s sas for workload identity instead of spiffe?)? would this be from an environment variable interface? would that config look different for each of the different "execution modes"? I'd say from the oauth/spiffe angles it looks good to e
huang195 commentedon Apr 10, 2026
@maia-iyer great questions. The design handles both of these.
Identity (SPIFFE vs K8s SA vs client-secret) is a config field, not hard-wired to mode:
Mode sets the default (envoy-sidecar → spiffe, waypoint → client-secret, proxy-sidecar → spiffe), but the user can override freely. Someone running envoy-sidecar without SPIRE just sets
identity.type: client-secret. Startup validation warns on unusual-but-valid combos and rejects invalid ones.Vault as a token source (future phase) would fit as either an additional identity type or a route-level token source — the unified routing config already has a per-host rules structure that can carry this:
This extends naturally from the existing route rules without changing the pipeline or adding a new execution mode.
Config format: YAML with
${ENV_VAR}expansion (same pattern Klaviger already uses). The config schema is identical regardless of mode — mode only controls which listeners start. No mode-specific config dialects. A waypoint deployment and an envoy-sidecar deployment share the same config structure for identity, routing, inbound validation, and outbound exchange.✨ Add authlib/ — shared token exchange building blocks (Phase 1)
✨ Add authlib/ — shared token exchange building blocks (Phase 1)
✨ Add auth/ and config/ — composition layer and mode presets (Phase 2)
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
✨ Add authlib/ — shared token exchange building blocks (Phase 1)
✨ Add auth/ and config/ — composition layer and mode presets (Phase 2)
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
✨ Add authlib/ — shared token exchange building blocks (Phase 1)
✨ Add auth/ and config/ — composition layer and mode presets (Phase 2)
✨ Add listeners and single binary — four modes, one codebase (Phase 3)
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
ci: Add CI/build for unified authbridge, deprecate old components (Ph…
huang195 commentedon May 22, 2026
this is pretty much done. we have a modular authlib + plugin pipeline. closing