oidcfed

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package oidcfed validates externally issued OIDC ID tokens presented as a machine credential (#62, machine-identities ADR § Federation), and owns the server-side JWKS cache with its bounded staleness window.

It is a sibling of internal/oidcrp, not an extension of it, and the split is deliberate: oidcrp is a RELYING PARTY — it runs an authorization-code flow, holds a client id and secret, and validates a token it asked for. Federation has no flow, no client secret and no redirect: a workload arrives holding a token some platform minted for it, and the only questions are whether the signature is genuinely that issuer's and whether every pinned claim matches. Sharing one type would have meant one struct with two disjoint halves.

What this package does NOT do: hand-roll any JWT or signature verification. go-oidc performs the whole cryptographic check against keys this package fetched and cached; go-jose parses the JWKS document into public keys and reads the unverified header for cache maintenance. The human-auth ADR's no-hand-rolled-primitive invariant governs federation unchanged.

Index

Constants

View Source
const (
	// RefreshInterval is how old a cached key set may get before a validation
	// tries to refresh it PROACTIVELY. A failed proactive refresh is not a
	// refusal: the ADR rejects "failing closed the moment a scheduled refresh
	// fails" outright, because the failure this must survive is an API-server
	// blip and that would stop every workload fetch cluster-wide.
	RefreshInterval = 15 * time.Minute
	// StalenessBound is the ceiling. Past it, validation FAILS CLOSED AND
	// LOUDLY rather than serving from a key set nobody has been able to
	// confirm. Kubernetes service-account signing keys rotate rarely, so a
	// bounded window costs very little exposure — but it is bounded.
	StalenessBound = 6 * time.Hour
	// UnknownKIDRefreshesPerMinute rate-limits the refresh an unknown `kid`
	// triggers, PER ISSUER. This is load-bearing rather than hygiene: the
	// trigger sits on a pre-authentication path, so a stream of fabricated
	// `kid` values is an outbound-fetch amplifier aimed at the issuer.
	UnknownKIDRefreshesPerMinute = 5
	// RefreshBackoff is how long a FAILED fetch suppresses the next attempt for
	// that issuer.
	//
	// It is the difference between a tolerated outage and a self-inflicted one.
	// Without it, every request during an issuer outage starts its own
	// fetchTimeout-bounded fetch: the stale-but-valid path the ADR insists on
	// becomes an unauthenticated amplifier against both the issuer and this
	// instance. With it, one attempt per issuer per window discovers the outage
	// and every other request serves stale (or fails closed past the bound)
	// without touching the network.
	RefreshBackoff = 30 * time.Second
	// MaxTokenAge caps `now - iat` INDEPENDENTLY of what the issuer chose: a
	// configured issuer that mints long-lived tokens must not thereby mint
	// long-lived Hikyo access.
	//
	// One hour, and the number is a compromise with reality rather than a
	// preference: a Kubernetes projected ServiceAccount token defaults to a
	// one-hour lifetime and the kubelet refreshes it at 80% of that, so a
	// legitimate token on disk can be ~48 minutes old. A tighter cap would
	// refuse the platform's default configuration, which is a cap that gets
	// turned off rather than a cap that holds.
	MaxTokenAge = time.Hour
	// MaxTokenSpan caps `exp - iat`, the issuer's own declared validity
	// window. Two hours leaves headroom above the one-hour Kubernetes default
	// without admitting the day-long tokens some CI platforms can be
	// configured to mint.
	MaxTokenSpan = 2 * time.Hour
	// MaxClockSkew is the accepted positive clock skew, and it does double
	// duty: it bounds how far into Hikyo's future an `iat` may sit, and it IS
	// the margin in the post-restore `iat` predicate (§ Restore: "strictly
	// greater than reactivated_at plus the maximum accepted positive clock
	// skew"). One constant, because two would let the predicate's margin drift
	// below the skew validation accepts — which is exactly the gap the
	// predicate exists to close.
	MaxClockSkew = 2 * time.Minute
)

The operations-spec fog values this ticket chose, every one recorded for ratification in docs/handoff/62-oidc-federation-cursor.md.

View Source
const EventNameClaim = "event_name"

EventNameClaim is the claim every CI binding must pin.

View Source
const KubernetesServiceAccountUID = "/kubernetes.io/serviceaccount/uid"

KubernetesServiceAccountUID is where a projected ServiceAccount token carries the immutable UID: nested under the literal `kubernetes.io` claim.

Variables

View Source
var (
	// ErrNotAToken means the presented value is not a JWS at all. It is
	// returned before anything else so a bearer credential presented on this
	// path is classified rather than refused as a bad signature.
	ErrNotAToken = errors.New("oidcfed: presented value is not a signed token")
	// ErrNoIssuer means the token names an issuer this instance does not
	// configure. It is indistinguishable on the wire from every other refusal.
	ErrNoIssuer = errors.New("oidcfed: token issuer is not configured")
	// ErrKeysUnavailable means no key set could be obtained and none is
	// cached. Fail closed.
	ErrKeysUnavailable = errors.New("oidcfed: issuer keys are unavailable")
	// ErrInsecureTransport means a discovery document, a redirect or an issuer
	// URL named a non-HTTPS endpoint. It is its own sentinel because it is not a
	// transport failure: it is the one failure mode where completing the fetch
	// successfully would be the vulnerability.
	ErrInsecureTransport = errors.New("oidcfed: issuer key material must be fetched over https")
	// ErrKeysStale means the cached key set is older than the staleness bound.
	// This is the LOUD half of "validation continues from cache up to that
	// bound and then fails closed, loudly".
	ErrKeysStale = errors.New("oidcfed: cached issuer keys are past the staleness bound")
	// ErrTokenInvalid is a signature, issuer, audience, expiry or claim
	// failure.
	ErrTokenInvalid = errors.New("oidcfed: token validation failed")
	// ErrTokenAge is a token older than Hikyo's own cap, or whose declared
	// validity span exceeds it. Separate from ErrTokenInvalid because it is
	// Hikyo refusing a token the issuer considers perfectly valid.
	ErrTokenAge = errors.New("oidcfed: token age or validity span exceeds the instance cap")
	// ErrAudience is a token whose audiences do not include the bound one, or
	// which carries an audience the issuer configuration refuses.
	ErrAudience = errors.New("oidcfed: token audience is not the bound audience")
	// ErrClaim is a pinned claim that is absent or does not match byte-exactly.
	ErrClaim = errors.New("oidcfed: a pinned claim is absent or does not match")
	// ErrImmutableIdentityUnavailable refuses federation from an issuer whose
	// tokens cannot bind a workload to immutable repository ownership.
	ErrImmutableIdentityUnavailable = errors.New("oidcfed: issuer exposes no immutable workload identity")
	// ErrEventName is the CI-specific refusal: a `pull_request` or
	// `pull_request_target` token presented against a binding that did not
	// separately and deliberately bind that event.
	ErrEventName = errors.New("oidcfed: pull-request events are refused unless separately bound")
	// ErrRestorePredicate is the post-restore `iat` refusal. It is permanent
	// for the life of the binding, not a waiting period.
	ErrRestorePredicate = errors.New("oidcfed: token predates this binding's re-activation")
)

Refusals. Every one is a REFUSAL, never a downgrade (§ Federation: "failure at any step is a refusal"). They are separate sentinels because each maps to a distinct closed audit cause, and an investigator needs to tell "we could not reach the issuer" from "the token was forged".

View Source
var RefusedEvents = []string{"pull_request", "pull_request_target"}

RefusedEvents are the two triggers a CI binding must not admit unless one of them is what it deliberately bound.

View Source
var RequiredPins = map[domain.IssuerType][]string{
	domain.IssuerGitHubActions: {"repository_id", "repository_owner_id", EventNameClaim},
	domain.IssuerKubernetes:    {KubernetesServiceAccountUID},
}

RequiredPins is the closed per-issuer-type set of claims a binding MUST pin, enforced at creation.

This is the ADR's rule read as the MUST it is: "where an issuer exposes immutable numeric identifiers for the repository and its owner, the binding pins those rather than the names. A rename or transfer otherwise silently re-points a production binding at whatever now occupies the old path." Leaving it to operator diligence — which the first cut did, enforcing only `event_name` — accepts a binding pinning nothing but `event_name=push`, and a renamed-then-reused repository path inherits the principal.

There is deliberately NO override flag. An override is the thing an operator sets once during a migration and never removes, and the ADR does not offer one.

  • github-actions exposes both numeric ids, so both are required, plus `event_name` for the pull-request rule.
  • kubernetes exposes the ServiceAccount UID, nested — required through its JSON Pointer. A recreated ServiceAccount with the same name has a different UID, which is precisely what this closes.

Forgejo is intentionally absent. Its Actions tokens expose repository names, not immutable repository ownership. Binding them would let a reused path inherit an existing machine principal, so creation and validation refuse the issuer until it exposes an immutable identifier.

Functions

func CheckBinding

func CheckBinding(iss Issuer, b Binding, c Claims, now time.Time) error

CheckBinding is the binding half of validation, evaluated against the row the `(issuer, subject)` lookup resolved to.

Order matters here and is deliberate: the audience is checked first because it is the one the ADR calls MANDATORY and the one whose default the issuer itself would otherwise satisfy; the pinned claims next; the CI event rule after them, because it reads a claim the pinned set has already been proven to contain; the restore predicate last, because it is the only check that can pass for a token that is in every other way correct.

func LooksLikeToken

func LooksLikeToken(presented string) bool

LooksLikeToken reports whether a presented value is a compact JWS at all. It is the transport's classifier: a `hik_` bearer artifact and an ID token arrive through the same header, and the branch must be on the SHAPE the caller sent rather than on anything the server has yet decided to trust.

func MissingRequiredPins

func MissingRequiredPins(t domain.IssuerType, pinned map[string]json.RawMessage) []string

MissingRequiredPins returns the claims this issuer type demands and the binding does not pin, sorted. Empty means the binding satisfies the rule.

func ParseRequiredClaims

func ParseRequiredClaims(raw string) (map[string]json.RawMessage, error)

ParseRequiredClaims decodes a binding's pinned-claim object. It is exported because the mint path validates the same document before storing it, and two decoders would be two chances to disagree about what a pinned claim is.

A pinned VALUE is always a scalar — a nested pinned value would make "byte-exact" a question about JSON key order and whitespace rather than about the value. A pinned NAME may be either a top-level claim name or a JSON Pointer (RFC 6901) into a nested object; see resolveClaim.

func Peek

func Peek(presented string) (issuer, kid string, err error)

Peek reads the presented value's UNVERIFIED issuer and key id.

Nothing here is trusted, and the naming says so: the result drives only cache maintenance — which issuer configuration to look up, and whether the cached key set plausibly contains the key this token was signed with. Every security decision happens in Verify, against a key set chosen before the signature is checked.

func ValidatePointer

func ValidatePointer(name string) error

ValidatePointer refuses a malformed pointer at BINDING CREATION rather than leaving it to be discovered as a pin that never matches.

It is called from ParseRequiredClaims, which both the creation path and the validation path go through — so there is one definition of a well-formed pointer and neither path can drift from it.

Types

type Binding

type Binding struct {
	Audience string
	// RequiredClaimsJSON is the stored JSON object of pinned claims. Every one
	// is required; a binding pinning nothing is refused at creation, not here.
	RequiredClaimsJSON string
	// ReactivatedAt drives the restore predicate when non-zero.
	ReactivatedAt time.Time
}

Binding is the cache's projection of one federated binding — the policy half of validation, evaluated after the signature is proven and the binding found.

type Cache

type Cache struct {
	// HTTP is the client discovery and JWKS fetches use. Nil means a client
	// with fetchTimeout. Whatever is supplied, it is used through a COPY
	// carrying the HTTPS redirect guard (see guardedClient).
	HTTP *http.Client
	// Limiter rate-limits OUTBOUND REFRESHES, per issuer. Nil means unlimited,
	// which is only for tests: production wiring passes the admission limiter.
	Limiter RefreshLimiter
	// Now is injectable so the staleness bound is testable without sleeping.
	Nowf func() time.Time
	// contains filtered or unexported fields
}

Cache is the process-wide JWKS cache. There is deliberately no table behind it: a restart empties it, which makes the first validation after a restart fetch or fail closed — STRICTER than the staleness bound, never looser.

There is also deliberately no background ticker. Refresh is lazy: a validation whose keys are older than RefreshInterval tries to renew them on the way past. This binary has no scheduler (see #61's same disposition for expiry-threshold events), and a lazy refresh has the property a ticker does not: an issuer nobody authenticates against is never polled.

LOCKING, because the naive version is a denial-of-service rather than a performance note. `mu` guards the MAP ONLY and is never held across a network call; each issuer's own `entry.mu` serializes that issuer's fetches. So concurrent validations for one issuer queue behind a single refresh (singleflight, which is what we want — they all need the same answer), while an unreachable issuer cannot block validation for any OTHER issuer.

Holding one process-wide mutex across the fetch, as the first cut did, meant a single dead issuer stalled every federated authentication in the instance for `fetchTimeout` per request — an unauthenticated cross-issuer outage lever, reachable by anyone who can present a token.

func (*Cache) Verify

func (c *Cache) Verify(ctx context.Context, iss Issuer, presented string, now time.Time) (Claims, KeyState, error)

Verify performs the complete cryptographic and generic validation: exact `iss` against the configured issuer, signature under an algorithm from the allowlist (never `none`), `exp`/`iat`/`nbf` within a bounded skew, and Hikyo's own caps on token age and declared span.

It deliberately does NOT check the audience or the pinned claims. Those are properties of a BINDING, and the binding is found by the `(iss, sub)` pair this function produces — so they are CheckBinding's, evaluated in the authorizing transaction against the row that was actually resolved.

type Claims

type Claims struct {
	Issuer   string
	Subject  string
	Audience []string
	IssuedAt time.Time
	Expiry   time.Time
	Raw      map[string]json.RawMessage
}

Claims is a validated token's content. `Raw` carries every claim so the binding's pinned set can be compared without this package knowing which claims any platform uses.

type Issuer

type Issuer struct {
	ID          string
	Issuer      string
	Type        domain.IssuerType
	KeySource   jwkssource.KeySource
	CABundlePEM string
	// RefusedAudiences are the issuer's default audiences. A token carrying
	// ANY of them is refused even when it also carries the bound one: a token
	// minted for the Kubernetes API server that happens to list Hikyo too is
	// still a token the API server could have been handed.
	RefusedAudiences []string
}

Issuer is the cache's projection of one configured issuer. It carries only what fetching and verifying need, so this package never sees a stored row.

type KeyState

type KeyState struct {
	// Served reports the cache age the validation used. Zero for a static
	// JWKS, which has no age.
	Age time.Duration
	// RefreshFailed is the error a proactive or unknown-`kid` refresh hit and
	// which the cache absorbed by serving stale keys. Nil when nothing failed.
	RefreshFailed error
	// ServedStale reports that the key set was older than RefreshInterval and
	// a refresh did not renew it — the ADR's tolerated window in use.
	ServedStale bool
	// RefreshThrottled reports that an unknown `kid` did NOT trigger a fetch
	// because the per-issuer rate limit refused it.
	RefreshThrottled bool
}

KeyState is what a validation observed about the key set it used, so the caller can emit the ADR's "JWKS refresh failure and staleness-bound breach" events without this package owning an audit dependency.

type RefreshLimiter

type RefreshLimiter interface {
	AllowIssuerRefresh(issuer string) bool
}

RefreshLimiter is the rate limit an unknown-`kid` refresh runs under. It is an interface so this package does not import the admission limiter (and so the outage fixtures can drive it), but the production implementation IS that limiter: the ADR puts this trigger under the same instance-wide pre-authentication budget as every other unauthenticated path.

Jump to

Keyboard shortcuts

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