auth

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 26 Imported by: ? 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 auth is Fletch's authentication toolkit: session stores, signed session cookies, argon2id password hashing, cross-origin protection, and request-context helpers. Its only dependency outside the standard library is golang.org/x/crypto/argon2, which is pure Go.

Index

Constants

View Source
const (
	ImpersonationStart  = "impersonation.start"
	ImpersonationStop   = "impersonation.stop"
	ImpersonationDenied = "impersonation.denied"
)

The actions of an ImpersonationEvent.

View Source
const DefaultCSRFField = "_csrf"

DefaultCSRFField is the form field CSRF reads the token from.

View Source
const DefaultCSRFHeader = "X-CSRF-Token"

DefaultCSRFHeader is the request header CSRF reads the token from. It is checked before the form field, and a request that sends it has its body left unread.

View Source
const DefaultCSRFMaxBodyBytes = 1 << 20

DefaultCSRFMaxBodyBytes is the largest form body CSRF parses to find the token field, the same as the router's default form limit.

View Source
const MinSecretLen = 32

MinSecretLen is the shortest accepted HMAC secret.

View Source
const Redacted = "[redacted]"

Redacted replaces secret setting values in a Description.

Variables

View Source
var (
	// ErrNotFound is returned by a SessionStore for an unknown or expired id.
	ErrNotFound = errors.New("auth: not found")
	// ErrUnauthenticated means the request carries no valid credentials.
	ErrUnauthenticated = errors.New("auth: unauthenticated")
	// ErrForbidden means the caller is known but not allowed.
	ErrForbidden = errors.New("auth: forbidden")
)
View Source
var (
	// ErrAlreadyImpersonating refuses an impersonation started from an
	// impersonation session.
	ErrAlreadyImpersonating = errors.New("auth: already impersonating")
	// ErrSelfImpersonation refuses an impersonation of the actor's own user.
	ErrSelfImpersonation = errors.New("auth: cannot impersonate yourself")
	// ErrNotImpersonating is Impersonation.Stop on a session that is not an
	// impersonation.
	ErrNotImpersonating = errors.New("auth: not impersonating")
)
View Source
var ErrCSRF = errors.New("auth: invalid csrf token")

ErrCSRF is the reason an unsafe request was rejected.

View Source
var ErrInvalidHash = errors.New("auth: invalid password hash")

ErrInvalidHash is returned by Verify for a malformed encoded hash.

View Source
var ErrTooManyAttempts = errors.New("auth: too many login attempts")

ErrTooManyAttempts is LoginThrottle.Allow refusing a login attempt.

Functions

func CSRF

func CSRF(secret []byte, opts ...CSRFOption) (func(http.Handler) http.Handler, error)

CSRF returns middleware that protects unsafe requests with a signed double-submit token. The cookie holds "<token>.<hmac(token)>"; forms and scripts echo the token in the field or header. The signature stops a planted cookie from being accepted, the constant-time comparison stops timing leaks. It complements OriginProtection; use both. secret must be at least MinSecretLen bytes.

func CSRFError

func CSRFError(r *http.Request) error

CSRFError returns why CSRF rejected the request; it is meant for a custom error handler.

func CSRFToken

func CSRFToken(ctx context.Context) string

CSRFToken returns the token CSRF made available to the request, or "".

func CSRFTokenFromRequest

func CSRFTokenFromRequest(r *http.Request) string

CSRFTokenFromRequest is CSRFToken(r.Context()).

func ClientIP added in v0.3.0

func ClientIP(r *http.Request) string

ClientIP returns the host part of r.RemoteAddr: the client address once router.TrustedProxies has rewritten it behind a proxy.

func Impersonator added in v0.3.0

func Impersonator(ctx context.Context) (string, bool)

Impersonator returns the real user behind an impersonated request: the value WithImpersonator stored. User is the impersonated user.

func IsImpersonating added in v0.3.0

func IsImpersonating(ctx context.Context) bool

IsImpersonating reports whether ctx carries an impersonator.

func NewSessionID

func NewSessionID() (string, error)

NewSessionID returns 256 random bits as hex.

func OriginProtection

func OriginProtection(trusted ...string) (func(http.Handler) http.Handler, error)

OriginProtection rejects cross-origin state-changing requests using http.CrossOriginProtection. trusted lists extra origins such as "https://app.example.com" that may submit cross-origin.

func OriginProtectionFunc added in v0.3.0

func OriginProtectionFunc(trust func(r *http.Request, origin string) bool, trusted ...string) (func(http.Handler) http.Handler, error)

OriginProtectionFunc is OriginProtection that also asks trust about a cross-origin request the static rules reject, such as one from a tenant's custom domain. trust sees only requests that carry an Origin header; a cross-site request without one is still rejected.

func RequireUser

func RequireUser(next http.Handler) http.Handler

RequireUser answers 401 unless SessionMiddleware found a user.

func SessionMiddleware

func SessionMiddleware(a Authenticator) func(http.Handler) http.Handler

SessionMiddleware authenticates each request with a and, on success, puts the subject in the request context (see User). Unauthenticated requests pass through without a user; wrap handlers that need one in RequireUser. Any other authentication error is a 500.

func SortSessions

func SortSessions(ss []Session)

SortSessions orders sessions by expiry (no expiry last), then id. Store implementations use it to give ListByUser a stable order.

func User

func User(ctx context.Context) (string, bool)

User returns the subject stored by WithUser.

func WithCSRFToken

func WithCSRFToken(ctx context.Context, token string) context.Context

WithCSRFToken returns a context that carries token.

func WithImpersonator added in v0.3.0

func WithImpersonator(ctx context.Context, impersonatorID string) context.Context

WithImpersonator returns a context that records that the request's user is being impersonated by impersonatorID. SessionMiddleware sets it from Session.ImpersonatorID.

func WithSession

func WithSession(ctx context.Context, s Session) context.Context

WithSession returns a context that carries the authenticated session.

func WithUser

func WithUser(ctx context.Context, subject string) context.Context

WithUser returns a context that carries the authenticated subject.

Types

type Authenticator

type Authenticator interface {
	// Authenticate returns the subject of the request, or ErrUnauthenticated.
	Authenticate(r *http.Request) (string, error)
	// Describe reports the provider for AX inspection.
	Describe() Description
}

Authenticator identifies the caller of a request.

func NoAuth

func NoAuth() Authenticator

NoAuth returns an Authenticator that accepts every request with an empty subject, for apps and tests that have no users.

type CSRFOption

type CSRFOption func(*csrfConfig)

CSRFOption configures CSRF.

func WithCSRFContext

func WithCSRFContext(fn func(ctx context.Context, token string) context.Context) CSRFOption

WithCSRFContext lets a caller copy the token into its own context key on every request. It may be given more than once; the hooks run in order.

func WithCSRFCookie

func WithCSRFCookie(name string) CSRFOption

WithCSRFCookie sets the cookie name. The default is "fletch_csrf".

func WithCSRFErrorHandler

func WithCSRFErrorHandler(h http.Handler) CSRFOption

WithCSRFErrorHandler answers rejected requests instead of the default 403. CSRFError(r) reports why.

func WithCSRFField

func WithCSRFField(name string) CSRFOption

WithCSRFField sets the form field. The default is "_csrf".

func WithCSRFHeader

func WithCSRFHeader(name string) CSRFOption

WithCSRFHeader sets the request header. The default is "X-CSRF-Token".

func WithCSRFMaxBodyBytes

func WithCSRFMaxBodyBytes(n int64) CSRFOption

WithCSRFMaxBodyBytes sets the largest urlencoded or multipart body CSRF reads when the token comes in the form field; a larger body is answered 413. The default is DefaultCSRFMaxBodyBytes. A urlencoded body is read, checked, and handed on unparsed, so the route still applies its own form limit. A multipart form is parsed here and is what the handler sees, so for multipart this limit replaces the route's: raise it, or send the token in the header, for larger uploads.

func WithCSRFPath

func WithCSRFPath(p string) CSRFOption

WithCSRFPath sets the cookie path. The default is "/".

func WithCSRFSecure

func WithCSRFSecure(secure bool) CSRFOption

WithCSRFSecure sets the Secure attribute of the cookie. It defaults to true; turn it off only for plain-HTTP local development.

type CookieOption

type CookieOption func(*SessionCookie)

CookieOption configures a SessionCookie.

func WithAbsoluteTimeout

func WithAbsoluteTimeout(d time.Duration) CookieOption

WithAbsoluteTimeout caps a session at d after Session.AuthTime, however active it is, so a clinical or financial app forces a fresh login.

func WithCookieClock

func WithCookieClock(now func() time.Time) CookieOption

WithCookieClock sets the clock used for session expiry. Give it the clock of the session store (auth.WithClock); two clocks that differ make every request after login look signed out. SessionCookies made by fletch.App.SessionCookie share the app's clock.

func WithCookieDomain added in v0.3.0

func WithCookieDomain(domain string) CookieOption

WithCookieDomain sets the Domain attribute of the session cookie, such as ".platform.com" to share a session across its subdomains. The default is host-only.

func WithCookieDomainFunc added in v0.3.0

func WithCookieDomainFunc(fn func(*http.Request) string) CookieOption

WithCookieDomainFunc sets the Domain attribute of the session cookie per request: fn might return ".platform.com" on a platform subdomain and "", host-only, on a tenant's custom domain. Logout clears the cookie with the same Domain.

func WithCookieName

func WithCookieName(name string) CookieOption

WithCookieName sets the cookie name. The default is "fletch_session".

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) CookieOption

WithIdleTimeout makes sessions slide: each one expires d after its last authenticated request instead of WithTTL after login, never past the WithAbsoluteTimeout cap. The store is written at most once per tenth of d.

func WithOnSessionRevoked

func WithOnSessionRevoked(fn func(bindingKey string)) CookieOption

WithOnSessionRevoked calls fn with the id of every session that Logout, Login (replacing the request's session), or RevokeUser ends, so Live sessions bound with BindingKey can be closed (live.Handler.EvictBinding). A session that simply expires is not reported. fn must not block.

func WithPath

func WithPath(p string) CookieOption

WithPath sets the cookie path. The default is "/".

func WithSecure

func WithSecure(secure bool) CookieOption

WithSecure sets the Secure attribute. It defaults to true; turn it off only for plain-HTTP local development.

func WithTTL

func WithTTL(d time.Duration) CookieOption

WithTTL sets the session lifetime used by Login. The default is 30 days.

type Description

type Description struct {
	Provider string            `json:"provider"`
	Settings map[string]string `json:"settings,omitempty"`
}

Description is what an auth component reports about itself for `fletch ax inspect`. Settings are already redacted.

type HasherOption

type HasherOption func(*PasswordHasher)

HasherOption configures a PasswordHasher.

func WithArgon2

func WithArgon2(memoryKiB, passes uint32, threads uint8) HasherOption

WithArgon2 sets the argon2id cost: memory in KiB, passes, and threads.

type Impersonation added in v0.3.0

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

Impersonation lets an authorized user act as another through a SessionCookie. Starting parks the actor's session server-side, under a new id, and issues an impersonation session (Subject the target, ImpersonatorID the actor) under another new id; stopping restores the actor's session under a third. Ending the parked session, by RevokeUser or RevokeOthers on the actor, ends the impersonation on its next request.

func NewImpersonation added in v0.3.0

func NewImpersonation(c *SessionCookie, authorize func(ctx context.Context, actor, target string) error, record func(ctx context.Context, e ImpersonationEvent) error) (*Impersonation, error)

NewImpersonation returns an Impersonation over c. authorize decides whether actor may impersonate target, returning an error to refuse; record writes each start, stop, and denial, and a start whose record fails is undone. Both are required.

func (*Impersonation) Start added in v0.3.0

func (im *Impersonation) Start(w http.ResponseWriter, r *http.Request, target, reason string) error

Start makes the request's user act as target and sets the new session's cookie on w. reason is recorded with the event. It returns ErrUnauthenticated without a session, ErrAlreadyImpersonating from an impersonation session, ErrSelfImpersonation for the actor's own user, or authorize's error; each refusal is recorded as ImpersonationDenied.

func (*Impersonation) Stop added in v0.3.0

Stop ends the request's impersonation: it restores the impersonator's session under a new id, deletes the impersonation session, and sets the cookie on w. It returns ErrNotImpersonating for any other session, and ErrUnauthenticated without one. The impersonation has ended even when the returned error is a failed record.

type ImpersonationEvent added in v0.3.0

type ImpersonationEvent struct {
	Action string
	Actor  string
	Target string
	IP     string
	Reason string
	// Err is why a start was denied.
	Err  error
	Time time.Time
}

ImpersonationEvent is one audited impersonation step. Actor is always the real user, never the impersonated one. admin.ImpersonationAudit records it as an audit.Event.

type LoginThrottle added in v0.3.0

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

LoginThrottle limits failed logins. It counts failures per normalized email and client IP pair, so one attacker cannot lock a user out from everywhere, and, with WithIPLimit, per IP across every email, which catches credential stuffing. After WithMaxAttempts failures a key is refused for WithLockout.

Call Allow before checking the password, RecordFailure when it is wrong (or the user does not exist), and Reset after a successful login.

func NewLoginThrottle added in v0.3.0

func NewLoginThrottle(opts ...ThrottleOption) (*LoginThrottle, error)

NewLoginThrottle returns a LoginThrottle.

func (*LoginThrottle) Allow added in v0.3.0

func (t *LoginThrottle) Allow(ctx context.Context, email, ip string) (time.Duration, error)

Allow reports whether a login for email from ip may be tried. When it may not, it returns ErrTooManyAttempts and how long until it may.

func (*LoginThrottle) RecordFailure added in v0.3.0

func (t *LoginThrottle) RecordFailure(ctx context.Context, email, ip string) error

RecordFailure counts a failed login for email from ip.

func (*LoginThrottle) Reset added in v0.3.0

func (t *LoginThrottle) Reset(ctx context.Context, email, ip string) error

Reset clears the failures of email from ip, after a successful login. The per-IP count is kept: one good password must not reset a credential stuffing run.

type PasswordHasher

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

PasswordHasher hashes and verifies passwords with argon2id. The encoded form is the standard PHC string, so parameters travel with each hash and old hashes keep verifying after the defaults change.

func NewPasswordHasher

func NewPasswordHasher(opts ...HasherOption) *PasswordHasher

NewPasswordHasher returns a hasher with the OWASP-recommended argon2id defaults (64 MiB, 1 pass, 4 threads) unless overridden.

func (*PasswordHasher) Describe

func (h *PasswordHasher) Describe() Description

Describe reports the provider for AX inspection.

func (*PasswordHasher) Hash

func (h *PasswordHasher) Hash(password string) (string, error)

Hash returns the encoded argon2id hash of password with a fresh salt.

func (*PasswordHasher) Verify

func (h *PasswordHasher) Verify(password, encoded string) (bool, error)

Verify reports whether password matches encoded, comparing in constant time.

type Session

type Session struct {
	ID        string            `json:"id"`
	Subject   string            `json:"subject"`
	Data      map[string]string `json:"data,omitempty"`
	ExpiresAt time.Time         `json:"expires_at"`
	// AuthTime is when the user last proved who they are (OIDC auth_time).
	// SessionCookie sets it at login and caps sliding expiry from it.
	AuthTime time.Time `json:"auth_time,omitzero"`
	// AMR lists the authentication methods used, such as "pwd" and "mfa".
	AMR []string `json:"amr,omitempty"`
	// CreatedAt is when the session was issued.
	CreatedAt time.Time `json:"created_at,omitzero"`
	// LastSeenAt is when the session last authenticated a request, kept to
	// within a minute by stores that implement SessionManager.
	LastSeenAt time.Time `json:"last_seen_at,omitzero"`
	// IP is the client address of the last request that wrote the session.
	IP string `json:"ip,omitempty"`
	// UserAgent is the User-Agent of the login request, cut to 512 bytes.
	UserAgent string `json:"user_agent,omitempty"`
	// ImpersonatorID is the real user behind an impersonation session;
	// Subject is the user being impersonated. See Impersonation.
	ImpersonatorID string `json:"impersonator_id,omitempty"`
	// ImpersonatorSessionID is the impersonator's own session, kept while
	// they impersonate and restored by Impersonation.Stop. Revoking it ends
	// the impersonation.
	ImpersonatorSessionID string `json:"impersonator_session_id,omitempty"`
}

Session is server-side state for one signed-in browser.

func SessionFromContext

func SessionFromContext(ctx context.Context) (Session, bool)

SessionFromContext returns the session stored by WithSession.

type SessionActivity added in v0.3.0

type SessionActivity struct {
	LastSeenAt time.Time
	// IP replaces the session's IP unless it is empty.
	IP string
	// ExpiresAt replaces the session's expiry unless it is zero.
	ExpiresAt time.Time
}

SessionActivity is what SessionManager.TouchActivity writes.

type SessionAuthenticator

type SessionAuthenticator interface {
	Authenticator
	AuthenticateSession(r *http.Request) (Session, error)
}

SessionAuthenticator is an Authenticator that can return the whole session; SessionCookie is one. SessionMiddleware uses it to make the session available through SessionFromContext without a second load.

type SessionCookie

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

SessionCookie authenticates requests with an HMAC-SHA256 signed cookie that carries a session id; the session itself lives in a SessionStore. It implements Authenticator.

func NewSessionCookie

func NewSessionCookie(store SessionStore, secret []byte, opts ...CookieOption) (*SessionCookie, error)

NewSessionCookie returns a SessionCookie that signs with secret, which must be at least MinSecretLen bytes.

func (*SessionCookie) Authenticate

func (c *SessionCookie) Authenticate(r *http.Request) (string, error)

Authenticate returns the subject of the request's session, or ErrUnauthenticated when the cookie is missing, forged, or expired.

func (*SessionCookie) AuthenticateSession

func (c *SessionCookie) AuthenticateSession(r *http.Request) (Session, error)

AuthenticateSession is Authenticate returning the whole session.

func (*SessionCookie) BindingKey

func (c *SessionCookie) BindingKey(r *http.Request) string

BindingKey returns the id of the request's session, or "" without a valid cookie. Use it with live.WithSessionBinding: it is the key WithOnSessionRevoked reports.

func (*SessionCookie) Describe

func (c *SessionCookie) Describe() Description

Describe reports the provider for AX inspection. The signing secret is never included.

func (*SessionCookie) ListSessions added in v0.3.0

func (c *SessionCookie) ListSessions(ctx context.Context, userID string) ([]SessionInfo, error)

ListSessions returns the live sessions of userID, soonest expiry first. The one SessionFromContext(ctx) holds is marked Current. The store must implement UserSessionStore.

func (*SessionCookie) Login

func (c *SessionCookie) Login(w http.ResponseWriter, r *http.Request, subject string, data map[string]string) error

Login creates a session for subject, stores it, and sets the cookie on w. The session the request's cookie names, if any, is deleted: a login never leaves an earlier session usable by whoever else holds its cookie.

func (*SessionCookie) LoginSession

func (c *SessionCookie) LoginSession(w http.ResponseWriter, r *http.Request, sess Session) error

LoginSession is Login for a session with AuthTime and AMR, such as one from an OIDC login. ID and ExpiresAt are set here; a zero AuthTime is now. CreatedAt, IP, and UserAgent default to now and the request's (see ClientIP).

func (*SessionCookie) Logout

Logout deletes the request's session and clears the cookie. Logging out of an impersonation also ends the impersonator's session.

func (*SessionCookie) RevokeOthers added in v0.3.0

func (c *SessionCookie) RevokeOthers(ctx context.Context, userID, keepSessionID string) error

RevokeOthers deletes every session of userID except keepSessionID, such as "sign out everywhere else" with the current session's id, and reports each to WithOnSessionRevoked. The store must implement UserSessionStore; a SessionManager does it in one step.

func (*SessionCookie) RevokeSession added in v0.3.0

func (c *SessionCookie) RevokeSession(ctx context.Context, userID, handle string) error

RevokeSession deletes the session of userID that handle names, from SessionInfo.Handle, and reports it to WithOnSessionRevoked. A handle that names no session of userID is ErrNotFound, so a user can end only their own sessions.

func (*SessionCookie) RevokeUser

func (c *SessionCookie) RevokeUser(ctx context.Context, userID string) error

RevokeUser deletes every session of userID, such as after a password change or an admin lock, and reports each one to WithOnSessionRevoked. The store must implement UserSessionStore.

func (*SessionCookie) Session

func (c *SessionCookie) Session(r *http.Request) (Session, bool)

Session returns the request's loaded session, so an app can read its id and Data. ok is false when the request has no valid session.

type SessionInfo added in v0.3.0

type SessionInfo struct {
	Handle string `json:"handle"`
	// Current is true for the session in the context, from SessionMiddleware.
	Current    bool      `json:"current"`
	IP         string    `json:"ip,omitempty"`
	UserAgent  string    `json:"user_agent,omitempty"`
	CreatedAt  time.Time `json:"created_at,omitzero"`
	LastSeenAt time.Time `json:"last_seen_at,omitzero"`
	ExpiresAt  time.Time `json:"expires_at,omitzero"`
	// Impersonated marks a session in which someone else acts as the user.
	// Its IP and UserAgent, the impersonator's, are left out.
	Impersonated bool `json:"impersonated,omitempty"`
}

SessionInfo describes one session for a "your devices" page. It carries no session id: Handle names the session to RevokeSession and cannot be turned back into a credential.

type SessionManager added in v0.3.0

type SessionManager interface {
	UserSessionStore
	// TouchActivity records activity on an existing, unexpired session
	// without rewriting it. A missing or expired id is ErrNotFound.
	TouchActivity(ctx context.Context, id string, a SessionActivity) error
	// RevokeOthers deletes every session of userID except keepID and
	// returns the ids it deleted.
	RevokeOthers(ctx context.Context, userID, keepID string) ([]string, error)
}

SessionManager is an optional extension of UserSessionStore for stores that back a "your devices" page. MemorySessions and DBSessions implement it; SessionCookie falls back to ListByUser and Delete for other UserSessionStores, and then does not record LastSeenAt.

type SessionOption

type SessionOption func(*sessionConfig)

SessionOption configures a session store.

func WithClock

func WithClock(now func() time.Time) SessionOption

WithClock sets the clock used for expiry. A store and the SessionCookie that issues its sessions must read the same clock (see WithCookieClock), or a cookie can carry an expiry the store already considers past; fletch.WithClock passes one clock to the defaults it builds.

func WithPostgres

func WithPostgres() SessionOption

WithPostgres makes DBSessions use $1 placeholders instead of ?.

func WithTable

func WithTable(name string) SessionOption

WithTable sets the session table name. The default is fletch_sessions.

type SessionPruner

type SessionPruner interface {
	// Prune deletes every session that has expired at before and reports
	// how many it deleted.
	Prune(ctx context.Context, before time.Time) (int64, error)
}

SessionPruner is an optional extension of SessionStore for stores that keep expired sessions until they are read. MemorySessions and DBSessions implement it; auth/redis expires keys on the server instead.

type SessionStore

type SessionStore interface {
	// Load returns the session, or ErrNotFound when it is missing or expired.
	Load(ctx context.Context, id string) (Session, error)
	// Save creates or replaces the session with s.ID.
	Save(ctx context.Context, s Session) error
	// Delete removes the session. Deleting a missing id is not an error.
	Delete(ctx context.Context, id string) error
	// Describe reports the provider for AX inspection.
	Describe() Description
}

SessionStore persists sessions. Implementations must not do I/O in their constructors.

func DBSessions

func DBSessions(db *sql.DB, opts ...SessionOption) SessionStore

DBSessions returns a session store backed by the fletch_sessions table of db, which the app owns. It works with SQLite and, with WithPostgres, Postgres. The table is created on first use.

func MemorySessions

func MemorySessions(opts ...SessionOption) SessionStore

MemorySessions returns an in-process session store.

type SessionToucher

type SessionToucher interface {
	// Touch sets the expiry of an existing, unexpired session to exp. It
	// never creates a session: a missing or expired id is ErrNotFound.
	Touch(ctx context.Context, id string, exp time.Time) error
}

SessionToucher is an optional extension of SessionStore for stores that can move a session's expiry without rewriting it. SessionCookie uses it for sliding expiry so a request that loaded a session just before a concurrent Logout or RevokeUser cannot write the revoked session back. MemorySessions, DBSessions, and auth/redis implement it.

type ThrottleOption added in v0.3.0

type ThrottleOption func(*LoginThrottle)

ThrottleOption configures a LoginThrottle.

func WithIPLimit added in v0.3.0

func WithIPLimit(n int) ThrottleOption

WithIPLimit also limits failures from one IP across all emails to n per window. The default, 0, has no per-IP limit; set it above the number of users that share an office or carrier NAT.

func WithLockout added in v0.3.0

func WithLockout(d time.Duration) ThrottleOption

WithLockout sets how long a key is refused after the failure that reached its limit. The default is the window.

func WithMaxAttempts added in v0.3.0

func WithMaxAttempts(n int) ThrottleOption

WithMaxAttempts sets the failures allowed per email and IP in a window. The default is 5.

func WithThrottleClock added in v0.3.0

func WithThrottleClock(now func() time.Time) ThrottleOption

WithThrottleClock sets the clock. The default is time.Now.

func WithThrottleStore added in v0.3.0

func WithThrottleStore(s ThrottleStore) ThrottleOption

WithThrottleStore sets where counters live, such as Redis shared by every replica. The default is NewMemoryThrottleStore(100000), per process.

func WithWindow added in v0.3.0

func WithWindow(d time.Duration) ThrottleOption

WithWindow sets how long failures count. The default is 15 minutes.

type ThrottleStore added in v0.3.0

type ThrottleStore interface {
	// Failures returns the failures recorded for key and when the count
	// ends; a key with no count, or one that ended by now, has zero.
	Failures(ctx context.Context, key string, now time.Time) (n int, until time.Time, err error)
	// AddFailure adds one failure to key and returns the new count and its
	// end. A key with no live count starts at 1 and ends at now+window.
	AddFailure(ctx context.Context, key string, now time.Time, window time.Duration) (n int, until time.Time, err error)
	// Extend moves the end of key's count to until when that is later.
	Extend(ctx context.Context, key string, until time.Time) error
	// Reset clears key.
	Reset(ctx context.Context, key string) error
}

ThrottleStore keeps LoginThrottle's failure counters. Each key counts failures in a window that starts with its first failure. Implementations must be safe for concurrent use; Redis or Postgres versions are a few lines over INCR with PEXPIREAT or an upsert.

func NewMemoryThrottleStore added in v0.3.0

func NewMemoryThrottleStore(maxKeys int) ThrottleStore

NewMemoryThrottleStore returns an in-process ThrottleStore that holds at most maxKeys counters. When it is full it drops ended counters, then the counter with the fewest failures, so locked keys go last.

type UserSessionStore

type UserSessionStore interface {
	SessionStore
	// DeleteByUser removes every session of userID. A user with none is
	// not an error.
	DeleteByUser(ctx context.Context, userID string) error
	// ListByUser returns the live sessions of userID, soonest expiry
	// first, then by id.
	ListByUser(ctx context.Context, userID string) ([]Session, error)
}

UserSessionStore is an optional extension of SessionStore for stores that can find sessions by user. A user is the Session.Subject. Check for it with a type assertion; MemorySessions, DBSessions, and auth/redis implement it.

Directories

Path Synopsis
apikey module
Package authtest is the conformance suite every auth.SessionStore must pass.
Package authtest is the conformance suite every auth.SessionStore must pass.
dbcheck module
Package flash carries one-time messages across a redirect in an HMAC-SHA256 signed, short-lived cookie.
Package flash carries one-time messages across a redirect in an HMAC-SHA256 signed, short-lived cookie.
Package handoff moves a signed-in user from a central platform host to another host the app serves, such as a customer's own domain.
Package handoff moves a signed-in user from a central platform host to another host the app serves, such as a customer's own domain.
jwt module
oauth module
oidc module
passkey module
rbac module
redis module
Package seal makes and opens encrypted, expiring tokens for invite, unsubscribe, and password-reset links.
Package seal makes and opens encrypted, expiring tokens for invite, unsubscribe, and password-reset links.
Package signedurl makes and checks HMAC-SHA256 signed, expiring URLs, for email verification, unsubscribe, and "this was not me" links.
Package signedurl makes and checks HMAC-SHA256 signed, expiring URLs, for email verification, unsubscribe, and "this was not me" links.
totp module

Jump to

Keyboard shortcuts

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