idpmeta

package
v1.0.521 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 12 Imported by: 0 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 idpmeta is the durable last-known-good store for the REMOTE documents an interactive IdP provider needs in order to exist at all: the SAML IdP EntityDescriptor (metadata_url) and the OIDC discovery document (issuer/.well-known/openid-configuration).

Why this package exists (CHAOS-87)

Compiling an enabled SAML or OIDC profile used to perform a synchronous outbound fetch against the customer's IdP, with no cache and no fallback, on three paths that must not depend on a third party:

  • the BOOT path (IdPRegistry.Load), where a failure was permanent for the life of the process and left the profile enabled-but-not-live, reported by exactly one log line;
  • the admin write path (Upsert);
  • the CP->DP CONFIG SYNC path (ReplaceAll, from syncSnapshotIdPProfiles), where a failure ABORTED THE WHOLE SNAPSHOT — so an IdP maintenance window stopped policy, blocklist and threat-feed distribution across the entire fleet, and every data plane retried the fetch every 30 s for the duration, aiming the fleet's full poll rate at the IdP that was already down.

The rule this package establishes: **a third party's availability decides whether an IdP's metadata is FRESH, never whether the IdP EXISTS.** A document that was fetched successfully once is kept, and a later fetch failure degrades to it instead of destroying the provider.

The staleness ceiling is the security half

Serving a cached document forever would keep trusting an IdP signing certificate the IdP may have withdrawn — withdrawing a key from published metadata is the IdP's revocation lever, exactly as it is for a JWKS document. internal/auth's jwksStaleMaxAge (SEC-JWKS-1) reached the same conclusion one layer down and the answer is the same here: stale is a BOUNDED degradation. Past StaleMaxAge the entry is refused and the caller fails exactly as it did before this package existed.

Two invariants callers must preserve

  1. CACHED BYTES GO THROUGH THE IDENTICAL PARSER AND VALIDATOR AS NETWORK BYTES. This store returns raw bytes and nothing else; it never parses, never validates, and must never become a path that admits a document the network path would have rejected. An operator (or anything with write access to dataDir) editing a cache file must not be able to widen a trust decision.

  2. THE KEY BINDS THE DOCUMENT TO ITS SOURCE. Entries are keyed by profile id AND a digest of the source URL, so re-pointing a profile at a different IdP can never be answered from the previous IdP's document. A profile whose source changed has no cache until it fetches one.

Index

Constants

View Source
const (
	// StaleMaxAge bounds how long a cached document may substitute for a
	// live fetch. Past it the entry is refused and the caller fails closed
	// (pre-CHAOS-87 behaviour). Seven days comfortably covers an IdP
	// maintenance window, a weekend outage and an egress misconfiguration,
	// while staying far short of a key-rotation interval.
	//
	// It is a CONSTANT by design: an operator knob here could only ever
	// WIDEN the window in which a withdrawn IdP signing key keeps being
	// trusted, which is the one direction this value must not move. Same
	// reasoning as jwksStaleMaxAge.
	StaleMaxAge = 7 * 24 * time.Hour

	// MaxDocumentBytes bounds one cached document. The SAML fetch already
	// limits its read to 1 MiB and OIDC discovery to 64 KiB; this is the
	// store's own backstop so a future caller cannot make the cache a
	// disk-exhaustion vector.
	MaxDocumentBytes = 1 << 20

	// MaxEntries bounds the store. An appliance has a handful of IdP
	// profiles; the cap exists so repeated re-pointing of a profile's
	// source URL cannot grow the directory without limit. Eviction is
	// oldest-first by fetch time.
	MaxEntries = 64

	// MaxIndexBytes bounds the index READ, derived rather than picked: at most
	// MaxEntries records, and 4 KiB is far above what one record can serialise to
	// (five short fields, the longest an operator-chosen profile id). It exists
	// because os.ReadFile sizes its buffer from the FILE and json.Unmarshal will
	// populate a map of any size, so MaxEntries bounded writes and bounded
	// NOTHING on the boot/compile read path — the same gap round 11 closed for
	// the document read, left open on its twin, the index (Codex round 13).
	MaxIndexBytes = MaxEntries * 4096
)

Variables

View Source
var ErrNoEntry = errors.New("idpmeta: no usable cached document")

ErrNoEntry means nothing usable is cached for this key: never fetched, past StaleMaxAge, or unreadable. The caller must treat it exactly as it treated a fetch failure before this package existed.

View Source
var ErrRetired = errors.New("idpmeta: profile documents retired since this fetch began")

ErrRetired means PutIfCurrent refused a document because the profile's cached documents were retired (Forget) after the caller took its Generation: the fetch that produced the document belongs to a generation of the profile that a committed deletion has already ended. It is not a storage fault, and the caller's fetch is otherwise unaffected.

Functions

This section is empty.

Types

type Generation

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

Generation is a profile's retirement epoch as observed by one fetch. A caller takes it with Store.Generation BEFORE dialling the IdP and hands it to PutIfCurrent with the document that fetch produced.

It exists for register row IDP-18 (Codex review, round 21): Forget runs at a deletion's COMMIT, but a recovery or revalidation fetch that was already on the wire for the deleted profile could finish afterwards and Put its document back, undoing the committed retirement. Recreating the same id and source during an outage then compiled from the deleted generation's signing material. Forget now advances the epoch, so such a late Put is refused.

The epoch is PASSED IN rather than looked up from the registry because Upsert holds the registry lock across the compile that reaches Put (IDP-10/IDP-11): the store must never call out to ask whether a profile is still live.

type Kind

type Kind string

Kind distinguishes the two document types so one profile that somehow carries both cannot have them collide on disk.

const (
	// KindSAMLMetadata is a SAML IdP EntityDescriptor fetched from a
	// profile's metadata_url.
	KindSAMLMetadata Kind = "saml_metadata"
	// KindOIDCDiscovery is an OIDC discovery document fetched from a
	// profile's issuer.
	KindOIDCDiscovery Kind = "oidc_discovery"
)

The two remote document kinds an interactive IdP profile can depend on.

type Store

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

Store is a durable, bounded last-known-good document cache.

A Store with an empty directory is INERT: Get always reports ErrNoEntry and Put is a no-op returning nil. That is the deliberate posture for a node with no writable state root — the cache is an availability aid, never a correctness dependency, so its absence must degrade to exactly the pre-CHAOS-87 behaviour rather than fail a compile.

func New

func New(dir string) *Store

New returns a Store rooted at dir. An empty dir yields an inert store.

func (*Store) Dir

func (s *Store) Dir() string

Dir reports the store's root directory ("" when inert). Observability and test support only.

func (*Store) Enabled

func (s *Store) Enabled() bool

Enabled reports whether this store can persist anything.

func (*Store) Forget

func (s *Store) Forget(profileID string) error

Forget removes every cached document for profileID, whatever its kind or source.

IT MUST BE CALLED ONLY AFTER A PROFILE DELETION HAS BEEN PERSISTED — the same ordering rule as RetireSuperseded, for the same reason: the registry's deletion is not committed until r.persist returns, and sweeping a profile's documents before that would destroy the fallback of a profile that is still in service if the write then fails.

Two things this closes (register row IDP-11, raised again by CodeRabbit on the owner-decision round). A deleted profile's final entry used to linger forever: it fed the global, oldest-first, liveness-blind evictLocked, so with more than MaxEntries profiles having ever existed a LIVE profile's only fallback could be evicted on behalf of a profile that no longer exists. And because Get is keyed by (profile, kind, source), recreating a profile under the SAME id pointed at the SAME source would be served the PRE-DELETION document during an outage — metadata the operator had deliberately deleted, including whatever signing material it carried, coming back for up to StaleMaxAge.

Deleting rather than moving aside matches evictLocked and RetireSuperseded: the CHAOS-50/62 "quarantine, never delete" rule governs a store whose content is EVIDENCE of a fault, and this content is a cache of a remote document that the next successful fetch reproduces.

func (*Store) Generation

func (s *Store) Generation(profileID string) Generation

Generation returns profileID's current retirement epoch. Take it BEFORE the fetch whose result will be offered to PutIfCurrent: a token taken after the network call cannot detect a Forget that ran while the fetch was in flight.

func (*Store) Get

func (s *Store) Get(profileID string, kind Kind, source string) (doc []byte, age time.Duration, err error)

Get returns the cached document for (profileID, kind, source) together with its age, or ErrNoEntry when nothing usable is cached.

"Usable" means: present, readable, its byte length matches what the index recorded, and its age is within StaleMaxAge. A NEGATIVE age — a document stamped in the future, which a clock rollback produces — is treated as UNUSABLE, not as maximally fresh: the same rule CHAOS-61 established for cluster rate-limit broadcast freshness, and for the same reason (a future stamp otherwise extends the trust window by however far the clock moved).

func (*Store) Len

func (s *Store) Len() int

Len reports how many documents are cached AND STILL SERVABLE — the number a compile could actually fall back on right now. Observability only.

It deliberately does not report len(s.entries): an index entry is not a fallback. See checkServableLocked for what the index cannot see and why the two must give one answer.

COST, and the rule that follows from it: answering honestly means one os.Stat per entry, so this is O(MaxEntries) syscalls on the data volume under s.mu, where it used to be O(1) and volume-independent. That is bounded by a compile-time constant and is dwarfed by Get, which already holds this same lock across a read of up to MaxDocumentBytes — but it does mean the caller inherits the data volume's availability. Its ONE caller is the /metrics exposition, scraped at the collector's interval; do not call it from a request path, and do not raise MaxEntries without re-reading this.

func (*Store) Put

func (s *Store) Put(profileID string, kind Kind, source string, doc []byte) error

Put records doc as the last-known-good document for (profileID, kind, source). A failure to persist is returned but is never fatal to the caller: the fetch it came from already succeeded, so the only cost is that a FUTURE outage has no fallback.

Put does not consult the profile's retirement epoch. A document produced by a network fetch must be recorded through PutIfCurrent instead, so a fetch that straddles a committed deletion cannot write the deleted generation back.

func (*Store) PutIfCurrent

func (s *Store) PutIfCurrent(profileID string, kind Kind, source string, doc []byte, gen Generation) error

PutIfCurrent is Put for a document a fetch produced: it records doc only if profileID has not been retired (Forget) since gen was taken, and otherwise returns ErrRetired and writes nothing. The check and the write happen under one hold of the store lock, so a Forget cannot land between them.

A Generation taken from a different Store (the store was swapped while the fetch was in flight) is refused the same way: the epoch it carries says nothing about this store's retirements.

func (*Store) RetireSuperseded

func (s *Store) RetireSuperseded(profileID string, kind Kind, keepSource string) error

RetireSuperseded drops every cached document for (profileID, kind) EXCEPT the one for keepSource.

IT MUST BE CALLED ONLY AFTER THE PUBLICATION THAT MADE keepSource AUTHORITATIVE HAS BEEN PERSISTED, and that is the whole point of its existing. Round 19 did this retirement inside Put, which looked equivalent and was not: Put is reached from compileIdPProfile, i.e. from the SPECULATIVE half of a registry write, and both of the registry's writers can abandon that candidate afterwards — Upsert when r.persist fails, and ReplaceAll when any later profile fails to validate, fails to compile or fails to persist. In those cases the OLD source stays authoritative, so retiring at Put time deleted the last-known-good of the document still in service and the next outage took a healthy profile dark: the exact pre-CHAOS-87 failure this package exists to prevent, reintroduced by the round that bounded the cache (CodeRabbit + Codex, independently, on the owner-decision round).

COMPILING IS NOT COMMITTING — this section's own rule, from rounds 4 and 6, applied to durable cache state instead of to episode state. The surrounding registry code states the same contract in three places ("the published slice/map must not be touched until persistence succeeds", "the generation is PUBLISHED only here, after the save landed"), and a durable store write is a publication like any other.

What round 19 was right about is unchanged: a superseded entry is UNREACHABLE, since Get is keyed by the profile's CURRENT source, so leaving it behind accumulates one dead key per repoint and the global, oldest-first, liveness-blind evictLocked can then drop the ONLY fallback of a profile that is still live. Moving the retirement to the commit site keeps that bound for every repoint that actually commits — the case that accumulates in practice — and leaves only a refused candidate's own entry behind, which eviction bounds.

keepSource == "" retires NOTHING. A profile with no remote source left (disabled, or switched to inline SAML metadata) is the Forget(profileID) case recorded as register row IDP-11, which needs its own gates.

Deleting rather than moving aside is deliberate and matches evictLocked: the CHAOS-50/62 "quarantine, never delete" rule governs a store whose content is EVIDENCE of a fault, and this content is a cache of a remote document that the next successful fetch reproduces.

func (*Store) SetClockForTest

func (s *Store) SetClockForTest(now func() time.Time)

SetClockForTest injects a clock. Test-only.

Jump to

Keyboard shortcuts

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