sessioncore

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 19 Imported by: 0 modules, 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 sessioncore is what the session types are built from: the base session over the storage and the cookie client, the options every session type takes, session establishment, the API methods every session type shares, impersonation establishment and its guards, the custom data type checks, the password comparison and the login refusal redirect. The root package builds on it and exports what an application needs of it under its own names.

Index

Constants

View Source
const DefaultSessionTimeout = 10 * time.Minute

DefaultSessionTimeout is the idle session timeout unless WithSessionTimeout sets one.

Variables

View Source
var DefaultAttemptLimit = dbtype.SignInAttemptLimit{Failures: 5, Window: 15 * time.Minute, Lock: 15 * time.Minute}

DefaultAttemptLimit is the attempt limit before any option: five failed attempts on a name within fifteen minutes lock the name for fifteen minutes.

View Source
var ErrNoPassword = errors.New("the user has no password")

ErrNoPassword is the comparison failure for a user with no password hash, such as one provisioned for external sign-in only.

View Source
var IdentityAsGiven = IdentityResolver{
	User: func(_ context.Context, user accesstypes.User) (string, impulse.UUID, error) {
		return string(user), impulse.NilUUID, nil
	},
}

IdentityAsGiven is the resolver of Preauth, which keeps no user record: the principal's name is the username, the user ID is zero, and no name can collide with a user.

Functions

func ComparePassword

func ComparePassword(hasher *securehash.SecureHasher, hash *securehash.Hash, password string) (upgrade bool, err error)

ComparePassword checks password against hash with hasher, reporting whether the hash should be upgraded. A nil hash (a user without a password) fails like a wrong password, so the hasher, which dereferences the hash, never sees nil.

func EraseMutate

func EraseMutate[T any](mutate func(data *T) error) func(data any) error

EraseMutate adapts a typed mutate callback to the erased form the storage layer carries across the driver boundary, guarding the type assertion with a clear error.

func EstablishSession

func EstablishSession(
	ctx context.Context, w http.ResponseWriter, base *basesession.BaseSession, sameSite SameSite, create func(ctx context.Context) (impulse.UUID, error),
) (impulse.UUID, error)

EstablishSession creates a session for every session type outside impersonation. create inserts the session row. The auth and XSRF cookies for the new session ID are written only after it succeeds. An error from create is returned unchanged, and no cookie is written.

func ImpersonatedContext

func ImpersonatedContext(ctx context.Context) bool

ImpersonatedContext reports whether ctx carries a validated impersonated session.

func ImpersonationInCtx

func ImpersonationInCtx(ctx context.Context) (*sessioninfo.Impersonation, bool)

ImpersonationInCtx returns the impersonation record of the validated session in ctx, if any. Unlike sessioninfo.ImpersonationFromCtx it does not panic without a session: the establishing call may arrive from a server-to-server context with none, and the library's handlers are exercised without one in tests.

func LogSessionStarted

func LogSessionStarted(ctx context.Context, username string, sessionID impulse.UUID)

LogSessionStarted adds a new session's ID and username to the request's log entry.

func NewBaseSession

func NewBaseSession[O any](storage sessionstorage.BaseStore, cookieKey string, options []O) (*basesession.BaseSession, *internalcookie.Client, error)

NewBaseSession builds the BaseSession a session type runs on, applying the BaseSessionOptions and CookieOptions among options. Other options are left to the caller. The cookie client is also returned, for the OIDC authenticators that write their state cookie through it.

func NewDecoder

func NewDecoder[T any]() *httpio.StructDecoder[T]

NewDecoder builds the decoder for a handler's request body. Construction fails only for a malformed request struct, a programming error, so it panics at startup.

func RedirectRefusedLogin

func RedirectRefusedLogin(w http.ResponseWriter, _ *http.Request, loginURL string, err error)

RedirectRefusedLogin returns the browser to the login page with the reason as a code: loginURL?code=<code>, the code read from err by sessioninfo.LoginRefusalCodeOf. The code is all the URL carries; the error itself goes to the log through the handler's return. See the "Login refusal codes" section of the README.

func RefuseImpersonated

func RefuseImpersonated(ctx context.Context, base *basesession.BaseSession, operation string, selfOperation bool) error

RefuseImpersonated guards the library's identity-mutating handlers. A self operation (the session user's own password, name, address, tokens, approved devices and accepted invitations: everything a person's own-account routes write) is refused in every impersonated session — it would alter the impersonated user's account, and what it changes there outlives the view. Other user-management operations are refused only under a mask, which declares the session read-only. Refusals are evidenced as IdentityOperationBlocked events.

func StartImpersonatedSession

func StartImpersonatedSession[T any](
	ctx context.Context, w http.ResponseWriter, base *basesession.BaseSession, req *ImpersonationRequest, customData []*T, resolve IdentityResolver,
) (impulse.UUID, error)

StartImpersonatedSession is the establishing flow shared by every session type: the type-independent refusals, identity resolution through resolveUser, the record, and the BaseSession step that writes, evidences and sets cookies.

func VerifyCustomDataType

func VerifyCustomDataType[T any](storage sessionstorage.BaseStore) error

VerifyCustomDataType checks at construction that the storage's attached custom session data configuration was built for T. NoCustomData session types skip the check (a configuration may still be attached; its data is reachable via sessioninfo.CustomDataFromCtx).

func VerifyCustomDataTypes

func VerifyCustomDataTypes[S, U any](storage sessionstorage.BaseStore) error

VerifyCustomDataTypes checks that the storage's custom session data and custom user data configurations were built for S and U.

func VerifyCustomUserDataType

func VerifyCustomUserDataType[U any](storage sessionstorage.BaseStore) error

VerifyCustomUserDataType checks at construction that the storage's attached custom user data configuration was built for U. NoCustomData session types skip the check.

Types

type API

type API[SessionData, UserData any] struct {
	Base  *basesession.BaseSession
	Store sessionstorage.BaseStore
	// Users is the store's custom user data surface. It is nil for Preauth.
	Users UserDataStore
	// StoreName names the store interface in wrapped errors, e.g. "AuthStore".
	StoreName string
}

API implements the API methods every session type shares. A type's API builds one per call from its own fields and delegates to it.

func (API[S, U]) ActiveImpersonations

func (a API[S, U]) ActiveImpersonations(ctx context.Context, q *sessioninfo.ImpersonationQuery) ([]*sessioninfo.Impersonation, error)

ActiveImpersonations lists the impersonated sessions live right now, newest first.

func (API[S, U]) Cookie

func (a API[S, U]) Cookie() *cookie.Client

Cookie returns the underlying cookie.Client.

func (API[S, U]) CustomData

func (a API[S, U]) CustomData(ctx context.Context) (S, error)

CustomData returns the current session's custom session data from the context. A session with no custom data row yields a zero-value S.

func (API[S, U]) CustomUserData

func (a API[S, U]) CustomUserData(ctx context.Context, userID impulse.UUID) (U, error)

CustomUserData returns a user's custom user data. A user with no custom data row yields a zero-value U.

func (API[S, U]) DestroyImpersonatedSession

func (a API[S, U]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error

DestroyImpersonatedSession ends one live impersonated session, Revoked.

func (API[S, U]) DestroyImpersonatedSessions

func (a API[S, U]) DestroyImpersonatedSessions(ctx context.Context, actor string) error

DestroyImpersonatedSessions expires every live impersonated session established by actor, ending their records Revoked.

func (API[S, U]) EndImpersonation

func (a API[S, U]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)

EndImpersonation ends the impersonated session in ctx, Released, restoring a local actor's own session when it is still live.

func (API[S, U]) Logout

func (a API[S, U]) Logout(ctx context.Context) error

Logout destroys the current session, announcing an impersonated session's end.

func (API[S, U]) StartImpersonatedSession

func (a API[S, U]) StartImpersonatedSession(
	ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, customData []*S, resolve IdentityResolver,
) (impulse.UUID, error)

StartImpersonatedSession establishes an impersonated session. resolve is the type's identity resolver.

func (API[S, U]) StartSession

func (a API[S, U]) StartSession(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)

StartSession restores the session from its cookie or initializes a new one.

func (API[S, U]) UpdateCustomSessionData

func (a API[S, U]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *S) error) error

UpdateCustomSessionData is the typed transactional read-modify-write of an active session's custom session data.

func (API[S, U]) UpdateCustomUserData

func (a API[S, U]) UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data *U) error) error

UpdateCustomUserData is the typed transactional read-modify-write of a user's custom user data.

func (API[S, U]) ValidateSession

func (a API[S, U]) ValidateSession(ctx context.Context) (context.Context, error)

ValidateSession checks the session cookie and, when it is valid, stores the session data in the context.

type AuthOption

type AuthOption interface {
	// contains filtered or unexported methods
}

AuthOption configures an Auth session.

type AuthOptionMarker

type AuthOptionMarker struct{}

AuthOptionMarker makes the type that embeds it an AuthOption: the root package's own Auth settings option embeds it.

type BaseSessionOption

type BaseSessionOption func(*basesession.BaseSession)

BaseSessionOption configures the base session. It configures every session type.

type CookieOption

type CookieOption internalcookie.Option

CookieOption is a cookie client option. It configures every session type.

type IdentityResolver

type IdentityResolver struct {
	// user resolves a user principal to the session's username and user record ID.
	User func(ctx context.Context, user accesstypes.User) (username string, userID impulse.UUID, err error)
	// actor guards a role principal, whose session carries the actor's own username:
	// it refuses when that name already belongs to a user in this store, so one
	// name never means two users in one session table. Nil when the store keeps no
	// users.
	Actor func(ctx context.Context, actor string) error
	// Accounts reports a store whose people are accounts, named by id in the
	// permission store: there a text that reads as an id is an account's, so an actor
	// from another application whose name reads as one is refused, whatever the
	// principal (refuseActorNamedAsAccount).
	Accounts bool
}

IdentityResolver is what a session type contributes to establishment: how a user principal becomes the session's identity, and whether an actor may hold a role principal's session under their own name.

func UserIdentity

func UserIdentity(storage UserStore) IdentityResolver

UserIdentity is the identity resolver of Auth, whose users are SessionUsers records. A user principal resolves against storage. A foreign actor's role principal is refused when the actor's name is already a user there.

type ImpersonationRequest

type ImpersonationRequest struct {
	// Actor is the authenticated real user the session acts on behalf of. Required.
	Actor string
	// ActorRealm names the application or identity provider that authenticated the
	// actor, when it differs from this application (e.g. "admin-portal"). Leave it empty
	// for a local actor: a user of this application, logged in here, whose own
	// session is SourceSessionID.
	ActorRealm string
	// SourceSessionID is the actor's own session. For a local actor it is required and
	// verified: a live, non-impersonated session of this application carrying the
	// actor's username. It is kept alive by the impersonated session's activity and
	// EndImpersonation returns the actor to it. For a foreign actor it is the session in
	// the source application, optional, for cross-application correlation.
	SourceSessionID impulse.NullUUID
	// Principal is the authorization subject the session evaluates against:
	// accesstypes.UserPrincipal for an impersonated user, or accesstypes.RolePrincipal
	// for a role. Required. A user principal names the person as the permission store
	// does: by the id of their account for a session type whose users are accounts
	// (Auth), by the username for one that keeps none. How it becomes the session's
	// identity depends on the session type — see StartImpersonatedSession on each API.
	Principal accesstypes.Principal
	// Mask attenuates the session to the listed permissions; the zero mask
	// (accesstypes.AllowAll()) leaves it unrestricted, and
	// accesstypes.MaskPermissions(accesstypes.DenyAll(), accesstypes.List, accesstypes.Read)
	// is a read-only session.
	Mask accesstypes.PermissionMask
	// Reason is a free-text justification (a ticket reference, a support note)
	// recorded on the impersonation record. Optional; an application's guard may
	// require it.
	Reason string
	// MaxDuration shortens the session's hard cap below the configured
	// impersonation timeout; zero or a longer value leaves the cap unchanged.
	MaxDuration time.Duration
}

ImpersonationRequest describes the impersonated session to establish. It is a struct so future fields can be added without breaking callers.

type NoCustomData

type NoCustomData struct{}

NoCustomData is the custom data type of session types that do not use custom session data (the SessionData type parameter) or custom user data (the UserData type parameter). Instantiate with NoCustomData for each axis the application does not use.

type PasswordOption

type PasswordOption interface {
	// contains filtered or unexported methods
}

PasswordOption configures the password method.

func AttemptLimit

func AttemptLimit(failures int, window, lock time.Duration) PasswordOption

AttemptLimit sets the attempt limit: failures failed attempts on a name within window lock the name for lock. (default: DefaultAttemptLimit)

func AutoUpgradeHashes

func AutoUpgradeHashes(a bool) PasswordOption

AutoUpgradeHashes controls whether password hashes are upgraded at login. (default: true)

func HashAlgorithm

func HashAlgorithm(hasher securehash.HashAlgorithm) PasswordOption

HashAlgorithm controls the hashing algorithm. (default: securehash.Argon2())

func UsernameIsEmail

func UsernameIsEmail() PasswordOption

UsernameIsEmail declares that the username is the user's email address. (default: the two are apart)

type PasswordSettings

type PasswordSettings struct {
	Hasher      *securehash.SecureHasher
	AutoUpgrade bool
	Attempts    dbtype.SignInAttemptLimit
	// UsernameIsEmail says the username is the user's email address: the users table
	// derives the address from the username, a rename is refused, and a verified
	// address is written as the username.
	UsernameIsEmail bool
}

PasswordSettings are the password method's settings: how passwords are hashed, whether a hash made with an older algorithm is upgraded at login, and the attempt limit failed attempts are held to.

func DefaultPasswordSettings

func DefaultPasswordSettings() PasswordSettings

DefaultPasswordSettings returns the settings before any option: Argon2, upgrading, the default attempt limit.

func (*PasswordSettings) Apply

func (s *PasswordSettings) Apply(opt PasswordOption) bool

Apply applies opt when it is a password settings option and reports whether it was one; a cookie or base session option is not, and is left to the caller.

type PreauthOption

type PreauthOption interface {
	// contains filtered or unexported methods
}

PreauthOption configures a Preauth session.

type SameSite

type SameSite bool

SameSite is how a new session's auth cookie is written.

const (
	// SameSiteStrict is for a session established by a same-site request, such as a
	// login form or an API call.
	SameSiteStrict SameSite = true
	// SameSiteNone is for a session established on a provider's callback. That is a
	// cross-site redirect, which a Strict cookie would not survive. StartSession
	// upgrades it to Strict on the next request.
	SameSiteNone SameSite = false
)

type UserDataStore

type UserDataStore interface {
	CustomUserData(ctx context.Context, userID impulse.UUID) (any, error)
	UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data any) error) error
}

UserDataStore is the custom user data surface of the stores that have a user record.

type UserStore

type UserStore interface {
	User(ctx context.Context, id impulse.UUID) (*sessionstorage.SessionUser, error)
	UserByUserName(ctx context.Context, username string) (*sessionstorage.SessionUser, error)
}

UserStore is the user lookup the identity resolver needs: the Auth store has it.

Jump to

Keyboard shortcuts

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