spiffeauth

package
v0.136.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 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 spiffeauth authenticates incoming requests by SPIFFE identity (an X.509-SVID over mTLS or an audience-scoped JWT-SVID) next to the API key, in dual mode: a request without a SPIFFE identity is handled exactly as before.

It is the server side of the ephemeral-credentials program (fleet-state docs/architecture/ephemeral-credentials, Phase 3): callers that hold a SPIRE identity stop depending on a long-lived API key, while every caller that still sends a key keeps working. It ships inert: nothing is verified, listened on or connected to until SPIFFEAUTH_MODE=dual is set.

What a service does

Nothing in code. server.New reads the SPIFFEAUTH_* variables and, when the mode is dual, hands an Authenticator to every WithKeystoreAuth* option (middleware.KeystoreOpts.Identity). A service that builds its own middleware.TokenAuthKeystore sets Identity itself:

h, err := spiffeauth.Start(cfg, log.Printf) // cfg from spiffeauth.ConfigFromEnv()
...
middleware.TokenAuthKeystore(middleware.KeystoreOpts{Verifier: ks, Observer: auth, Identity: h})

Configuration

SPIFFEAUTH_MODE          off (default) | dual. Rollback: unset it and restart.
SPIFFE_ENDPOINT_SOCKET   unix:///run/spire/agent.sock (the Workload API)
SPIFFEAUTH_PEERS_FILE    JSON peer map (or SPIFFEAUTH_PEERS inline), see below
SPIFFEAUTH_TRUST_DOMAINS comma list, default 0exec.com
SPIFFEAUTH_JWT_AUDIENCE  comma list; empty = no JWT-SVID path
SPIFFEAUTH_JWT_MAX_TTL   default 6m, at most 10m (SPIRE issues 5m)
SPIFFEAUTH_MTLS_ADDR     :8443 = extra TLS listener that verifies client certificates
SPIFFEAUTH_UNMAPPED      deny (default) | fallback

The peer map says which SPIFFE ID is which principal:

{"peers":[
  {"id":"spiffe://0exec.com/ns/*/sa/agent-tools","principal":"agent-tools","tier":"internal","scope":"write"},
  {"id":"spiffe://0exec.com/ns/0crawl/sa/go-url-fetcher","principal":"go-url-fetcher"}
]}

Both ID shapes the fleet issues are understood, spiffe://0exec.com/ns/fleet/sa/<service> and spiffe://0exec.com/ns/0crawl/sa/<service>; "*" as the ns segment covers those two namespaces and no other (ParseWorkloadID). The principal, tier and scope are what the request carries afterwards (X-Auth-User, X-Auth-Tier, X-Auth-Scope, the graph caller label, and the RequiredTier gate), replacing anything the caller sent in those headers.

What counts as an identity

  • mTLS: a client certificate on the SPIFFEAUTH_MTLS_ADDR listener. The handshake verifies it against the trust bundle (an invalid or foreign one fails the handshake), and the request check verifies it again.
  • JWT-SVID: Authorization: Bearer <jwt> (only a JWT-shaped value, never an ak_/fb_ key) or the X-Spiffe-Jwt header, on any listener. Signature, expiry and audience are checked against the bundle, and a token with more than SPIFFEAUTH_JWT_MAX_TTL left is refused, so a leaked token dies in minutes. A JWT-SVID is never sent to the keystore as if it were a key.

Dual mode

A request with no SVID is not touched: gateway header, local token and keystore work as before, and nothing is rejected for lacking a SPIFFE identity. The default-deny applies only to a caller that presented an SVID: an ID missing from the map gets 403 (SPIFFEAUTH_UNMAPPED=fallback counts it and lets the key decide). A presented JWT-SVID that does not verify is counted and, when the request also carries a key, the key decides; without a key the answer is 401.

Metrics

apikey_auth_total{source="spiffe-mtls"|"spiffe-jwt", result}
spiffe_verify_failures_total{source, reason}
spiffe_apikey_fallback_total{principal, reason}

The last one counts an API key authenticating a principal that has a SPIFFE mapping, "SPIFFE expected, key used". The Phase 3 exit metric, fallback below 0.1 %:

sum(rate(spiffe_apikey_fallback_total[7d])) /
  (sum(rate(spiffe_apikey_fallback_total[7d])) +
   sum(rate(apikey_auth_total{source=~"spiffe-.*",result="allow"}[7d])))

No token, certificate or peer detail reaches a log line, an error or a metric label: the labels are the fixed Reason* tokens and operator-configured principals.

A binary built with -tags gocommon_nospiffe does not link this package or go-spiffe; server.New then only logs that SPIFFEAUTH_MODE has no effect.

Index

Constants

View Source
const (
	ReasonInvalidSVID     = "invalid_svid"     // the certificate chain does not verify against the trust bundle
	ReasonUntrustedDomain = "untrusted_domain" // verified, but from a trust domain this service does not accept
	ReasonExpiredToken    = "expired_token"    // JWT-SVID expired
	ReasonWrongAudience   = "wrong_audience"   // JWT-SVID minted for another audience
	ReasonInvalidToken    = "invalid_token"    // JWT-SVID malformed or its signature does not verify
	ReasonTTLTooLong      = "ttl_too_long"     // JWT-SVID valid for longer than SPIFFEAUTH_JWT_MAX_TTL
	ReasonUnmappedID      = "unmapped_id"      // verified, but the ID is not in the peer map
	ReasonNotReady        = "not_ready"        // the Workload API connection is not up yet
	ReasonOther           = "other"
)

The reasons a presented SPIFFE identity is not accepted. They are the values of spiffe_verify_failures_total{reason} and nothing else: no token, no certificate content and no peer detail ever reaches a log, an error or a metric.

View Source
const (
	EnvMode            = "SPIFFEAUTH_MODE"
	EnvPeersFile       = "SPIFFEAUTH_PEERS_FILE"
	EnvPeers           = "SPIFFEAUTH_PEERS"
	EnvTrustDomains    = "SPIFFEAUTH_TRUST_DOMAINS"
	EnvJWTAudience     = "SPIFFEAUTH_JWT_AUDIENCE"
	EnvJWTMaxTTL       = "SPIFFEAUTH_JWT_MAX_TTL"
	EnvMTLSAddr        = "SPIFFEAUTH_MTLS_ADDR"
	EnvUnmapped        = "SPIFFEAUTH_UNMAPPED"
	EnvStrictPresented = "SPIFFEAUTH_STRICT_PRESENTED"
	EnvSocket          = "SPIFFE_ENDPOINT_SOCKET"
	DefaultTrustZone   = "0exec.com"

	// DefaultJWTMaxTTL is the longest remaining lifetime of a JWT-SVID accepted
	// when SPIFFEAUTH_JWT_MAX_TTL is unset. SPIRE issues 5-minute JWT-SVIDs here;
	// the extra minute is clock skew.
	DefaultJWTMaxTTL = 6 * time.Minute
	// MaxJWTMaxTTL is the ceiling for SPIFFEAUTH_JWT_MAX_TTL.
	MaxJWTMaxTTL = 10 * time.Minute
)

Environment variable names. SPIFFE_ENDPOINT_SOCKET (the Workload API address) is the standard variable and is declared by package graph.

View Source
const JWTHeader = "X-Spiffe-Jwt"

JWTHeader is the request header that can carry a JWT-SVID, for a caller that also sends an API key in Authorization.

Variables

View Source
var ErrNoServerSVID = errors.New("spiffeauth: no server X.509-SVID source")

ErrNoServerSVID: the Authenticator has no X.509-SVID of its own to present.

Functions

func ParseWorkloadID

func ParseWorkloadID(id string) (trustDomain, namespace, service string, ok bool)

ParseWorkloadID splits spiffe://<trust domain>/ns/<ns>/sa/<service>, the shape of every workload identity in the fleet (the 0exec namespaces are "fleet" and "0crawl"). ok is false for any other path.

Types

type Authenticator

type Authenticator struct {
	// contains filtered or unexported fields
}

Authenticator verifies SPIFFE identities against the trust bundle the Workload API delivers and maps them to principals. It implements middleware.IdentityAuthenticator. Methods are safe for concurrent use.

func New

func New(ctx context.Context, cfg Config) (*Authenticator, error)

New connects to the Workload API at cfg.Socket, waits (up to cfg.ConnectTimeout) for the first SVID and bundle, and returns the Authenticator. It reuses package spiffe's Workload API clients. cfg must be enabled (ModeDual) and valid; ConfigFromEnv returns one.

func NewFromSources

func NewFromSources(cfg Config, svid x509svid.Source, x509 x509bundle.Source, jwt jwtbundle.Source) (*Authenticator, error)

NewFromSources builds an Authenticator on explicit sources: svid is this workload's own X.509-SVID (needed only for TLSConfig, may be nil), x509 the trust bundles for client certificates, jwt the JWT authorities (nil turns the JWT path off). New wires the Workload API into it; tests wire fakes.

func (*Authenticator) AuthenticateIdentity

func (a *Authenticator) AuthenticateIdentity(r *http.Request) middleware.IdentityDecision

AuthenticateIdentity implements middleware.IdentityAuthenticator.

func (*Authenticator) Close

func (a *Authenticator) Close() error

Close releases the Workload API connections.

func (*Authenticator) Config

func (a *Authenticator) Config() Config

Config returns the configuration in use (the peer map included; it holds no secret).

func (*Authenticator) ExpectedPrincipal

func (a *Authenticator) ExpectedPrincipal(user string) (string, bool)

ExpectedPrincipal implements middleware.IdentityAuthenticator.

func (*Authenticator) StrictPresented added in v0.115.2

func (a *Authenticator) StrictPresented() bool

StrictPresented implements middleware.StrictIdentity.

func (*Authenticator) TLSConfig

func (a *Authenticator) TLSConfig() (*tls.Config, error)

TLSConfig is the server-side tls.Config of the mTLS listener: it presents this workload's X.509-SVID and asks the client for a certificate. A client that sends none is served (the request then goes the API key path); one that sends a certificate must present an X.509-SVID that verifies against the trust bundle of an accepted trust domain, or the handshake fails. Which principal it is decided per request by AuthenticateIdentity, from the peer map.

type Config

type Config struct {
	Mode Mode
	// Socket is the Workload API address, unix:///run/spire/agent.sock.
	Socket string
	// TrustDomains are the trust domains whose SVIDs are accepted (default 0exec.com).
	TrustDomains []string
	// Peers is the SPIFFE ID to principal map. An ID that is not in it is
	// refused per Unmapped, but only when the caller presented an SVID.
	Peers []Peer
	// JWTAudience lists the accepted JWT-SVID audiences; empty turns the JWT path off.
	JWTAudience []string
	// JWTMaxTTL is the longest remaining lifetime of an accepted JWT-SVID.
	JWTMaxTTL time.Duration
	// MTLSAddr is the listen address of the extra TLS listener (":8443"); empty = none.
	MTLSAddr string
	Unmapped UnmappedPolicy
	// StrictPresented: a request that presented an SVID which was not accepted is
	// not admitted by private-mesh trust (middleware.StrictIdentity). Default false.
	StrictPresented bool
	// ConnectTimeout bounds one wait for the first SVID in New (default 30 s).
	ConnectTimeout time.Duration
	// Observer receives failures that happen below the HTTP layer (a TLS
	// handshake that failed verification). server.New sets it to the promx
	// collectors. nil is fine.
	Observer middleware.IdentityObserver
}

Config configures an Authenticator. The zero value is ModeOff.

func ConfigFromEnv

func ConfigFromEnv() (Config, error)

ConfigFromEnv reads the SPIFFEAUTH_* variables. With SPIFFEAUTH_MODE unset or off it returns a ModeOff Config and a nil error whatever else is set, so an unconfigured service is untouched. A configuration that cannot work (dual with no socket or no peers, a bad peer entry) is an error: the caller logs it and runs without the SPIFFE path (server.New does), never refusing to start.

func (Config) Enabled

func (c Config) Enabled() bool

Enabled reports whether the configuration turns SPIFFE authentication on.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is an Authenticator that connects to the Workload API in the background. A service never waits for SPIRE to start: until the connection is up the Handle authenticates nothing (every request goes the API key path) and its mTLS listener refuses client handshakes it cannot verify. It implements middleware.IdentityAuthenticator.

func Start

func Start(cfg Config, logf func(string, ...any)) (*Handle, error)

Start validates cfg and, for an enabled one, connects in the background, retrying with a growing pause until it succeeds. It returns nil, nil for a disabled (ModeOff) configuration, which is the inert default, and an error for a configuration that cannot work. logf (may be nil) gets one line per state change and never a credential.

func (*Handle) AuthenticateIdentity

func (h *Handle) AuthenticateIdentity(r *http.Request) middleware.IdentityDecision

AuthenticateIdentity implements middleware.IdentityAuthenticator: it authenticates nothing until the connection is up.

func (*Handle) Close

func (h *Handle) Close() error

Close stops the background connect and releases the connections. It is safe to call twice.

func (*Handle) Config

func (h *Handle) Config() Config

Config returns the configuration in use.

func (*Handle) ExpectedPrincipal

func (h *Handle) ExpectedPrincipal(user string) (string, bool)

ExpectedPrincipal implements middleware.IdentityAuthenticator; it needs only the configured map, so it works before the connection is up.

func (*Handle) Ready

func (h *Handle) Ready() bool

Ready reports whether the Workload API connection is up.

func (*Handle) StrictPresented added in v0.115.2

func (h *Handle) StrictPresented() bool

StrictPresented implements middleware.StrictIdentity; like ExpectedPrincipal it needs only the configuration.

func (*Handle) TLSConfig

func (h *Handle) TLSConfig() *tls.Config

TLSConfig is the tls.Config for the mTLS listener. It asks the current Authenticator for its config on every handshake, so it works once the connection is up and refuses handshakes before.

type Mode

type Mode string

Mode is the SPIFFEAUTH_MODE setting.

const (
	// ModeOff (the default): nothing is verified, no listener is started, no
	// Workload API connection is made.
	ModeOff Mode = "off"
	// ModeDual: a request carrying a valid, mapped SVID is authenticated as the
	// mapped principal; a request without one goes through the API key path
	// unchanged. Nothing is rejected for lacking a SPIFFE identity.
	ModeDual Mode = "dual"
)

type Peer

type Peer struct {
	// ID is spiffe://<trust domain>/ns/<ns>/sa/<service>. "*" may stand for the
	// whole ns segment (spiffe://0exec.com/ns/*/sa/agent-tools covers
	// /ns/fleet/sa/agent-tools and /ns/0crawl/sa/agent-tools, and no other
	// namespace). An exact entry wins over a wildcard one.
	ID string `json:"id"`
	// Principal is what handlers see in X-Auth-User and what the graph labels
	// the caller with: use the service's name (lowercase, with a "-"). When the
	// service also has API keys, use the principal the keystore returns for them,
	// which is what lets spiffe_apikey_fallback_total see a fallback.
	Principal string `json:"principal"`
	// Tier is the access tier for KeystoreOpts.RequiredTier ("" = none, like a pre-tiering key).
	Tier string `json:"tier,omitempty"`
	// Scope is what X-Auth-Scope carries for this peer.
	Scope string `json:"scope,omitempty"`
}

Peer maps one SPIFFE ID (or one service in either namespace) to the principal a request carrying it is authenticated as.

func ParsePeers

func ParsePeers(b []byte) ([]Peer, error)

ParsePeers decodes the peer map JSON: {"peers":[{"id","principal","tier","scope"}]}. Unknown fields are an error, so a typo does not silently drop a restriction.

type UnmappedPolicy

type UnmappedPolicy string

UnmappedPolicy is what happens to a presented SVID whose SPIFFE ID is not in the peer map.

const (
	// UnmappedDeny (the default): 403. Applies only to a caller that presented an SVID.
	UnmappedDeny UnmappedPolicy = "deny"
	// UnmappedFallback: count it and let the API key path decide.
	UnmappedFallback UnmappedPolicy = "fallback"
)

Jump to

Keyboard shortcuts

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