session

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 13 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 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 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