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 ¶
- Variables
- func HashSecret(secret string) ([]byte, error)
- func NewSecret() (secret string, hash []byte)
- type Config
- type Manager
- func (m *Manager) Create(ctx context.Context, subjectID string, mode Mode, attrs map[string]string) (*Session, string, error)
- func (m *Manager) Get(ctx context.Context, id string) (*Session, error)
- func (m *Manager) Inspect(ctx context.Context, refreshToken string) (*Session, error)
- func (m *Manager) List(ctx context.Context, subjectID string) ([]*Session, error)
- func (m *Manager) Refresh(ctx context.Context, refreshToken string) (*Session, string, error)
- func (m *Manager) Revoke(ctx context.Context, secret string) (*Session, error)
- func (m *Manager) RevokeAll(ctx context.Context, subjectID, exceptID string) (int, error)
- func (m *Manager) RevokeByID(ctx context.Context, subjectID, sessionID string) error
- func (m *Manager) Rotate(ctx context.Context, secret string) (*Session, string, error)
- func (m *Manager) Validate(ctx context.Context, secret string) (*Session, error)
- type Mode
- type Session
- type Store
- type Timeouts
- type TokenState
Constants ¶
This section is empty.
Variables ¶
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 ¶
HashSecret validates the encoding of a client-supplied secret and returns its hash. Anything other than exactly 43 base64url characters is rejected before decoding.
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 ¶
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) Inspect ¶ added in v2.1.0
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) Refresh ¶
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 ¶
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 ¶
RevokeAll ends all of a subject's sessions except exceptID ("log out everywhere else"); pass "" to end all of them.
func (*Manager) RevokeByID ¶
RevokeByID ends one of subjectID's sessions. Sessions of other subjects are treated as not found, so callers cannot probe for them.
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.