Documentation
¶
Overview ¶
Package session provides server-side OIDC sessions for relying parties built on oidclient: the browser holds an opaque session id in a cookie, while the access token and the rotating refresh token live server-side, encrypted at rest. The Manager validates and renews the access token on each request (renewal collapsed under concurrency and guarded against the refresh-token replay race), and revokes sessions on logout.
The package persists nothing itself: the host application supplies a Store implemented over its own database, and a Keyring for the at-rest encryption. See docs/session-design.md in this repository for the rationale.
Index ¶
- Variables
- type Config
- type HandlerConfig
- type Handlers
- type Keyring
- type Login
- type Manager
- func (m *Manager) Authenticate(r *http.Request) (*oidclient.Claims, error)
- func (m *Manager) Destroy(w http.ResponseWriter, r *http.Request)
- func (m *Manager) Start(w http.ResponseWriter, r *http.Request, tokens *oidclient.Tokens, ...) error
- func (m *Manager) Sweep(ctx context.Context) (int64, error)
- type Provider
- type Renewer
- type Session
- type Store
Constants ¶
This section is empty.
Variables ¶
var ErrMalformedCiphertext = errors.New("oidclient/session: malformed ciphertext")
ErrMalformedCiphertext is returned by Open when a blob is too short or otherwise not a value produced by Seal.
var ErrNoActiveKey = errors.New("oidclient/session: keyring has no active key")
ErrNoActiveKey is returned by Seal when the keyring has no active key.
var ErrNoSession = errors.New("oidclient/session: no session")
ErrNoSession means the request carried no usable session: no cookie, an unknown id, or a session past its absolute TTL. Callers treat it as the expected unauthenticated case (proceed anonymous, or redirect to login), distinct from a real fault such as a failed renewal or a store error, which should be logged.
var ErrNotFound = errors.New("oidclient/session: not found")
ErrNotFound is what a Store.Get returns when no row matches the id. The Manager maps it to ErrNoSession.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Store Store
Renewer Renewer
Keyring *Keyring
CookieName string
// AbsoluteTTL is the hard session lifetime regardless of renewal. It must
// stay under the IdP's refresh-token lifetime, or renewal would fail before
// the session expires. Zero uses the 30d default.
AbsoluteTTL time.Duration
// RefreshSkew renews the access token this long before it actually expires,
// so a request never races the expiry boundary. Zero uses the 60s default.
RefreshSkew time.Duration
}
Config builds a Manager. Store, Renewer, Keyring, and CookieName are required.
type HandlerConfig ¶ added in v0.10.0
type HandlerConfig struct {
Provider Provider
Sessions *Manager
// OnAuthenticated runs after a successful code exchange and before the
// session starts: the place to provision or sync a local user from the
// claims. An error aborts the login (no session, a generic 500).
OnAuthenticated func(r *http.Request, claims *oidclient.Claims) (Login, error)
// Finish, when set, completes the response after the session cookie is
// written and the flow cookies are cleared, replacing the default 302. Use
// it for a login that ends differently: a popup that posts a message to
// its opener and closes, or an extra cookie. redirectTo is the final,
// already-sanitized local destination. Finish only runs for a login that
// succeeded.
Finish func(w http.ResponseWriter, r *http.Request, redirectTo string, login Login)
// LogoutRedirect is where Logout sends the browser; it must be a local
// path. Empty means "/".
LogoutRedirect string
// Logf receives diagnostics: upstream error params, failed exchanges and
// session or hook failures. Nil discards them. The HTTP responses never
// carry these details.
Logf func(format string, args ...any)
}
HandlerConfig builds the login handlers. Provider and Sessions are required.
type Handlers ¶ added in v0.10.0
type Handlers struct {
// contains filtered or unexported fields
}
Handlers are the three endpoints of the server-side-session login flow, for a relying party that keeps tokens server-side (see this package's Manager) rather than in a browser cookie. Mount them on routes of your choosing, for example GET /login, GET /auth/callback and POST /logout.
Open-redirect defense is applied on both sides: the "return" parameter is reduced to a local path when Login stores it, and the redirect cookie is reduced again when Callback reads it back, since the cookie can be planted from a sibling subdomain.
func NewHandlers ¶ added in v0.10.0
func NewHandlers(cfg HandlerConfig) (*Handlers, error)
NewHandlers validates cfg and returns the handlers.
func (*Handlers) Callback ¶ added in v0.10.0
Callback completes the flow: it surfaces an upstream error, checks the state against the flow cookie, exchanges the code with the PKCE verifier, runs OnAuthenticated, starts the server-side session, clears the flow cookies and redirects. Every rejection happens before the code is exchanged.
func (*Handlers) Login ¶ added in v0.10.0
Login starts the authorization-code flow (PKCE). It reuses a flow already in progress so two tabs do not overwrite each other's state and fail the callback. The optional "return" query parameter names the local path to land on afterwards.
type Keyring ¶
type Keyring struct {
// contains filtered or unexported fields
}
Keyring holds the AES-256-GCM keys used to encrypt token material at rest. One key is active and used for new Seals; every key in the ring can Open a blob it produced, selected by the key id stamped into the blob. This lets a key roll forward: add a new key, SetActive it, and old rows keep decrypting under their original key until they are next rotated and re-sealed.
A Keyring is safe for concurrent use.
func NewKeyring ¶
func NewKeyring() *Keyring
NewKeyring returns an empty keyring. Add at least one key before use.
func NewKeyringFromBase64 ¶ added in v0.8.0
func NewKeyringFromBase64(encKeyB64, envVarName string, logf func(format string, args ...any)) (*Keyring, error)
NewKeyringFromBase64 builds a Keyring from a base64-encoded 32-byte AES-256 key. It fails open rather than erroring when encKeyB64 is empty or unusable: the returned Keyring still has a working "ephemeral" key, so sessions keep encrypting at rest, they just won't survive a process restart. envVarName names the config source (e.g. "SESSION_ENC_KEY") in the warning so an operator knows what to fix; logf receives that warning, or is a no-op if nil. The only error return is a failure to generate the ephemeral key itself (an unrecoverable rand.Read failure).
func (*Keyring) Add ¶
Add registers a 32-byte (AES-256) key under id. The id is stamped into every blob the key seals, so it must be stable for the life of any data encrypted under it and short (at most 255 bytes). The first key added becomes active.
func (*Keyring) Open ¶
Open decrypts a blob produced by Seal, using the key id stamped into it and verifying aad. It returns an error for an unknown key id, a malformed blob, or a failed authentication (wrong key, tampered ciphertext, or mismatched aad).
type Login ¶ added in v0.11.0
type Login struct {
// DefaultRedirect is the post-login destination used only when the flow
// carried no explicit return target of its own. It must be a local path;
// anything else is ignored.
DefaultRedirect string
// Data is opaque to this package and reaches Finish unchanged. It is how a
// fact the hook learned (the account is new) gets to the code that
// completes the response.
Data any
}
Login is what OnAuthenticated hands back, and what Finish receives.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager owns the server-side session lifecycle.
func (*Manager) Authenticate ¶
Authenticate resolves the request's session cookie to validated claims, renewing the access token when it is absent or near expiry. It returns ErrNoSession when there is no usable session.
func (*Manager) Destroy ¶
func (m *Manager) Destroy(w http.ResponseWriter, r *http.Request)
Destroy revokes the request's session (logout): it deletes the server-side row so the session is dead immediately, and expires the cookie. The refresh token is discarded with the row; it expires at the IdP on its own TTL.
type Provider ¶ added in v0.10.0
type Provider interface {
// Ready reports whether discovery has completed. A lazy client that has
// not reached the IdP yet cannot start or finish a flow.
Ready() bool
AuthorizeURL(state, verifier string) string
RegisterURL(state, verifier string) string
Exchange(ctx context.Context, code, verifier string) (*oidclient.Tokens, *oidclient.Claims, error)
}
Provider is the slice of *oidclient.Client the login handlers need. The concrete client satisfies it; tests substitute a fake.
type Renewer ¶
type Renewer interface {
Validate(ctx context.Context, accessToken string) (*oidclient.Claims, error)
Refresh(ctx context.Context, refreshToken string) (*oidclient.Tokens, *oidclient.Claims, error)
}
Renewer is the slice of *oidclient.Client the Manager needs: validate a stored access token and spend a refresh token. The concrete client satisfies it; tests substitute a fake.
type Session ¶
type Session struct {
ID string // opaque session id; the cookie value
UserSub string // claims.Sub, for the host's user lookup
AccessToken []byte // AES-GCM ciphertext
RefreshToken []byte // AES-GCM ciphertext
Version int64 // compare-and-swap guard for rotation
AccessExpiry time.Time
AbsoluteExpiry time.Time
}
Session is the persisted state the Manager needs. The token fields cross the Store boundary as ciphertext: the Manager seals them before Create and Rotate and opens them after Get, so a Store implementation never handles plaintext tokens.
type Store ¶
type Store interface {
Create(ctx context.Context, s Session) error
// Get returns ErrNotFound when no row matches id.
Get(ctx context.Context, id string) (Session, error)
// Rotate compare-and-swaps on version: it writes the new ciphertext, expiry,
// and version=expectVersion+1 only if the row's current version still equals
// expectVersion. It returns true on success, false on a CAS miss (another
// writer rotated first).
Rotate(ctx context.Context, id string, access, refresh []byte, accessExpiry time.Time, expectVersion int64) (bool, error)
Delete(ctx context.Context, id string) error
DeleteExpired(ctx context.Context, cutoff time.Time) (int64, error)
}
Store is the host-implemented persistence boundary. Implementations own the schema and driver; the Manager owns the values. All token bytes passed in and out are ciphertext.