config

package
v0.0.0-...-4ef879c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package config provides YAML-based configuration with mode presets and startup validation for the AuthBridge auth layer.

Package config's resolve.go previously constructed a shared auth.Config + auth.Auth for all plugins to share. With per-plugin configuration, that responsibility moved into each plugin's Configure (see authbridge/docs/plugin-reference.md), and this file is now just the shared credential-file waiters that multiple plugins need when they share a file path (e.g. /shared/client-id.txt used by both jwt-validation's audience_file and token-exchange's client_id_file).

Index

Constants

View Source
const (
	RoleReverse = "reverse" // inbound reverse proxy
	RoleForward = "forward" // outbound forward proxy
)

Proxy roles selectable via ListenerConfig.Roles in proxy-sidecar mode.

View Source
const (
	InboundInterceptionReverseProxy = "reverse-proxy" // fixed backend (default)
	InboundInterceptionTransparent  = "transparent"   // SO_ORIGINAL_DST per connection
)

Valid ListenerConfig.InboundInterception values. Interception is two independent axes (inbound, outbound), so the inbound mechanism is a field on the reverse role rather than a role of its own — matching the outbound transparent listener, which likewise rides inside the forward role instead of being separately selectable.

View Source
const (
	ModeEnvoySidecar = "envoy-sidecar"
	ModeProxySidecar = "proxy-sidecar"
)

Valid mode strings.

Variables

This section is empty.

Functions

func ApplyPreset

func ApplyPreset(cfg *Config)

ApplyPreset fills in mode-specific defaults for listener addresses. Plugin-specific defaults live inside each plugin's Configure (see authbridge/docs/plugin-reference.md); the runtime config no longer shapes plugin behavior.

func ReadCredentialFile

func ReadCredentialFile(path string) (string, error)

ReadCredentialFile performs a one-shot read of a credential file, returning its whitespace-trimmed contents. Used by plugins from Configure to opportunistically pick up values the operator has already mounted from a Secret; when it returns an error, the plugin should fall back to WaitForCredentialFile from Init to wait for the file.

func Validate

func Validate(cfg *Config) error

Validate checks the top-level runtime config: mode and listener combo. Plugin-specific validation (issuer, token URL, identity type, jwt_audience) lives inside each plugin's Configure and runs at pipeline build time.

Empty pipelines are permitted: AuthBridge will run as a pass-through on any stage with no plugins. This supports testing scenarios and asymmetric deployments (e.g. inbound auth only, no outbound token exchange). Operators get a startup WARN per empty stage from WarnEmptyPipelines so the open-proxy condition is visible in logs.

func WaitForCredentialFile

func WaitForCredentialFile(ctx context.Context, path string) (string, error)

WaitForCredentialFile blocks until the file is readable with non-zero length, or until ctx is cancelled. Plugins call this from Init (via a goroutine) to wait out the race with the operator's Secret-mount propagation.

Polls at 2s intervals — fast enough for human-observable boot times, slow enough that a pod full of plugins isn't hammering the kubelet. Emits a WARN every heartbeatInterval while the file is still absent so operators can spot wrong paths / missing volume mounts in `kubectl logs` during an incident, rather than discovering them after chasing silent 503s from traffic.

func WarnEmptyPipelines

func WarnEmptyPipelines(cfg *Config, logger *slog.Logger)

WarnEmptyPipelines emits a startup WARN for every pipeline stage that has no plugins. An empty stage is a supported configuration (pass-through), not an error, but it means traffic on that direction flows without authentication, JWT validation, or token exchange. Surfacing this once at startup makes the open-proxy condition visible in logs without blocking deployments that intentionally run without plugins (e.g. testing, asymmetric deployments).

Call this from each cmd entry point AFTER Validate succeeds and BEFORE the pipelines are built. Pass slog.Default() unless you need a scoped logger.

Types

type Config

type Config struct {
	Mode     string         `yaml:"mode" json:"mode"` // "envoy-sidecar", "proxy-sidecar"
	Listener ListenerConfig `yaml:"listener" json:"listener"`
	Pipeline PipelineConfig `yaml:"pipeline" json:"pipeline"`
	Session  SessionConfig  `yaml:"session" json:"session"`
	Stats    StatsConfig    `yaml:"stats" json:"stats"`
	// MTLS, when non-nil, enables transport-level mTLS using SPIRE
	// X.509 SVIDs. Applies symmetrically to inbound (reverse-proxy)
	// and outbound (forward-proxy) traffic in proxy-sidecar mode;
	// envoy-sidecar mode is unaffected (Envoy handles its own TLS via
	// SDS). Pointer so absent block = today's plaintext behavior.
	MTLS *MTLSConfig `yaml:"mtls,omitempty" json:"mtls,omitempty"`
	// SPIFFE, when non-nil, configures the in-process Provider that
	// supplies X.509-SVIDs to the mTLS listeners and a JWT-SVID to the
	// token-exchange plugin (when configured). Pointer so absent block
	// = today's spiffe-helper-driven behavior (until the chart/operator
	// follow-ups land and start populating the block).
	SPIFFE *SPIFFEConfig `yaml:"spiffe,omitempty" json:"spiffe,omitempty"`
	// TLSBridge, when non-nil and Enabled, terminates agent outbound TLS so the
	// outbound pipeline sees decrypted HTTPS. See docs/.../tlsbridge-design.md.
	TLSBridge *TLSBridgeConfig `yaml:"tls_bridge,omitempty" json:"tls_bridge,omitempty"`
	// Pricing configures model rates for the whole process — one section rather
	// than a knob per plugin, so cost is consistent wherever it is reported.
	//
	// Absent means the bundled price table alone, which is deliberate: covering
	// internal usage with no manual setup is the point. Set `pricing.bundled:
	// false` to price only what you configure. See authlib/pricing.
	Pricing *pricing.Config `yaml:"pricing,omitempty" json:"pricing,omitempty"`
	// CostLedger configures the durable per-minute cost ledger (authlib/costledger),
	// which persists closed minutes so "what did today cost" survives a restart.
	//
	// Absent means the caller's default, and the callers differ deliberately: a local
	// install turns it ON (a laptop has a home directory and a developer who wants
	// yesterday's number), Kubernetes leaves it OFF (writing files in a pod is the
	// wrong sink; a central collector is the right one). Set `cost_ledger.enabled:
	// false` to turn it off locally.
	CostLedger *CostLedgerConfig `yaml:"cost_ledger,omitempty" json:"cost_ledger,omitempty"`
}

Config is the top-level AuthBridge configuration.

Plugin-specific settings (inbound JWT validation, outbound token exchange, identity, bypass paths, routes) live inside their respective entries under Pipeline.* now — see the plugin reference at authbridge/docs/plugin-reference.md for how each plugin declares its own config schema and defaults.

func Load

func Load(path string) (*Config, error)

Load reads and parses a YAML config file with environment variable expansion. Defined env vars are expanded; undefined references like ${UNDEFINED} are left as-is to avoid silent empty-string substitution.

type CostLedgerConfig

type CostLedgerConfig struct {
	// Enabled is a POINTER so "unset" and "explicitly false" are different states.
	// The local default is on, and an operator has to be able to turn it off; with a
	// plain bool an absent block and `enabled: false` would be the same value, so the
	// only way to disable it would be to delete the whole block — which also discards
	// the retention setting beside it.
	//
	// Takes effect on restart. See the type doc.
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
	// Dir is where day files are written. Empty means the caller's default, which for
	// a local install is ~/.cortex/cost — kept out of this struct so the config does
	// not pin a $HOME-derived absolute path into a file that may be copied between
	// machines.
	Dir string `yaml:"dir,omitempty" json:"dir,omitempty"`
	// RetentionDays is how many day files survive. Zero means the package default of
	// 31, which is roughly 10 MB.
	//
	// THIRTY-ONE because that is what window=month needs: a month-to-date total on the 31st
	// of a 31-day month opens 31 day files, and costledger's prune keeps exactly
	// retention_days distinct dates. See costledger.defaultRetentionDays, which is pinned to
	// usage.WindowMonthLocalDays.
	//
	// A non-zero value must be at least minCostLedgerRetentionDays; see there. Note that the
	// FLOOR is lower than the default: a deployment may legitimately keep less history than
	// window=month needs, and one that does will answer that window short.
	//
	// THE SHORTFALL IS DISCLOSED, which an earlier version of this comment denied: a pruned day
	// file is absent rather than unreadable, so it produces no Caveats entry — but
	// usage.Snapshot.DaysOutsideRetention counts the days a REQUEST asks for beyond this setting,
	// and the band marks such a total as a floor while `abctl cost` prints a coverage line. What
	// is still silent is a day pruned INSIDE the current horizon, from a setting that used to be
	// shorter; see that field. The default covers the longest shipped window so that the ordinary
	// case needs no disclosure at all.
	RetentionDays int `yaml:"retention_days,omitempty" json:"retention_days,omitempty"`
}

CostLedgerConfig configures the durable cost ledger.

NOT HOT-RELOADABLE, unlike most of this file. The reloader swaps the plugin pipeline and per-plugin config in place, but the ledger is constructed once at startup and handed to the session store as a recorder, so a running proxy holds whichever writer it opened. Editing anything here — enabled, dir, retention_days — takes effect on RESTART.

The edit is REFUSED rather than ignored: reloader.validateReloadable compares this block the way it compares mode and listener.*, so a live edit fails the reload, leaves LastError naming cost_ledger on /reload/status, and asks for a pod restart.

It did not always. This doc used to warn that "an operator who edits this to stop writing cost history has every reason to believe it stopped" — and they did, because the edit was ACCEPTED: ReloadsOK incremented, ActiveConfigSHA256 moved, and /config served the new values while the startup writer kept appending under the old retention. Documenting that was the weaker of the two options available; the guard is three lines and the precedent for it was already in the same function. Pinned by reloader.TestReloader_RefusesCostLedgerChange.

func (*CostLedgerConfig) DirSet

func (c *CostLedgerConfig) DirSet() bool

DirSet reports whether an operator named a directory for the ledger.

IT IS THE STRONGEST AVAILABLE SIGNAL THAT THE LEDGER CAN DELIVER, which is why the caller uses it to pick the default. The ledger's whole purpose is surviving a restart; writing to a path nobody chose achieves the opposite in a container, where the only place left is the image's writable layer — wiped on every restart and counted against the pod's ephemeral-storage limit, which is an eviction rather than a lost figure. An operator who names a path has mounted something to put it on, and that is a fact this package can see where "is there a volume here" is not.

A method rather than a field read, and nil-safe, because the block is absent in the common Kubernetes case and every caller would otherwise repeat the same check.

func (*CostLedgerConfig) LedgerEnabled

func (c *CostLedgerConfig) LedgerEnabled(defaultOn bool) bool

LedgerEnabled reports whether the ledger should run, given the default for this deployment shape.

WHAT defaultOn USED TO MEAN, AND WHY IT CHANGED. It was localMode — true under --local, false otherwise — and that made the default a property of WHICH FLAG STARTED THE BINARY rather than of whether the ledger could do its job. Every service install runs --config, so the documented "on by default" was false for every installed laptop. The caller now derives defaultOn from whether a durable location exists at all (see DirSet), so the answer no longer depends on the command line.

A method on the pointer receiver so a nil block — the common case in Kubernetes — answers without every caller writing the same nil check and one of them getting it backwards.

func (*CostLedgerConfig) Validate

func (c *CostLedgerConfig) Validate() error

Validate is called from the loader when CostLedger != nil.

type ListenerConfig

type ListenerConfig struct {
	ExtProcAddr         string `yaml:"ext_proc_addr" json:"ext_proc_addr"`
	ForwardProxyAddr    string `yaml:"forward_proxy_addr" json:"forward_proxy_addr"`
	ReverseProxyAddr    string `yaml:"reverse_proxy_addr" json:"reverse_proxy_addr"`
	ReverseProxyBackend string `yaml:"reverse_proxy_backend" json:"reverse_proxy_backend"`

	// Roles selects which proxies run in proxy-sidecar mode. Empty (the
	// default) runs BOTH the reverse proxy (inbound) and the forward proxy
	// (outbound) — the full pod deployment, so existing configs are unchanged.
	// Set a subset to run a single shape:
	//   roles: [forward]   # egress-only (e.g. a laptop TLS-bridge demo)
	//   roles: [reverse]   # inbound-only JWT validation
	// Valid values: "reverse", "forward". The preset fills an addr default
	// only for an active role, and reverse_proxy_backend is required only when
	// the reverse role is active. Ignored outside proxy-sidecar mode.
	Roles []string `yaml:"roles" json:"roles"`

	// InboundInterception selects HOW inbound traffic reaches the reverse
	// proxy's pipeline, in proxy-sidecar mode with the reverse role active:
	//
	//   reverse-proxy (default) — the operator binds AuthBridge on the agent's
	//                 original port and relocates the agent to a free one
	//                 ("port stealing"), so the Service needs no patching.
	//                 Forwards to the single reverse_proxy_backend URL.
	//   transparent — proxy-init PREROUTING-REDIRECTs inbound TCP to
	//                 transparent_inbound_addr; the listener recovers the port
	//                 the client actually addressed via SO_ORIGINAL_DST and
	//                 forwards there over loopback. The agent keeps its own
	//                 port, so no PORT env var is imposed on it and every port
	//                 it listens on is covered — not just the first declared
	//                 one. Requires proxy-init (NET_ADMIN) and is Linux-only.
	//
	// Defaults to reverse-proxy: transparent adds a privileged init container,
	// so it is opt-in, and leaving it unset keeps existing deployments
	// byte-identical.
	InboundInterception string `yaml:"inbound_interception" json:"inbound_interception"`

	// TransparentInboundAddr is the bind address for the inbound transparent
	// listener (inbound_interception: transparent). The proxy-sidecar preset
	// defaults it to ":8083" when that mode is selected — 8080 (reverse), 8081
	// (forward) and 8082 (transparent egress) are already taken. It MUST match
	// proxy-init's INBOUND_TRANSPARENT_PORT, or PREROUTING will REDIRECT to a
	// dead port and inbound traffic will break outright.
	TransparentInboundAddr string `yaml:"transparent_inbound_addr" json:"transparent_inbound_addr"`

	// TransparentProxyAddr is the bind address for the outbound transparent
	// listener used by proxy-sidecar enforce-redirect mode: iptables REDIRECTs
	// the agent's bypass egress here, and the listener recovers the original
	// destination via SO_ORIGINAL_DST and tunnels it through the same outbound
	// pipeline as the forward proxy. The proxy-sidecar / lite presets default it
	// to ":8082", so for those shapes the listener is effectively always on —
	// binding is harmless when nothing is redirected to it (cooperative
	// HTTP_PROXY deployments simply never receive connections on it). An empty
	// value only disables the listener for modes that have no preset default for
	// this field (envoy-sidecar); under proxy-sidecar / lite the
	// preset refills it, matching the always-on enforce-redirect design.
	TransparentProxyAddr string `yaml:"transparent_proxy_addr" json:"transparent_proxy_addr"`

	// SessionAPIAddr is the bind address for the session events HTTP server
	// (JSON snapshots + SSE stream consumed by abctl or curl). Default per
	// mode preset is ":9094". Set to empty string to disable the endpoint.
	SessionAPIAddr string `yaml:"session_api_addr" json:"session_api_addr"`

	// HealthAddr is the bind address for the liveness/readiness server
	// (/healthz, /readyz). Every mode preset defaults it to ":9091", which is
	// what Kubernetes probes expect. It is configurable because the literal was
	// previously hardcoded, and two proxies on one host could therefore never
	// coexist: the second died on a bind conflict. Local setups can pin it to
	// loopback on another port; leaving it empty keeps the preset default.
	HealthAddr string `yaml:"health_addr" json:"health_addr"`

	// BindLoopbackOnly rewrites EVERY listener address in this config (and the
	// stats address) to 127.0.0.1, keeping each port. Off by default, which
	// preserves Kubernetes behaviour exactly.
	//
	// Why a flag and not the default: in a pod, a wildcard bind is correct and
	// necessary — the network namespace is the boundary, and kubelet probes health
	// from outside the container's loopback, so forcing 127.0.0.1 there would fail
	// every liveness probe. On a laptop there is no namespace, and the same default
	// publishes the listener on Wi-Fi.
	//
	// Why a flag and not a per-listener pin: pinning each address protects only the
	// listeners someone remembered to name. A config written before a pin existed
	// never receives it (writeBuiltinConfig never overwrites, so hand edits
	// survive), and a listener added later starts wide with nothing to catch it.
	// This was not hypothetical: a laptop config predating the health and
	// transparent pins was serving *:9091 and *:8082 on every interface. One rule
	// covers listeners that do not exist yet.
	BindLoopbackOnly bool `yaml:"bind_loopback_only" json:"bind_loopback_only"`

	// SkipHosts lists outbound destination host patterns whose traffic
	// bypasses the plugin pipeline AND session recording entirely. The
	// listener forwards matched requests as a transparent proxy without
	// running plugins or appending events to any session bucket.
	//
	// Intended for high-volume infrastructure traffic that competes
	// with agent-meaningful events for session-buffer slots. The
	// canonical example: an OpenTelemetry collector sidecar that emits
	// dozens of exports per agent turn — without this gate, those
	// exports occupy the session buffer's FIFO eviction window and
	// silently push out the inbound A2A user intent that IBAC needs
	// to align tool calls against, causing IBAC to fall through to
	// the no_intent skip path on every call after the first.
	//
	// Patterns use `.`-delimited glob semantics (same library as
	// `authproxy-routes`): "otel-collector*" matches the short
	// service name, "otel-collector.rossoctl-system.svc.cluster.local"
	// matches the FQDN, "*-collector" matches any single-label name
	// ending in -collector. Port is stripped before matching, so
	// patterns must NOT include `:port`.
	//
	// Empty list (default) preserves current behavior: every outbound
	// host runs the pipeline and is eligible for session recording.
	//
	// Trust model — the value matched against SkipHosts is the
	// destination Host as observed at the listener boundary, which is
	// agent-influenceable in two of the three deployment shapes:
	//
	//   - ext_proc / envoy-sidecar: matches Envoy's `:authority`
	//     (fallback `host` header). The agent sets these; Envoy may
	//     rewrite them per its config, but ultimately the value is
	//     "what the agent told Envoy it wanted to talk to."
	//   - HTTP forward-proxy / proxy-sidecar: matches `r.Host` from
	//     the HTTP request. The request is then dialed against
	//     `r.URL`, so a forged Host that diverges from the real URL
	//     host would skip-match yet send to the actual upstream.
	//   - CONNECT-tunnel / proxy-sidecar: safer-by-construction —
	//     `r.Host` IS the dial target. A forged Host cannot
	//     skip-match while dialing elsewhere.
	//
	// Implication: do NOT list a destination here that you'd want
	// IBAC / token-exchange to deny on. Skip means "the operator
	// trusts every flow to this host enough to bypass the entire
	// outbound enforcement pipeline." Limit entries to infrastructure
	// destinations the agent should not be making policy decisions
	// against in the first place (collector sidecars, log shippers).
	//
	// Each skip is logged at INFO with the matched host and pattern
	// so an operator reviewing logs can see when a pattern fired and
	// catch unexpected matches early. The `transparentproxy` listener
	// (proxy-sidecar enforce-redirect mode) intentionally does NOT
	// consult SkipHosts — that is the hard egress guard and must not
	// be self-exemptable via the agent's outbound destination.
	//
	// Match-all patterns ("*", "**", whitespace-only) and patterns
	// containing ":port" are rejected at startup so a single
	// misconfigured entry can't silently disable all outbound
	// enforcement. Mirrors the bypass-pattern guard added to ibac
	// in #496.
	SkipHosts []string `yaml:"skip_hosts" json:"skip_hosts"`
}

ListenerConfig holds per-mode listener addresses.

func (ListenerConfig) ActiveRoles

func (l ListenerConfig) ActiveRoles() map[string]bool

ActiveRoles returns the set of proxy roles to run in proxy-sidecar mode. An empty Roles list defaults to BOTH roles (the full pod deployment), so existing configs and the operator path are unchanged; a non-empty list runs exactly the roles named. Unknown values are surfaced by Validate, not here.

func (ListenerConfig) InboundTransparent

func (l ListenerConfig) InboundTransparent() bool

InboundTransparent reports whether the inbound transparent listener should run instead of the fixed-backend reverse proxy. Empty means the default (reverse-proxy), so callers need no separate zero-value check.

type MTLSConfig

type MTLSConfig struct {
	// Mode controls the inbound + outbound TLS posture. Defaults to
	// permissive when empty.
	Mode MTLSMode `yaml:"mode" json:"mode"`
}

MTLSConfig is the top-level mTLS schema. One mode applies to both directions; if asymmetric needs surface later, this can split into separate Inbound / Outbound sub-blocks without breaking the existing flat shape.

X.509-SVID material is supplied by the in-process Provider (see SPIFFEConfig) and no longer configured here. Legacy chart configs may still ship cert_file / key_file / bundle_file keys; the YAML loader silently drops them (pinned by TestLoad_UnknownMTLSFields_Ignored).

func (*MTLSConfig) ResolvedMode

func (m *MTLSConfig) ResolvedMode() MTLSMode

ResolvedMode returns Mode with the empty-string default applied.

func (*MTLSConfig) Validate

func (m *MTLSConfig) Validate() error

Validate rejects unknown mode values at startup. SVID material is supplied by the SPIFFE Provider (see SPIFFEConfig); validation of that material is the Provider's responsibility, not this struct's.

type MTLSMode

type MTLSMode string

MTLSMode names the inbound + outbound TLS posture. Vocabulary borrows from Istio's PeerAuthentication.mtls.mode for familiarity.

const (
	// MTLSModePermissive accepts both TLS and plaintext on the
	// inbound side (byte-peek listener) and tries TLS on the outbound
	// side, falling back to plain TCP on handshake failure. The
	// rollout-friendly default; when an operator omits the mode
	// field, this is what they get.
	MTLSModePermissive MTLSMode = "permissive"
	// MTLSModeStrict accepts only TLS on the inbound side (byte-peek
	// closes non-TLS connections) and treats outbound TLS handshake
	// failures as hard errors with no fallback. Production posture
	// once the cluster is fully mTLS-capable.
	MTLSModeStrict MTLSMode = "strict"
)

type PipelineConfig

type PipelineConfig struct {
	Inbound  PipelineStageConfig `yaml:"inbound" json:"inbound"`
	Outbound PipelineStageConfig `yaml:"outbound" json:"outbound"`
}

PipelineConfig holds the plugin pipeline composition. Required: the runtime YAML must populate both inbound and outbound lists, or plugins.Build will produce empty pipelines and the listener will have nothing to invoke. There are no implicit defaults.

type PipelineStageConfig

type PipelineStageConfig struct {
	Plugins []PluginEntry `yaml:"plugins" json:"plugins"`
}

PipelineStageConfig lists the plugins for a pipeline stage in execution order.

type PluginEntry

type PluginEntry struct {
	Name    string               `yaml:"name" json:"name"`
	ID      string               `yaml:"id,omitempty" json:"id,omitempty"`
	OnError pipeline.ErrorPolicy `yaml:"on_error,omitempty" json:"on_error,omitempty"`
	Config  json.RawMessage      `yaml:"-" json:"config,omitempty"`
}

PluginEntry names a plugin and optionally carries per-instance config.

The YAML accepts both the bare-name form ("jwt-validation") and the full form ({name, id, on_error, config}). The short form keeps existing pipeline configs parsing unchanged; the long form is what plugins that implement pipeline.Configurable actually need. See authbridge/docs/plugin-reference.md for the convention plugins follow when decoding Config.

Config is captured as a raw subtree via json.RawMessage so the plugin can do its own DisallowUnknownFields decode against a typed struct — the framework does not interpret it.

OnError is the framework-owned wrapper policy (see ErrorPolicy). Plugin authors do not consume it — it lives outside the plugin's own config block so all plugins get the same rollout story without each one re-implementing shadow mode.

func (*PluginEntry) UnmarshalYAML

func (p *PluginEntry) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML accepts either a bare string or a map. The string form is equivalent to {name: <string>} with no config.

type SPIFFEConfig

type SPIFFEConfig struct {
	// Socket is the SPIRE agent socket URL. Defaults to
	// "unix:///spiffe-workload-api/spire-agent.sock" — the same path
	// spiffe-helper used to talk to.
	Socket string `yaml:"socket" json:"socket"`

	// MirrorFiles, when true, runs an in-process goroutine that writes
	// /opt/svid.pem, /opt/svid_key.pem, /opt/svid_bundle.pem, and
	// /opt/jwt_svid.token on every rotation — preserving today's
	// external-reader contract (Envoy filesystem SDS, e2e probes,
	// debugging shells). Pointer so we can distinguish unset
	// ("apply default true") from explicit false ("operator opted out").
	MirrorFiles *bool `yaml:"mirror_files" json:"mirror_files"`

	// MirrorDir is the directory where mirror files are written.
	// Defaults to "/opt". Only used when MirrorFiles is true.
	MirrorDir string `yaml:"mirror_dir" json:"mirror_dir"`
}

SPIFFEConfig is the top-level SPIFFE provider configuration. One block drives the in-process Provider that supplies X.509-SVIDs to the mTLS listeners and a JWT-SVID to the token-exchange plugin (when configured).

Defaults match today's spiffe-helper-driven setup so existing deployments boot without changes once chart/operator follow-ups land.

The audience for the JWT-SVID used by token-exchange as a client assertion is per-plugin (tokenexchange.identity.jwt_audience) and is no longer carried here — only the tokenexchange plugin's spiffe identity path consumes it, so it lives in that plugin's config.

func (*SPIFFEConfig) Validate

func (s *SPIFFEConfig) Validate() error

Validate rejects sockets that aren't unix:// URLs. The Workload API only speaks over a unix domain socket in our deployment model; a tcp:// or http:// scheme is almost certainly an operator typo and should fail at startup rather than at first dial.

type SessionConfig

type SessionConfig struct {
	// Enabled: nil means "unset → default on". Explicit `false` opts out.
	// Do not change to a plain bool — losing the nil sentinel would collapse
	// "user didn't say" with "user said false" and silently flip the default.
	Enabled *bool `yaml:"enabled" json:"enabled"`
	// TTL bounds how long an IDLE session is kept. Empty or "0" means never, which is
	// the default: time-based expiry read as data loss — traffic vanished because
	// someone stepped away, not because anything overflowed. Set it to a duration
	// ("30m") where limiting how long raw prompts sit in memory is worth the surprise,
	// or where one long-lived session would otherwise grow without limit — with
	// MaxEvents unset, a ttl is the only thing that bounds that shape. See Limits for
	// how the three resolve together and why the default is what it is.
	TTL string `yaml:"ttl" json:"ttl"` // duration string; default: never

	// MaxEvents bounds how many events ONE session keeps, oldest evicted first.
	// Unset (0) means unlimited, which is the default: a trimmed store is lossy on
	// exactly the sessions worth reading, and the trim point is invisible from the
	// timeline. Set it where one long-lived chatty session would otherwise grow
	// without limit — MaxSessions bounds how MANY sessions are kept, not how big any
	// one of them gets, so it is no help against a single session that never ends.
	MaxEvents int `yaml:"max_events" json:"max_events"` // max events per session; default: unlimited
	// MaxSessions bounds how many sessions are kept at once, least-recently-updated
	// evicted first. Unset means 100.
	//
	// NOT "0 = unlimited", which is what this said and what the store would do with a
	// zero it was handed: Limits substitutes 100 for any value <= 0, so the documented
	// unlimited was unreachable through every binary. It cannot be honoured either,
	// because MaxSessions is a plain int — an operator who never mentions max_sessions
	// yields the same 0 as one who writes it, so honouring 0 would delete the default
	// for everyone who left it alone, and with MaxEvents now unset that is the last
	// default bound standing. Distinguishing the two would take a *int, the way Enabled
	// above uses a *bool for exactly this reason. Not worth it for a value nobody has
	// asked for: to lift the cap, set it high.
	MaxSessions int `yaml:"max_sessions" json:"max_sessions"` // max concurrent sessions; default: 100 (<= 0 means default)

	// IDHeaders names the request headers consulted, in order, for a
	// client-supplied session id to bucket events under. Unset means the built-in
	// list of supported-agent headers (see SessionIDHeaders); an explicit list
	// REPLACES that default rather than extending it, and an explicit empty list
	// turns header bucketing off and puts every session back in one shared bucket.
	// Like Enabled above, the nil-versus-empty distinction is load-bearing — do
	// not collapse it by assigning a default at load time.
	//
	// The ids these headers carry are client-asserted and unauthenticated: a
	// client can name any bucket, including another session's. The store is
	// in-process, so the reach of that is every client that can reach this proxy
	// — one workload for a sidecar, but all of them for a shared or standalone
	// forward proxy, which binds a wildcard address by default. Set this to an
	// empty list in any deployment where telemetry attribution is a trust
	// boundary rather than a convenience. See session.IDFromHeaders for the full
	// reasoning.
	IDHeaders []string `yaml:"id_headers" json:"id_headers"`
}

SessionConfig controls in-memory session tracking for cross-request correlation. When enabled, the framework records inbound intents and outbound tool calls so that guardrail plugins can evaluate sequences across request boundaries.

Enabled is a pointer so the loader can distinguish "unset" (apply default) from "explicitly false" (user opted out). Default when unset: enabled.

func (SessionConfig) Limits

func (s SessionConfig) Limits() (SessionLimits, error)

Limits resolves the session store's parameters from config.

One home for what used to be the same twenty lines in three main packages, kept in step by review alone. It is also the only way to assert the part that matters most and is easiest to get wrong in one copy: MaxEvents passes through UNMODIFIED, so an operator who has not set session.max_events gets a store that never evicts an event from a live session.

The defaults, and why they are not symmetrical:

  • TTL 0 (never expire on time). Time-based expiry read as data loss — traffic vanished because someone stepped away, not because anything overflowed. Note what this does NOT rest on any more: it used to be justified by "the size caps still bound memory", and with MaxEvents unset by default that is no longer true for a single long-lived session. TTL stays 0 because a clock is the wrong tool for bounding memory, not because something else is bounding it.
  • MaxEvents 0 (unlimited). A trimmed store is lossy on exactly the sessions worth reading, and FIFO eviction takes the BEGINNING of a session — on a long agent run, the inbound request that started it — with no mark left in the timeline.
  • MaxSessions 100, for any configured value <= 0 including unset. This one keeps a default because it bounds how MANY sessions are kept, which is the dimension that grows without an operator doing anything unusual, and evicting a whole idle session costs less than truncating a live one. So the resolved MaxSessions is always positive, which is why LogAttrs does not render an "unlimited" for it the way it does for MaxEvents.

So on a single session that never ends, nothing here is a ceiling: set max_events or a ttl for that shape. A negative max_events means unlimited, the same as unset — it used to fall back to 500, and the startup log reports the resolved value either way.

A malformed session.ttl yields the zero TTL and is returned as an error for the caller to log; resolution stays here, logging stays at the edge.

func (SessionConfig) SessionEnabled

func (s SessionConfig) SessionEnabled() bool

SessionEnabled returns true when session tracking should run. Defaults to true when Enabled is unset, so operators need to explicitly opt out.

func (SessionConfig) SessionIDHeaders

func (s SessionConfig) SessionIDHeaders() []string

SessionIDHeaders returns the headers to consult for a client-supplied session id, defaulting to the known coding-agent session headers when unset: bucketing per coding-agent session is the point of running this on a laptop, and an operator should not have to learn a header name to get it. An explicit empty list disables the lookup.

The order is a precedence rule over clients, not a ranking — a request carrying both headers buckets under the Claude Code id. See session.IDFromHeaders.

Whatever this returns, a request that carries none of the named headers buckets exactly as it did before this option existed.

type SessionLimits

type SessionLimits struct {
	TTL         time.Duration
	MaxEvents   int
	MaxSessions int
}

SessionLimits is the resolved form of the three store parameters: what session.New should be called with, after defaults.

func (SessionLimits) LogAttrs

func (l SessionLimits) LogAttrs() []any

LogAttrs renders the resolved limits for a startup line, spelling out the two zeros that would otherwise read as misconfiguration: "ttl=0s" as if sessions expired instantly, "maxEvents=0" as if the store kept nothing. Takes limits as Limits produces them, where MaxSessions is always positive.

type StatsConfig

type StatsConfig struct {
	StatsAddress string `yaml:"address" json:"address"` // for example, ":9093"
}

StatsConfig represents the configuration for reporting config and statistics

type TLSBridgeConfig

type TLSBridgeConfig struct {
	// Mode is the bridge posture: "disabled" (off) or "enabled" (intercept all
	// eligible egress on the configured Ports). Empty == disabled.
	Mode string `yaml:"mode" json:"mode"` // disabled | enabled
	// CADir holds the per-agent signing CA, mounted from the operator's
	// cert-manager Secret. The bridge reads tls.crt + tls.key (to sign leaves);
	// ca.crt is the trust cert handed to the agent. cert-manager Secret key
	// conventions, so only the directory is configured.
	CADir string `yaml:"ca_dir" json:"ca_dir"`
	// GenerateCA, when true, makes the bridge mint and persist a self-signed CA
	// into CADir (tls.crt/tls.key/ca.crt) if those files are absent, instead of
	// failing at startup. For standalone / demo use only — in-cluster the CA is
	// a mounted cert-manager Secret and this stays false so a missing Secret
	// fails loudly rather than silently forging leaves under an untrusted CA.
	// CADir should persist across restarts: on ephemeral storage (e.g. an
	// emptyDir) a fresh CA is minted each boot, so clients must re-trust the
	// new ca.crt.
	GenerateCA bool `yaml:"generate_ca" json:"generate_ca"`
	// UpstreamCABundle is an extra-roots PEM file for re-origination (private-CA
	// origins the agent trusts); empty == system roots only.
	UpstreamCABundle string `yaml:"upstream_ca_bundle" json:"upstream_ca_bundle"`
	// UpstreamInsecure disables origin cert verification on re-origination
	// (InsecureSkipVerify). For internal/self-signed upstreams when the origin CA
	// is unavailable. Prefer UpstreamCABundle when possible.
	UpstreamInsecure bool `yaml:"upstream_insecure" json:"upstream_insecure"`
	// PassthroughHosts are hosts to tunnel (never intercept). Distinct from
	// listener.skip_hosts, which bypasses the whole pipeline; these still run the
	// egress gate, they just aren't TLS-terminated.
	PassthroughHosts []string `yaml:"passthrough_hosts" json:"passthrough_hosts"`
	// Ports is the set of TCP ports to intercept as TLS. Empty => {443, 8443}.
	// Only HTTP(S)-bearing ports belong here: the bridge serves the decrypted
	// stream as HTTP/1.1 or h2, so terminating a non-HTTP TLS protocol (LDAPS,
	// SMTPS, DB-over-TLS, …) would break it.
	Ports []int `yaml:"ports" json:"ports"`
}

TLSBridgeConfig configures the outbound TLS bridge (TLS termination of agent egress — formerly "MITM" — so the outbound plugin pipeline sees decrypted HTTPS).

func (*TLSBridgeConfig) Validate

func (b *TLSBridgeConfig) Validate() error

Validate is called from the loader when TLSBridge != nil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL