session

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 7 Imported by: 4 modules, 2 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 manages server-side sessions for both session modes:

  • ModeCookie: the client holds an opaque session secret in a cookie.
  • ModeBearer: the client holds an opaque refresh token and short-lived access tokens. The session is the refresh-token family.

Secrets are 256-bit random values. Stores only ever see their SHA-256 hash, and look sessions up by that hash, so a leaked database does not contain usable credentials and lookups leak nothing useful through timing.

Every refresh rotates the refresh token. Presenting a token that was already rotated revokes the whole session (reuse detection), unless it happens within Config.ReuseGrace (a client that sent two refreshes at once).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalid is returned for unknown, expired, revoked or malformed
	// session secrets, and for a secret used in the wrong mode.
	ErrInvalid = errors.New("session: invalid or expired")

	// ErrReused is returned when an already-rotated refresh token is
	// presented. The session has been revoked.
	ErrReused = errors.New("session: refresh token reuse detected; session revoked")

	// ErrRaced is returned when a just-rotated refresh token is presented
	// again within Config.ReuseGrace. The session is kept.
	ErrRaced = errors.New("session: refresh token was just rotated")

	// ErrNotFound is returned by stores for missing sessions.
	ErrNotFound = errors.New("session: not found")

	// ErrConflict is returned by Store.Rotate when the session's current
	// token hash is no longer the expected one (a concurrent rotation won).
	ErrConflict = errors.New("session: concurrent rotation")
)

Functions

func HashSecret

func HashSecret(secret string) ([]byte, error)

HashSecret validates the encoding of a client-supplied secret and returns its hash. Anything other than exactly 43 base64url characters is rejected before decoding.

func NewSecret

func NewSecret() (secret string, hash []byte)

NewSecret returns a new random secret and its hash.

Types

type Config

type Config struct {
	Cookie Timeouts // default: idle 30m, absolute 7 days
	Bearer Timeouts // default: idle 14 days, absolute 30 days

	// ReuseGrace is how long after a rotation the previous refresh token
	// fails with ErrRaced instead of revoking the session. Default 0: any
	// reuse revokes.
	ReuseGrace time.Duration

	// TouchInterval limits how often LastUsedAt is written in cookie mode.
	// Default 1 minute.
	TouchInterval time.Duration

	// Now returns the current time. Nil means time.Now.
	Now func() time.Time
}

Config configures a Manager. Zero values take the defaults shown.

type Manager

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

Manager implements session lifecycle on top of a Store.

func NewManager

func NewManager(store Store, cfg Config) (*Manager, error)

NewManager returns a Manager.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, subjectID string, mode Mode, attrs map[string]string) (*Session, string, error)

Create starts a session and returns it with its secret (the cookie value or refresh token). The secret is never stored.

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, id string) (*Session, error)

Get returns an active session by public ID, or ErrInvalid.

func (*Manager) Inspect added in v2.1.0

func (m *Manager) Inspect(ctx context.Context, refreshToken string) (*Session, error)

Inspect checks a bearer-mode refresh token without rotating or touching it, and returns its session. It returns ErrInvalid for an unknown, expired or already rotated token; use Refresh to rotate (Refresh also detects reuse of rotated tokens). Store failures are returned as is.

Inspect lets a caller check the session's subject before rotating, so that a failure there does not discard the client's refresh token.

func (*Manager) List

func (m *Manager) List(ctx context.Context, subjectID string) ([]*Session, error)

List returns a subject's active sessions.

func (*Manager) Refresh

func (m *Manager) Refresh(ctx context.Context, refreshToken string) (*Session, string, error)

Refresh rotates a bearer-mode refresh token and returns the session and the new refresh token.

Reuse of an already-rotated token revokes the session and returns ErrReused (or ErrRaced within Config.ReuseGrace). The returned session is non-nil for ErrReused and ErrRaced, so callers can audit it.

func (*Manager) Revoke

func (m *Manager) Revoke(ctx context.Context, secret string) (*Session, error)

Revoke ends the session that owns secret (a cookie secret or refresh token, current or rotated). Unknown secrets are not an error, so logout is idempotent. It returns the revoked session, or nil.

func (*Manager) RevokeAll

func (m *Manager) RevokeAll(ctx context.Context, subjectID, exceptID string) (int, error)

RevokeAll ends all of a subject's sessions except exceptID ("log out everywhere else"); pass "" to end all of them.

func (*Manager) RevokeByID

func (m *Manager) RevokeByID(ctx context.Context, subjectID, sessionID string) error

RevokeByID ends one of subjectID's sessions. Sessions of other subjects are treated as not found, so callers cannot probe for them.

func (*Manager) Rotate

func (m *Manager) Rotate(ctx context.Context, secret string) (*Session, string, error)

Rotate replaces a cookie-mode session secret (for example after a privilege change) and returns the new secret. The old secret stops working.

func (*Manager) Validate

func (m *Manager) Validate(ctx context.Context, secret string) (*Session, error)

Validate checks a cookie-mode session secret and records activity. A secret that was rotated away (see Rotate) is invalid.

type Mode

type Mode string

Mode selects how a client holds its session.

const (
	ModeCookie Mode = "cookie"
	ModeBearer Mode = "bearer"
)

func (Mode) Valid

func (m Mode) Valid() bool

Valid reports whether m is a known mode.

type Session

type Session struct {
	ID        string // public, random identifier; safe to show and log ("sid")
	SubjectID string
	Mode      Mode
	TokenHash []byte // SHA-256 of the current secret

	CreatedAt  time.Time
	LastUsedAt time.Time
	ExpiresAt  time.Time // absolute expiry; idle expiry is LastUsedAt + idle timeout

	Attrs map[string]string // ip, user_agent, provider, ...
}

Session is the server-side record. It never contains a secret.

type Store

type Store interface {
	// Create persists a new session. The ID and TokenHash are unique.
	Create(ctx context.Context, s *Session) error

	// Get returns a session by public ID, or ErrNotFound.
	Get(ctx context.Context, id string) (*Session, error)

	// GetByTokenHash returns the session whose current or previously
	// rotated token has this hash, or ErrNotFound.
	GetByTokenHash(ctx context.Context, hash []byte) (*Session, TokenState, error)

	// Rotate replaces the session's current token hash with newHash, but
	// only if it is still oldHash (otherwise ErrConflict). oldHash is kept
	// as a rotated hash, recorded at time at, for reuse detection. It also
	// sets LastUsedAt to at.
	Rotate(ctx context.Context, id string, oldHash, newHash []byte, at time.Time) error

	// Touch sets LastUsedAt.
	Touch(ctx context.Context, id string, at time.Time) error

	// Delete removes a session and its rotated hashes. Missing is not an error.
	Delete(ctx context.Context, id string) error

	// ListBySubject returns a subject's sessions, including expired ones
	// that have not been purged yet.
	ListBySubject(ctx context.Context, subjectID string) ([]*Session, error)

	// DeleteBySubject removes all of a subject's sessions except exceptID
	// (which may be empty) and returns how many were removed.
	DeleteBySubject(ctx context.Context, subjectID, exceptID string) (int, error)
}

Store persists sessions. Implementations must be safe for concurrent use, and Rotate must be atomic.

type Timeouts

type Timeouts struct {
	Idle     time.Duration // since last use
	Absolute time.Duration // since creation
}

Timeouts bound a session's lifetime.

type TokenState

type TokenState struct {
	// RotatedAt is zero if the hash is the session's current token, and
	// otherwise the time it was rotated away.
	RotatedAt time.Time
}

TokenState describes the token a lookup matched.

Jump to

Keyboard shortcuts

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