session

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 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 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

Constants

This section is empty.

Variables

View Source
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.

View Source
var ErrNoActiveKey = errors.New("oidclient/session: keyring has no active key")

ErrNoActiveKey is returned by Seal when the keyring has no active key.

View Source
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.

View Source
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). The
	// returned redirect, when it is a local path, is the destination used
	// only if the flow carried no explicit return target of its own.
	OnAuthenticated func(r *http.Request, claims *oidclient.Claims) (defaultRedirect string, err error)

	// 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

func (h *Handlers) Callback() http.Handler

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

func (h *Handlers) Login() http.Handler

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.

func (*Handlers) Logout added in v0.10.0

func (h *Handlers) Logout() http.Handler

Logout destroys the server-side session, expires its cookie and redirects to LogoutRedirect. It accepts POST only: a state-changing GET can be triggered by any page the user visits, an <img> tag being enough. Render the sign-out control as a form.

func (*Handlers) Register added in v0.10.0

func (h *Handlers) Register() http.Handler

Register is Login, but lands on the IdP's registration page.

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) ActiveID

func (k *Keyring) ActiveID() string

ActiveID returns the id of the active key, or "" if none is set.

func (*Keyring) Add

func (k *Keyring) Add(id string, key []byte) error

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

func (k *Keyring) Open(blob, aad []byte) ([]byte, error)

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

func (*Keyring) Seal

func (k *Keyring) Seal(plaintext, aad []byte) ([]byte, error)

Seal encrypts plaintext under the active key, binding aad (the session id) so the result cannot be decrypted in the context of a different row. The returned blob carries the key id and nonce; store it as-is.

func (*Keyring) SetActive

func (k *Keyring) SetActive(id string) error

SetActive selects which registered key seals new blobs.

type Manager

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

Manager owns the server-side session lifecycle.

func New

func New(cfg Config) (*Manager, error)

New validates cfg and constructs a Manager.

func (*Manager) Authenticate

func (m *Manager) Authenticate(r *http.Request) (*oidclient.Claims, error)

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.

func (*Manager) Start

func (m *Manager) Start(w http.ResponseWriter, r *http.Request, tokens *oidclient.Tokens, claims *oidclient.Claims) error

Start persists a freshly exchanged token set as a new session and writes the opaque session-id cookie. Call it from the OIDC callback after Exchange.

func (*Manager) Sweep

func (m *Manager) Sweep(ctx context.Context) (int64, error)

Sweep deletes sessions past their absolute TTL. Expired rows are also rejected at request time (Authenticate checks AbsoluteExpiry); this just keeps the table from growing. Run it on an interval.

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.

Jump to

Keyboard shortcuts

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