session

package
v1.0.364 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 17 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 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 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 RevocationsPath

func RevocationsPath() string

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

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
	// Prov is the provenance MAC of a locally MAC-verified 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.
	Prov string `json:"prov,omitempty"`
}

RevocationEntry is a single revoked session token for gRPC gossip and the persistence file.

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 sessions.

func (*RevocationList) ExportRevocations

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

ExportRevocations returns all non-expired revocation entries for syncing.

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. 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 admitUntrustedLocked (key-size bound, 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.

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. The whole save is serialized by saveMu; see its comment for why.

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.

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.

Jump to

Keyboard shortcuts

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