session

package
v1.0.559 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 18 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 session implements Culvert's HMAC-SHA256-signed session tokens and the revocation machinery behind them (ADR-0002 extraction; engine was session.go in package main).

The package owns: the signing key (with synchronized access — the key is written at runtime by the cluster snapshot sync while the MAC path reads it concurrently) and the pooled HMAC-SHA256 engine bound to it (Decode runs on the proxy authentication hot path, so the verify step is allocation-free; see the MAC engine section below), token encode/decode (base64(json).HMAC), the revocation list (token- and user-level, with lazy expiry eviction, gossip export/merge, and optional disk persistence), the session TTL, and jti generation.

package main keeps: the HTTP cookie helpers (they need isSecureRequest and the Identity hub type), the startup wiring (env/config key priority — env is read in the startup shim per the slice convention), and the Session→Identity conversion (Identity is a main hub type this package must not import).

Index

Constants

View Source
const CookieName = "ps_session"

CookieName is the session cookie name.

View Source
const MaxRevocationEntries = 65536

MaxRevocationEntries caps how many entries an untrusted origin may add. A local, MAC-verified revocation is admitted past it (see the header: refusing one would resurrect a session an operator deliberately killed).

View Source
const MaxRevocationTokenLen = 8192

MaxRevocationTokenLen bounds a revocation key arriving from an UNTRUSTED origin (cluster gossip, the persistence file). It is never applied to a locally MAC-verified revocation.

The bound is DERIVED, not guessed: a key is base64url(json(Session)) and must have travelled as a cookie value, and the de-facto browser limit is 4096 bytes for the whole cookie. 8192 is double that, so every cookie this appliance can issue AND a browser can carry is admitted with margin to spare. TestRevocationBounds_ExceedsAnythingEncodeCanProduce re-measures that against the live Encode rather than trusting this paragraph.

View Source
const MaxSessionLifetime = 7 * 24 * time.Hour

MaxSessionLifetime is the longest session TTL SetTTL admits. No session this appliance issues can expire later than issue time plus this.

Variables

View Source
var ErrRevocationsCorrupt = errors.New("session: revocations file corrupt")

ErrRevocationsCorrupt wraps a revocations file that was READ successfully and could not be PARSED.

The distinction is the caller's whole decision (CHAOS-68): a file we could not read may be perfectly intact behind a transient permission or I/O fault, and quarantining it would move a healthy security-critical file aside; a file we read and could not parse is corrupt, and the next SaveRevocations would atomically OVERWRITE it — destroying the evidence and every revocation in it. Only the second warrants the quarantine path. Same rule as state_corruption.go's, expressed as a sentinel so the caller need not re-classify the error.

View Source
var ErrRevocationsUnquarantined = errors.New("session: the corrupt revocations file could not be quarantined; refusing to overwrite the only copy")

ErrRevocationsUnquarantined is returned by SaveRevocations when the revocations file was read, failed to parse, and could NOT be renamed aside.

quarantineCorruptStateFile's own failure message says "the next save WILL OVERWRITE it" — that warning was the product's only mitigation, and it is a warning to a human who may never read it. The corrupt bytes at the target path are the only copy of whatever revocations the node was enforcing, so this refuses the save instead.

It is DISTINCT from ErrRevocationsUnread because the remedies differ: an unread file needs a permission or mount repair, while this one needs the operator to copy the file elsewhere (its name is too long to rename, the directory is read-only, and so on) before the node can persist again.

View Source
var ErrRevocationsUnread = errors.New("session: revocations file was not read this boot; refusing to overwrite it")

ErrRevocationsUnread is returned by SaveRevocations while this boot could not READ the revocations file. Nothing is written.

It is NOT a persistence failure and must not be counted as one: no write was attempted, the volume may be perfectly healthy, and the condition is already reported by the load-degraded branch of the session_revocation row. Routing it through the persist observers would replace that row's remedy (fix the permission or the mount and restart) with "check free space" — the wrong investigation, which is the defect class AU-36 closed one layer up.

View Source
var Revoked = NewRevocationList()

Revoked is the process-wide revocation list consulted by Decode.

Functions

func Encode

func Encode(s *Session) (string, error)

Encode serialises session data, signs it with HMAC-SHA256, and returns a cookie-safe string: base64(json).HMAC.

func HasSigningKey

func HasSigningKey() bool

HasSigningKey reports whether a key is installed.

func InitRandomKey

func InitRandomKey()

InitRandomKey installs a fresh random 32-byte key. Fails loudly: session machinery that cannot generate randomness is unsafe to keep running.

func IsWriteFenced added in v1.0.365

func IsWriteFenced(err error) bool

IsWriteFenced reports whether err is a refusal to write rather than a failed write. Callers MUST ask this rather than testing one sentinel: a refusal is not a persistence failure, and a call site that recognises only one reason will count the other as a failing volume and send the operator after free space (the AU-36 defect, one layer down).

func MAC

func MAC(data string) string

MAC computes the base64url HMAC-SHA256 of data under the current signing key. Exported for tests that hand-craft legacy-shaped tokens.

func NewJti

func NewJti() string

NewJti returns a fresh 128-bit random session identifier, hex encoded. Stamped into every newly-issued Session by the cookie issuers so two same-second logins for the same user produce distinct b64 payloads (and therefore distinct HMACs and cookie values). The only collision space is 2^128, far beyond birthday-bound concerns for any plausible deployment.

crypto/rand failure is treated the same as InitRandomKey's: fail loudly.

func Refused added in v1.0.340

func Refused(reason RevokeReason) int64

Refused returns the cumulative count of revocation attempts refused for the given reason. An unknown reason reports 0 rather than panicking — this feeds a metrics surface, which must never be the thing that takes the process down.

func ResetRefusalCountersForTest added in v1.0.340

func ResetRefusalCountersForTest()

ResetRefusalCountersForTest zeroes the process-wide refusal counters.

func RevocationLiveAt added in v1.0.365

func RevocationLiveAt(now time.Time, expiry int64) bool

RevocationLiveAt is the EXPORTED face of the same oracle, for the cluster surfaces in package main that carry a RevocationEntry's wire expiry (an int64 Unix second) and cannot reach the unexported predicate.

It exists so those surfaces do not hand-roll the comparison. A second spelling of "has this revocation's lifetime ended?" outside this file is how SEC-REVEXP-1 reopened twice: once in a counting path (AU-60), once in the user-export loop beside an already-fixed token loop (AU-62). Both were a raw `now.After(exp)` — or its transposition `exp.Before(now)` — standing in for this function.

Callers ask whether the revocation must still be HONOURED, which is the question every persistence, gossip and aggregation surface actually has.

func RevocationsPath

func RevocationsPath() string

RevocationsPath returns the configured persistence path ("" = disabled).

func SetPersistFailureObserver added in v1.0.365

func SetPersistFailureObserver(fn func(err error))

SetPersistFailureObserver installs the durability-failure callback (nil clears).

func SetPersistSuccessObserver added in v1.0.365

func SetPersistSuccessObserver(fn func())

SetPersistSuccessObserver installs the durability-RECOVERY callback (nil clears).

It exists for the same reason `ca.RotationPersistSuccessObserver` does: a health surface keyed on a CUMULATIVE failure counter can never recover, so it keeps reporting a security-control failure after the operator has fixed the volume, until the process restarts. The counter is the right instrument for magnitude and the wrong one for state.

A successful save is a genuine recovery here, not merely a fresh write: SaveRevocations persists the COMPLETE live list, so once one succeeds every revocation still in memory is durable again.

func SetRevocationsPath

func SetRevocationsPath(p string)

SetRevocationsPath configures where SaveRevocations/LoadRevocations persist.

func SetSigningKey

func SetSigningKey(key []byte)

SetSigningKey installs the HMAC key. Callers own validation (length/hex); the cluster snapshot path and the startup shim both funnel through here. Synchronized: the DP config-sync path replaces the key at runtime while concurrent requests compute MACs (previously an unguarded global write — latent data race, fixed with this extraction).

func SetTTL

func SetTTL(d time.Duration)

SetTTL updates the session lifetime. Clamped to [15min, MaxSessionLifetime].

func SigningKey

func SigningKey() []byte

SigningKey returns a copy of the current HMAC key (nil when unset). Used by the CP snapshot export (hex-encoded into ConfigSnapshot.SessionHMAC) and by test snapshot/restore helpers.

func TTL

func TTL() time.Duration

TTL returns the current session lifetime.

Types

type RevocationEntry

type RevocationEntry struct {
	Token  string `json:"token"`
	Expiry int64  `json:"expiry"` // Unix timestamp
	// User, when non-empty, makes this a user-level revocation (CHAOS-68).
	User string `json:"user,omitempty"`
	// Prov is the provenance MAC of a locally MAC-verified TOKEN revocation. It
	// is written to the PERSISTENCE FILE only (never by ExportRevocations, so
	// the gossip wire is unchanged) and lets LoadRevocations tell this
	// appliance's own verified entries from untrusted ones. See provenanceMAC.
	// User entries never carry one: they are reloaded through the untrusted
	// bounds, which no genuine account revocation can exceed.
	Prov string `json:"prov,omitempty"`
}

RevocationEntry is a single revocation for gRPC gossip and for the persisted revocations file.

Exactly one of the two revocation KINDS is represented by any entry:

  • a TOKEN revocation (explicit logout) sets Token to the cookie's base64 payload segment and leaves User empty;
  • a USER revocation (the account was deleted) sets User to the username and Token to userRevocationTokenPrefix+User.

User and Prov are `omitempty` and Token is always populated, so the document stays a JSON array that a binary predating CHAOS-68 parses without error. That downgrade compatibility is deliberate: promoting the file to an object would make an older binary fail the whole parse and lose the TOKEN revocations it does understand — trading a gap for a regression.

type RevocationList

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

RevocationList tracks revoked session tokens and user-level revocations.

func NewRevocationList

func NewRevocationList() *RevocationList

NewRevocationList returns an empty list (used by tests to swap the package singleton, mirroring the bl pointer-swap idiom).

func (*RevocationList) Count

func (r *RevocationList) Count() int

Count returns the number of active revoked session TOKENS.

It sweeps first (sweepLocked), so it reports LIVE entries; see the note after UserCount for why.

func (*RevocationList) ExportRevocations

func (r *RevocationList) ExportRevocations() []RevocationEntry

ExportRevocations returns all non-expired revocation entries — BOTH kinds — for syncing and for persistence.

CHAOS-68: this used to walk `r.tokens` only, which made the `users` map invisible to every durable and distributed surface the list has. A deleted account's live sessions were rejected in the memory of the one node that served the DELETE, until that process exited. Both maps are exported now, so a user revocation reaches disk and the fleet by the same paths a logout does.

func (*RevocationList) ExportRevocationsByOrigin added in v1.0.365

func (r *RevocationList) ExportRevocationsByOrigin() (local, other []RevocationEntry)

ExportRevocationsByOrigin is ExportRevocations split by provenance, for the cluster gossip request that has to choose what to send first (AU-50).

local holds the TOKEN entries this process admitted through RevokeVerified, or reloaded from its own file with a valid provenance MAC: the logouts that happened HERE, which no other node can tell the fleet about. other holds every other live entry — tokens learned from gossip or reloaded without provenance, and every ACCOUNT revocation. Account entries are not split because their origin is not tracked (they reload through the untrusted bounds), and the caller ranks them on their own anyway.

The union is exactly what ExportRevocations returns, under the same sweep, so the split decides ORDER and never membership.

func (*RevocationList) FenceWritesUnquarantined added in v1.0.365

func (r *RevocationList) FenceWritesUnquarantined()

FenceWritesUnquarantined refuses every later save because a corrupt file could not be moved aside. Called by the boot path when quarantineCorruptStateFile reports that its rename failed.

func (*RevocationList) IsRevoked

func (r *RevocationList) IsRevoked(token string) bool

IsRevoked reports whether the token is currently revoked, lazily evicting entries whose original expiry has passed.

func (*RevocationList) IsUserRevoked

func (r *RevocationList) IsUserRevoked(username string) bool

IsUserRevoked returns true if all sessions for the given username are revoked.

func (*RevocationList) LoadRevocations

func (r *RevocationList) LoadRevocations() error

LoadRevocations reads revocations from disk and merges them.

func (*RevocationList) MergeRevocations

func (r *RevocationList) MergeRevocations(entries []RevocationEntry) int

MergeRevocations imports remote revocation entries (from other cluster nodes). Only adds entries that are not yet expired and not already present. Returns how many entries were newly applied.

CHAOS-73: this is an UNTRUSTED-ORIGIN path — a peer node chooses the key bytes, the key length and the entry count — so every entry goes through the untrusted admission bounds (key-size bound, far-future refusal, entry cap, counted refusal). The list is swept first so the cap is measured against LIVE entries rather than against expired ones nobody has read since they died.

CHAOS-68: an entry is classified as a USER revocation when it carries an explicit User field, OR when its Token carries userRevocationTokenPrefix. The second form only arises when the entry has passed through a node predating CHAOS-68, which drops the unknown `user` JSON field but preserves the token verbatim; recovering the username from the prefix means one hop through an old node degrades nothing. A token that merely LOOKS like a user entry cannot be a real cookie payload (see userRevocationTokenPrefix), so this classification can never swallow a genuine token revocation. User entries get the same untrusted bounds as tokens (admitUntrustedUserLocked).

func (*RevocationList) Revoke

func (r *RevocationList) Revoke(token string, exp time.Time) bool

Revoke marks a token (its b64 payload) as revoked until exp.

It reports whether the list actually changed, so a caller that persists after revoking does not rewrite the whole file for a no-op. Callers that do not care may ignore the result.

CHAOS-73: this is the UNVERIFIED primitive and it is now internal to the package's own trusted callers plus tests. The logout path must use RevokeVerified, which authenticates the cookie first — see revocation_bounds.go for why the MAC check is the whole security property.

func (*RevocationList) RevokeUser

func (r *RevocationList) RevokeUser(username string)

RevokeUser invalidates all sessions for a username. Active session cookies for this user are rejected until the revocation expiry (max session TTL). Called when a user account is deleted (Finding 5.2).

func (*RevocationList) RevokeVerified added in v1.0.340

func (r *RevocationList) RevokeVerified(cookieValue string) (changed bool, reason RevokeReason)

RevokeVerified records a revocation for a cookie value this appliance signed, and refuses everything else. It reports whether the caller must persist (true only when the list actually changed) and the bounded reason.

The MAC check is the whole security property and it is FIRST: the key is derived from caller-supplied bytes, so nothing may be retained, parsed into a map or written to disk before we know the appliance issued it. The comparison is constant-time, like Decode's.

The expiry is read from the payload only AFTER the MAC verifies, so it is a value we signed rather than one the caller chose — which is what stops a forged entry pinning itself in the map with a far-future expiry the sweeper can never reclaim.

func (*RevocationList) SaveRevocations

func (r *RevocationList) SaveRevocations() error

SaveRevocations writes all non-expired revocations to disk as JSON.

Every failure path is routed through notePersistFailure, so "the revocation is not durable" is a countable event rather than one log line at a call site that returns 200 regardless.

The whole save is serialized by saveMu; see its comment for why.

func (*RevocationList) StatusFor added in v1.0.428

func (r *RevocationList) StatusFor(token, username string) (tokenRevoked, userRevoked bool)

StatusFor answers BOTH revocation questions — is this cookie revoked, and is this account revoked — under ONE acquisition of the list mutex.

── Why this exists ─────────────────────────────────────────────────────────

Decode runs on the PROXY authentication hot path, not just the admin UI: the signed session cookie is the first credential arm resolveRequestAuth tries, so every authenticated request runs it, and it used to consult this list TWICE — IsRevoked(b64), then IsUserRevoked(s.Sub). Both take the same exclusive mutex over a single map lookup, so the two checks serialised the authentication path against itself at twice the necessary rate.

Measured on this package's own BenchmarkDecodeParallel (Go 1.27.4, linux/amd64, 4 cores, -mutexprofile) with an EMPTY revocation list — so the contention is purely on the lock and not on anything under it:

source of mutex delay          share of the whole run
IsUserRevoked                  42.4%
IsRevoked                      30.9%
everything else                26.7%

In the CPU profile of the same run the two checks were 9.4% of cycles, with a further ~8% in runtime.procyield / futex / osyield / tgkill — spinning and parking on that one mutex. Halving the acquisitions halves that, and the saving grows with core count because the contention does.

An empty `username` is answered false without a lookup, which is the guard Decode's call site used to apply itself (`s.Sub != ""`).

It is the preferred entry point for ANY caller that needs both answers; IsRevoked and IsUserRevoked remain for callers that need only one.

── What was measured and rejected, so it is not retried blind ──────────────

Making the READ path lock-free would be worth more than halving the acquisitions, and three shapes were built and measured first. None of them can be had at this size, and the reasons are recorded here rather than rediscovered:

  1. AN RWMUTEX on this field was ~20% SLOWER under contention, not faster (~326 ns/op vs ~275 ns/op for two checks at 4 cores, measured on a 4096-entry list). The critical section is one map lookup, which is shorter than the lock protocol around it: RLock/RUnlock are two atomic read-modify-writes on the SAME cache line, so the line still ping-pongs between cores, with more total atomics and more branches than the mutex. An RWMutex is the right answer for a long read section; this is not one.

  2. AN IMMUTABLE COPY-ON-WRITE VIEW published through an atomic.Pointer — the repository's usual idiom — delivered the read win (2.8x at 4 cores) and cost a full map copy per revocation: Revoke went from 0.6 us to 750 us with 787 KB of garbage at 4096 entries, O(n) per insert. Not affordable HERE: the local MAC-verified path is deliberately uncapped (refusing to revoke a real session is the one failure this control may not have), so n reaches tens of thousands inside one 7-day TTL, and the logout path that would pay it is the same path CHAOS-73 recorded QUADRATIC write amplification on. Adding an O(n) term per insert there is adding to a multiplier that already has an incident.

  3. A sync.Map MIRROR BESIDE the authoritative maps keeps writes O(1) and reads lock-free, and is structurally unsafe at this size: it makes the authoritative map no longer authoritative for the read path, so any writer — including the 47 existing test sites that populate `tokens`/`users` directly under the lock — is silently ineffective.

The lock-free read is still the right end state; it needs the STORE itself to become concurrent (a sync.Map as the sole store, with a maintained count for MaxRevocationEntries and the sweep/export ranges rebuilt over it), which is a redesign of a security-critical structure and belongs in its own reviewed change rather than in a performance pass. These benchmarks (revocation_readpath_bench_test.go) are the harness it should be measured on.

func (*RevocationList) SwapForTest

func (r *RevocationList) SwapForTest() (restore func())

SwapForTest replaces the list's maps with empty ones and returns a restore function. Mirrors the snapshot/restore pattern documented in CLAUDE.md for tests that touch shared revocation state.

func (*RevocationList) Sweep added in v1.0.340

func (r *RevocationList) Sweep()

Sweep drops expired entries now. Exported for the startup path, which wants a load from disk not to carry forward entries that died while we were down.

func (*RevocationList) Tracked added in v1.0.340

func (r *RevocationList) Tracked() int

Tracked returns the number of revocation entries currently held.

func (*RevocationList) UserCount added in v1.0.365

func (r *RevocationList) UserCount() int

UserCount returns the number of active user-level revocations.

Separate from Count because the two answer different operator questions and used to be indistinguishable: `local_revoked` on the cluster API reported only tokens, so a node holding a hundred deleted-account revocations and one holding none serialised identically.

func (*RevocationList) WriteFenced added in v1.0.365

func (r *RevocationList) WriteFenced() bool

WriteFenced reports whether saves are currently refused (either reason; see SaveRevocations). While fenced, a missing backing file is EXPECTED — the operator may have moved the unreadable or corrupt original aside — and no save can recreate it, so callers must not treat its absence as a repairable durability doubt.

type RevokeReason added in v1.0.340

type RevokeReason string

RevokeReason is the BOUNDED classification of a refused or accepted revocation. It reaches a metric label and a log line, so it is a closed set and never carries caller-supplied bytes (WK-12/RS-5).

const (
	// RevokeAccepted — the cookie verified and the entry was recorded.
	RevokeAccepted RevokeReason = "accepted"
	// RevokeAlreadyKnown — verified, but already on the list. No write needed.
	RevokeAlreadyKnown RevokeReason = "already_known"
	// RevokeUnsigned — the HMAC did not verify. Cannot name a session of ours.
	RevokeUnsigned RevokeReason = "unsigned"
	// RevokeMalformed — no separator, or the payload is not a Session.
	RevokeMalformed RevokeReason = "malformed"
	// RevokeExpired — verified, but already past its own expiry. Decode
	// rejects it anyway, so recording it would buy nothing and cost a write.
	RevokeExpired RevokeReason = "expired"
	// RevokeOversize — untrusted origin only: key longer than a cookie this
	// appliance could have issued.
	RevokeOversize RevokeReason = "oversize"
	// RevokeCapacity — untrusted origin only: the entry cap is full.
	RevokeCapacity RevokeReason = "capacity"
	// RevokeFarFuture — untrusted origin only: the expiry lies further ahead
	// than any session this appliance can issue (MaxSessionLifetime plus clock
	// skew). Such an entry is never reclaimed by the sweeper until then, so
	// enough of them would fill MaxRevocationEntries and lock out genuine
	// remote revocations.
	RevokeFarFuture RevokeReason = "far_future"
)

type Session

type Session struct {
	Sub      string   `json:"sub"`
	Email    string   `json:"email"`
	Name     string   `json:"name"`
	Groups   []string `json:"grp,omitempty"`
	Provider string   `json:"pvd"`
	Role     string   `json:"role,omitempty"` // UI admin role: admin|operator|viewer
	Exp      int64    `json:"exp"`            // Unix timestamp
	// Jti is a 128-bit random session identifier (hex-encoded). Added in
	// Phase C5.1 to make the JSON payload unique per login even when two
	// logins for the same user happen in the same wall-clock second —
	// without Jti the (Sub, Role, Exp-in-seconds) tuple yielded a
	// byte-identical payload, identical b64, identical HMAC, and an
	// effectively-revoked cookie if any prior login of that tuple had
	// been revoked. omitempty keeps legacy cookies (issued before C5.1)
	// decoding cleanly: their Jti unmarshals to "" and the field is
	// simply absent on the wire.
	Jti string `json:"jti,omitempty"`
	// Iat is the Unix second the cookie was minted (AU-65). Package main
	// compares it with the asserting profile's SessionsNotBefore cutoff, so
	// re-enabling or re-creating an IdP under the same id does not revive
	// the sessions it minted before the cut. omitempty for the same reason
	// as Jti: a cookie minted before the field existed decodes to 0 and is
	// admitted only by a profile that carries no cutoff, and an older binary
	// ignores the key (json.Unmarshal drops unknown fields; the MAC covers
	// the encoded payload, not the struct).
	Iat int64 `json:"iat,omitempty"`
}

Session is the payload stored inside the signed proxy session cookie. It carries just enough identity data to reconstruct an Identity object without talking to the IdP on every request. (The Session→Identity conversion lives in package main — Identity is a main hub type.)

func Decode

func Decode(raw string) (*Session, error)

Decode parses and verifies a session cookie value. Returns an error when the signature is invalid, the session has expired, or the token/user has been revoked.

Directories

Path Synopsis
Package revsync plans which session-revocation entries ride one SyncRevocations message when the full set does not fit that leg's byte budget (AU-50 request leg, AU-71 reply leg; IM-015, ADR-0049).
Package revsync plans which session-revocation entries ride one SyncRevocations message when the full set does not fit that leg's byte budget (AU-50 request leg, AU-71 reply leg; IM-015, ADR-0049).

Jump to

Keyboard shortcuts

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