Skip to content

Modular token exchange library: shared core for AuthBridge, Klaviger, and Waypoint #279

Closed

Description

@huang195

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) *AuthDecision

Request 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 7662

Uses 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-SVID

Includes 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.Match

pkg/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.AuthorizationServer

Translates 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.ExternalProcessorServer

Handles 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.Handler

Receives 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.Handler

Receives 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")  // inbound

Repo 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

  1. Phase 1: Extract pkg/tokenexchange from current cmd/token-exchange-service/main.go. Build cmd/waypoint that imports it. Verify existing 4 E2E tests pass.

  2. Phase 2: Add pkg/adapter/extproc and build cmd/authbridge. Test against AuthBridge's E2E tests.

  3. Phase 3: Add pkg/adapter/reverseproxy and build cmd/klaviger. Test against Klaviger's E2E tests.

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

  1. make test — existing 4 E2E tests pass with refactored cmd/waypoint
  2. Unit tests for each pkg/tokenexchange/* package
  3. Integration test: same engine instance used by ext_authz and httpproxy produces identical decisions

Activity

  1. maia-iyer commented on Apr 8, 2026

    @maia-iyer
    Contributor

    Thanks for writing this up, @huang195! This is a really great idea. Couple comments at first glance:

    • the pkg/tokenexchange is a surprising name because it encapsulates all the core logic including other features like token validation or identity obtaining
    • I want to question the inclusion and use of each of the cmd components - IMO those components can live separately and be consumers of the library - otherwise we'll be responsible for building many container images for this library
  2. akram commented on Apr 8, 2026

    @akram
    Contributor

    @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:

    │     pkg/auth/  or pkg/authentication/ or pkg/iam/   │
    │                                                     │
    │  core/             - evaluateAuth(), authDecision   │
    │  identity/         - agent identity resolution      │
    │  token/validation/ - JWKS cache, JWT validation     │
    │  token/exchange/   - RFC 8693 client, token cache   │
    │  bypass/           - path matching                  │
    

    Also:

    This repo becomes the single home for all token exchange code. Each approach is a cmd/ binary:

    authbridge-waypoint/
    

    I am not sure to understand this naming for this repo. Would the authentication library repo named authbridge-waypoint ?

  3. huang195 commented on Apr 9, 2026

    @huang195
    MemberAuthor

    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.

    Mode Interception Inbound Outbound Deployment
    envoy-sidecar Envoy iptables + ext-proc Validate via ext-proc (inbound direction) Exchange via ext-proc (outbound direction) Sidecar per agent pod
    waypoint Istio ambient + ext-authz Validate via ext-authz Exchange via ext-authz + HTTP forward proxy Shared service in kagenti-system
    proxy-sidecar Reverse proxy + forward proxy Validate via reverse proxy Exchange via forward proxy Sidecar per agent pod

    Note: 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.

    Setting (locked by mode) envoy-sidecar waypoint proxy-sidecar
    Listener(s) ext-proc ext-authz + forward-proxy reverse-proxy + forward-proxy
    Audience source identity.client_id serviceNameFromHost(host) identity.client_id
    No-token outbound client-credentials bypass reject
    Routing style per-host routes hostname-derived per-host routes
    Setting (user can override) envoy-sidecar default waypoint default proxy-sidecar default
    Identity type spiffe client-secret spiffe
    Bypass paths standard set standard set standard set
    Outbound routes exchange all auto from hostname exchange all
    Listener addresses :8081 :9090 + :8080 :8080 + :8081

    Startup validation rejects invalid combinations (e.g., waypoint + ext-proc listener) and warns on unusual ones (e.g., envoy-sidecar + client-secret identity).

    Architecture

    ┌─────────────────────────────────────────────────────┐
    │                    authbridge                        │
    │                                                      │
    │  ┌─────────────┐   Selected by --mode:              │
    │  │  Listener    │   • ext-proc  (envoy-sidecar)     │
    │  │  (~50 lines  │   • ext-authz (waypoint)          │
    │  │   each)      │   • http proxy (proxy-sidecar)    │
    │  └──────┬───────┘                                   │
    │         │  translates protocol → (authHeader,       │
    │         │  host, path, audience)                    │
    │         ▼                                            │
    │  ┌─────────────────────────────────────────────┐    │
    │  │              auth/                           │    │
    │  │  HandleInbound(ctx, authHeader, path, aud)   │    │
    │  │  HandleOutbound(ctx, authHeader, host)       │    │
    │  └──────┬──────────────┬───────────────┬───────┘    │
    │         │              │               │             │
    │  ┌──────┴──┐    ┌──────┴──┐    ┌───────┴──┐        │
    │  │ authlib/ │    │ authlib/ │    │ authlib/ │        │
    │  │validate  │    │exchange  │    │ routing  │        │
    │  └─────────┘    └─────────┘    └──────────┘        │
    └─────────────────────────────────────────────────────┘
    
    • Listeners are thin protocol translators (~50 lines each). They convert ext-proc streams, ext-authz CheckRequests, or HTTP requests into (authHeader, host, path, audience) and call the auth layer.
    • auth/ composes authlib/ building blocks into HandleInbound and HandleOutbound. This is the only application logic (~150 lines). It can evolve to a middleware pipeline later (for guardrails, rate limiting) without changing authlib/ or listeners.
    • authlib/ contains pure, reusable building blocks. No application logic, no mode awareness.

    Repo layout

    kagenti-extensions/
    ├── AuthBridge/
    │   ├── authlib/                       # Shared building blocks
    │   │   ├── validation/                # JWKS verifier (lestrrat-go/jwx)
    │   │   │   ├── verifier.go           # Verifier interface + Claims
    │   │   │   ├── jwks.go               # JWKS-based implementation
    │   │   │   └── jwks_test.go
    │   │   ├── exchange/                  # RFC 8693 token exchange
    │   │   │   ├── client.go             # Exchange client
    │   │   │   ├── auth.go               # ClientAuth: secret, JWT assertion, bearer
    │   │   │   └── client_test.go
    │   │   ├── cache/                     # Token cache
    │   │   │   ├── cache.go              # SHA-256 keyed, TTL, eviction
    │   │   │   └── cache_test.go
    │   │   ├── bypass/                    # Path matcher
    │   │   │   ├── bypass.go
    │   │   │   └── bypass_test.go
    │   │   ├── spiffe/                    # SPIFFE credential sources
    │   │   │   ├── jwt_source.go         # JWT-SVID via Workload API
    │   │   │   ├── x509_source.go        # X.509-SVID for mTLS
    │   │   │   └── jwt_source_test.go
    │   │   └── routing/                   # Unified host → audience router
    │   │       ├── router.go
    │   │       └── router_test.go
    │   │
    │   ├── auth/                          # Auth pipeline (composes authlib/)
    │   │   └── auth.go                    # HandleInbound + HandleOutbound
    │   │
    │   ├── listener/                      # Protocol adapters (thin)
    │   │   ├── extproc/                   # Envoy ext-proc streaming
    │   │   ├── extauthz/                  # Envoy ext-authz unary gRPC
    │   │   ├── forwardproxy/              # HTTP forward proxy
    │   │   └── reverseproxy/              # HTTP reverse proxy
    │   │
    │   ├── config/                        # Mode presets + validation
    │   │   ├── presets.go                 # Mode → locked settings
    │   │   ├── config.go                  # YAML loading + env var expansion
    │   │   └── validate.go               # Reject invalid combinations
    │   │
    │   ├── cmd/authbridge/                # Single binary
    │   │   └── main.go                    # --mode → resolve preset → start listeners
    │   │
    │   ├── AuthProxy/                     # existing (removed after migration)
    │   ├── client-registration/           # existing
    │   ├── k8s/                           # existing
    │   └── demos/                         # existing
    │
    ├── kagenti-webhook/                   # existing
    ├── charts/
    ├── docs/
    └── go.mod
    

    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:

    type Verifier interface {
        Verify(ctx context.Context, tokenStr string, audience string) (*Claims, error)
    }
    
    type Claims struct {
        Subject   string
        Issuer    string
        Audience  []string
        ClientID  string         // "azp" claim
        Scopes    []string
        ExpiresAt time.Time
        Extra     map[string]any
    }
    
    func (c *Claims) HasAudience(aud string) bool
    func (c *Claims) HasScope(scope string) bool

    Each listener passes the appropriate audience:

    • envoy-sidecar / proxy-sidecar: identity.client_id (fixed per agent)
    • waypoint: serviceNameFromHost(host) (derived per-request from destination)

    Package: authlib/exchange/

    RFC 8693 token exchange with pluggable client authentication:

    type ClientAuth interface {
        Apply(ctx context.Context, form url.Values, headers http.Header) error
    }
    
    func NewClientSecretAuth(clientID, clientSecret string) ClientAuth
    func NewJWTAssertionAuth(tokenSource func(ctx context.Context) (string, error), assertionType string) ClientAuth
    func NewBearerAuth(tokenSource func(ctx context.Context) (string, error)) ClientAuth
    
    func (c *Client) Exchange(ctx context.Context, req *ExchangeRequest) (*ExchangeResponse, error)

    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:

    func New(opts ...Option) *Cache
    func (c *Cache) Get(subjectToken, audience string) (string, bool)
    func (c *Cache) Set(subjectToken, audience, token string, ttl time.Duration)

    Package: authlib/bypass/

    Path matching with query strip and path.Clean:

    func NewMatcher(patterns []string) *Matcher
    func (m *Matcher) Match(path string) bool

    Package: authlib/spiffe/

    Unified SPIFFE credential management. JWT-SVID for client auth during token exchange, X.509-SVID for mTLS:

    func NewJWTSource(ctx context.Context, socketPath string, audience []string) (*JWTSource, error)
    func (s *JWTSource) FetchJWTSVID(ctx context.Context, audience []string) (string, error)
    
    func NewX509Source(ctx context.Context, socketPath string) (*X509Source, error)
    func (s *X509Source) GetClientTLSConfig() (*tls.Config, error)

    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:

    type Router struct { ... }
    func NewRouter(defaultAction string, rules []Route) *Router
    func (r *Router) Resolve(host string) *ResolvedRoute
    Old routing model Unified equivalent
    Waypoint serviceNameFromHost(host) default_action: exchange with no rules, audience auto-derived
    Sidecar routes.yaml Explicit rules: with per-host audience + action
    Proxy hostRules Explicit rules: with per-host action

    The auth layer

    // auth/auth.go — composes authlib/ building blocks
    type Auth struct { ... }
    
    func New(cfg ResolvedConfig) (*Auth, error)
    func (a *Auth) HandleInbound(ctx context.Context, authHeader, path, audience string) *InboundResult
    func (a *Auth) HandleOutbound(ctx context.Context, authHeader, host string) *OutboundResult

    HandleInbound: bypass check → validate JWT with audience → allow/deny

    HandleOutbound: 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:

    mode: envoy-sidecar
    inbound:
      jwks_url: "${JWKS_URL}"
      issuer: "${ISSUER}"
    outbound:
      token_url: "${TOKEN_URL}"
    identity:
      socket_path: "unix:///run/spire/sockets/agent.sock"
      jwt_audience: ["keycloak"]
      client_id: "my-agent"

    waypoint — simplest config:

    mode: waypoint
    inbound:
      jwks_url: "${JWKS_URL}"
      issuer: "${ISSUER}"
    outbound:
      token_url: "${TOKEN_URL}"
    identity:
      type: client-secret
      client_id: "token-exchange-service"
      client_secret: "${CLIENT_SECRET}"

    proxy-sidecar:

    mode: proxy-sidecar
    listener:
      reverse_proxy_backend: "http://localhost:8081"
    inbound:
      jwks_url: "${JWKS_URL}"
      issuer: "${ISSUER}"
    outbound:
      token_url: "${TOKEN_URL}"
    identity:
      socket_path: "unix:///run/spire/sockets/agent.sock"
      jwt_audience: ["keycloak"]
      client_id: "my-agent"

    What existing code replaces

    Existing Action
    go-processor JWT validation, exchange, bypass, JWKS cache, config Deleted → authlib/
    go-processor Process() ext-proc streaming Copied to listener/extproc/ (~50 lines)
    go-processor resolver/ Moved to authlib/routing/
    waypoint evaluateAuth, validateJWT, parseRSAPublicKey, caches Deleted → authlib/
    waypoint Check(), handleProxy() Copied to listener/extauthz/ and listener/forwardproxy/
    Klaviger internal/auth/, tokeninjector/oauth_exchange, util/token_cache, internal/spiffe/ Deleted → authlib/
    Klaviger internal/forwardproxy/, internal/reverseproxy/ Copied to listener/ (~50 lines each)
    Klaviger Vault/file injectors Kept as proxy-sidecar internal for now, future authlib/ migration
    Klaviger internal/observability/ Kept as internal for now

    Migration plan

    Phase What Days
    1 authlib/ — 6 packages (validation, exchange, cache, bypass, spiffe, routing) + unit tests 5-7
    2 auth/ + config/ — auth layer + mode presets + startup validation 2-3
    3 listener/ + cmd/authbridge/ — four listeners + single binary 3-5
    4 Migrate existing tests, Dockerfile, CI 2-3
    Total ~12-18 days

    Future evolution

    The architecture supports future capabilities without restructuring:

    • Guardrails / rate limiting: auth/ evolves from two functions to a middleware pipeline. authlib/ and listeners unchanged.
    • Observability: Add OTel tracing + Prometheus metrics in auth/ (the choke point all requests flow through).
    • New listener types: Add listener/grpc-interceptor/ or similar — calls same auth.HandleInbound/HandleOutbound.
    • Vault / file token injection: Migrate from proxy-sidecar internal to authlib/injection/ when the abstraction is clear.

    Consolidated decision record

    Decision Rationale Round
    Three modes: envoy-sidecar, waypoint, proxy-sidecar Every mode validates inbound + exchanges outbound. Proxy-shared dropped — no inbound validation R5
    Mode = preset (locks listeners, routing, defaults) Prevents invalid config combinations; users configure what, not how R5
    Single binary with --mode flag One codebase, shared core, three deployment strategies R2
    authlib/ = pure building blocks Stable, reusable, no application logic, no mode awareness R4
    auth/ = application composition HandleInbound + HandleOutbound; evolves to middleware later R4
    Audience required parameter to Verify() Prevents confused deputy attacks — listener provides audience per mode R3
    Unified routing (host patterns → audience/action) All three routing models are same abstraction with different defaults R3
    Unified JWT via lestrrat-go/jwx Replaces 3 divergent implementations R1
    SPIFFE in authlib from Phase 1 All modes benefit; replaces file-based SVID with Workload API R4
    SHA-256 cache keys Fixes Klaviger's collision-prone first-16-chars R1
    No identity fallback chains Fail-closed; explicit config, no auto-detection R2
    No middleware pipeline yet Ship auth first; auth/ is the seam point for future evolution R4
    Startup validation rejects invalid combos Fail fast with clear error, not at request time R5
    Typed exchange errors with OAuth fields Modes need HTTP status + error_description for diagnostics R3
  4. maia-iyer commented on Apr 10, 2026

    @maia-iyer
    Contributor

    @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

  5. huang195 commented on Apr 10, 2026

    @huang195
    MemberAuthor

    @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:

    # Same config schema regardless of mode
    identity:
      type: spiffe | k8s-sa | client-secret

    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:

    # Future: Vault as token source for specific hosts
    routes:
      rules:
        - host: "vault-protected-api.*"
          token_source: vault
          vault:
            address: "https://vault:8200"
            path: "secret/data/api-token"
            field: "token"

    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.

  6. added 20 commits that reference this issue on Apr 14, 2026
  7. huang195 commented on May 22, 2026

    @huang195
    MemberAuthor

    this is pretty much done. we have a modular authlib + plugin pipeline. closing

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions