auth

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 26 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 auth signs people in and keeps their sessions (C-03): local sign-in with argon2id passwords and its throttling, the second step of a user with TOTP and the limited session states, sessions in PostgreSQL carried in the muster_session cookie, the CSRF token derived from the session, the password change, the client address behind trusted proxies, and the Permissions of the Roles. Every session time follows the business clock.

Index

Constants

View Source
const (
	// PermissionNone is a public operation, or one the request authenticates itself.
	PermissionNone = "none"
	// PermissionAuthenticated is any signed-in identity.
	PermissionAuthenticated = "authenticated"
	// PermissionIntegrationToken is ingestion and Heartbeat, with an Integration token.
	PermissionIntegrationToken = "integration-token"
)

The values of x-permission that are not Permissions.

View Source
const (
	RoleAdmin     = "admin"
	RoleResponder = "responder"
	RoleViewer    = "viewer"
)

The Roles of L1, in the order the API lists them.

View Source
const (
	// SessionPruneAfter is auth.session_prune_after: a session is deleted this long after it ended, by sign-out, by an
	// administrative action or at its idle timeout or lifetime. Until then a browser that comes back with its cookie
	// still learns why it has to sign in again (session_expired) instead of a bare unauthenticated, for a week that
	// covers a weekend or a short holiday, the same span as auth.session_lifetime.
	SessionPruneAfter = 7 * 24 * time.Hour
	// ThrottlePruneAfter is auth.signin_throttle_prune_after: a sign-in throttle row is deleted once no failure was
	// counted for this long and its block has passed. Forgetting the count then only restarts the auth.signin_throttle
	// sequence, which reaches its 60 s maximum again within minutes of new failures.
	ThrottlePruneAfter = 24 * time.Hour
)
View Source
const (
	// SessionIdleTimeout is auth.session_idle_timeout and SessionLifetime auth.session_lifetime.
	SessionIdleTimeout = 12 * time.Hour
	SessionLifetime    = 7 * 24 * time.Hour
)
View Source
const (
	MethodLocal = "local"
	MethodOIDC  = "oidc"
)

The sign-in methods.

View Source
const (
	EndSignOut           = "sign_out"
	EndSignOutEverywhere = "sign_out_everywhere"
	EndPasswordChanged   = "password_changed"
	EndExpired           = "expired"
	// The administrative endings: an Admin changed the Role, disabled or deleted the user (C-03.FR-9, FR-13).
	EndRoleChanged  = "role_changed"
	EndUserDisabled = "user_disabled"
	EndUserDeleted  = "user_deleted"
	// The OIDC endings (C-03.FR-9, FR-29, FR-30): the user linked an OIDC identity (the other sessions), an Admin
	// converted the account to local, or the identity provider refused the user at a background re-check.
	EndOIDCLinked       = "oidc_linked"
	EndConvertedToLocal = "converted_to_local"
	EndIDPRefused       = "idp_refused"
)

The reasons a session ends, as sessions.end_reason stores them.

View Source
const (
	ThrottleAfter      = 3
	ThrottleFirstDelay = time.Second
	ThrottleMaxDelay   = 60 * time.Second
)

auth.signin_throttle: after ThrottleAfter consecutive failures of an account or a source address, each attempt waits twice as long as the previous one, from ThrottleFirstDelay up to ThrottleMaxDelay.

View Source
const ActionSecondFactorFailed = "session.second_factor_failed"

ActionSecondFactorFailed is the Audit log action of a wrong TOTP or recovery code at sign-in.

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

CSRFHeader carries the CSRF token on every mutating request made with the session cookie.

View Source
const CookieName = "muster_session"

CookieName is the session cookie (HttpOnly; Secure; SameSite=Lax; Path=/).

View Source
const FailureTOTP = "totp"

FailureTOTP is the method label of muster_login_failures_total for a wrong TOTP or recovery code.

View Source
const PasswordMinLength = 12

PasswordMinLength is auth.password_min_length, in characters.

Variables

View Source
var (
	// ErrInvalidCredentials is a wrong login, password or second factor, or an account that cannot sign in; it never
	// says which.
	ErrInvalidCredentials = errors.New("the login, the password or the code is wrong")
	// ErrUnauthenticated is a request without a usable session.
	ErrUnauthenticated = errors.New("no valid session")
	// ErrSessionExpired is a session that ended by idle timeout or lifetime.
	ErrSessionExpired = errors.New("the session expired")
	// ErrOIDCSessionEnded is a session that ended because the identity provider refused its user at a background
	// re-check (C-03.FR-30).
	ErrOIDCSessionEnded = errors.New("the identity provider refused the user; sign in again")
	// ErrNotLocal is a password change of an account that signs in through OIDC.
	ErrNotLocal = errors.New("the account signs in through OIDC and has no password")
	// ErrTOTPNotPending is a second factor given to a session that does not wait for one.
	ErrTOTPNotPending = errors.New("the session is not waiting for a TOTP code")
)
View Source
var (
	// ErrPasswordTooShort is a password shorter than PasswordMinLength characters.
	ErrPasswordTooShort = fmt.Errorf("the password is shorter than %d characters", PasswordMinLength)
)

RoleNames are the Roles, highest first.

Functions

func CheckPasswordLength

func CheckPasswordLength(password string) error

CheckPasswordLength refuses a password shorter than PasswordMinLength characters.

func ClientAddress

func ClientAddress(remoteAddr string, forwardedFor []string, trusted []netip.Prefix) netip.Addr

ClientAddress is the client address of C-02.FR-1: the TCP peer of remoteAddr; when the peer is inside one of the trusted proxy networks, the first address of X-Forwarded-For read from the right that is outside them. A forged entry on the left is never reached while a trusted proxy appended the real one after it. When every entry is trusted, the left-most one is the client; an entry that does not parse ends the walk at the last good address.

func ClientAddressFrom

func ClientAddressFrom(ctx context.Context) netip.Addr

ClientAddressFrom returns the client address of the request; it is invalid when the middleware did not set one.

func HashPassword

func HashPassword(ctx context.Context, password string) (string, error)

HashPassword returns the argon2id PHC string of password with a random salt: $argon2id$v=19$m=<KiB>,t=<passes>,p=<lanes>$<salt>$<key>, salt and key in unpadded standard base64.

func ThrottleDelay

func ThrottleDelay(failures int64) time.Duration

ThrottleDelay is how long the next attempt waits after failures consecutive failures: nothing before ThrottleAfter, then 1 s, 2 s, 4 s and so on up to 60 s.

func VerifyPassword

func VerifyPassword(ctx context.Context, encoded, password string) (bool, error)

VerifyPassword reports whether password matches the PHC string encoded, in constant time for the key; a string that is not an argon2id hash is an error, and so is ctx ending while the check waits for its turn.

func WithClientAddress

func WithClientAddress(ctx context.Context, addr netip.Addr) context.Context

WithClientAddress returns ctx carrying the client address of the request.

func WithIdentity

func WithIdentity(ctx context.Context, id *Identity) context.Context

WithIdentity returns ctx carrying id.

Types

type Identity

type Identity struct {
	// Session is the web session; for a Personal access token only its User is set, to the token's owner, and for a
	// Service account token it is empty.
	Session     Session
	Permissions []Permission
	// Transport is ui for the web session and api for a token.
	Transport audit.Transport
	// Token is the token of the request; nil for the web session.
	Token *Token
}

Identity is who makes a request: a user signed in with a web session, a user through a Personal access token, or a Service account through one of its tokens (C-04). It is derived once per request by the API middleware and travels in the request context.

func IdentityFrom

func IdentityFrom(ctx context.Context) (*Identity, bool)

IdentityFrom returns the identity of the request, if it has one.

func (*Identity) Actor

func (id *Identity) Actor() audit.Actor

Actor is the identity as the Audit log records it, with the token it used.

func (*Identity) Can

func (id *Identity) Can(p Permission) bool

Can reports whether the identity holds p.

func (*Identity) IsServiceAccount

func (id *Identity) IsServiceAccount() bool

IsServiceAccount reports whether the identity is a Service account, which has no profile and no Account links.

func (*Identity) MayAssign

func (id *Identity) MayAssign(roles Roles, role string) (Permission, bool)

MayAssign reports whether the identity may give someone the Role role, and the first Permission of the Role it lacks when it may not: a token may only assign a Role whose Permissions it holds itself, so that a narrowed token never creates or changes a User or a Service account with more than the token (C-04.FR-7). The web session is not limited by this rule; the Permission of the operation decides.

type OIDCSignIn

type OIDCSignIn struct {
	User  Principal
	State SessionState
	// IDPMFA records that the identity provider asserted multi-factor authentication (amr).
	IDPMFA bool
	// Lifetime bounds the session's total life: auth.session_lifetime, or auth.oidc_fallback_session_lifetime for a
	// user without an offline token. Zero is auth.session_lifetime.
	Lifetime  time.Duration
	Address   netip.Addr
	UserAgent string
}

OIDCSignIn is a session to open for a user whom an OIDC sign-in identified; internal/oidc checked the identity and decided the state.

type PasswordChange

type PasswordChange struct {
	Current string
	New     string
	Address netip.Addr
}

PasswordChange is a user's change of their own password.

type Permission

type Permission string

Permission is one thing a Role allows, named <resource>:<verb> (C-03.FR-2).

type Principal

type Principal struct {
	ID       int64
	PublicID string
	Name     string
	Role     string
}

Principal is the user behind a session.

type Proof

type Proof struct {
	TOTPCode     string
	RecoveryCode string
}

Proof is a second factor: a current TOTP code or a single-use recovery code.

func (Proof) Given

func (p Proof) Given() bool

Given reports whether the proof carries a code.

type PruneQueries

type PruneQueries interface {
	PruneSessions(ctx context.Context, arg dbgen.PruneSessionsParams) (int64, error)
	PruneSignInThrottles(ctx context.Context, arg dbgen.PruneSignInThrottlesParams) (int64, error)
}

PruneQueries are the deletes of short-lived pruning; *dbgen.Queries implements them.

type Pruner

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

Pruner deletes the sessions and sign-in throttles that can no longer be used, one batch at a time, for the short_lived_pruning Leader task. Its methods are PruneTable deletes.

func NewPruner

func NewPruner(q PruneQueries) Pruner

NewPruner returns the Pruner over q.

func (Pruner) Sessions

func (p Pruner) Sessions(ctx context.Context, orgID int64, now time.Time, limit int32) (int64, error)

Sessions deletes at most limit sessions of the Organization that ended or expired SessionPruneAfter before now.

func (Pruner) SignInThrottles

func (p Pruner) SignInThrottles(ctx context.Context, orgID int64, now time.Time, limit int32) (int64, error)

SignInThrottles deletes at most limit sign-in throttle rows of the Organization whose last failure and block are ThrottlePruneAfter before now.

type Queries

type Queries interface {
	ListRolePermissions(ctx context.Context) ([]dbgen.RolePermission, error)
	GetSignInUser(ctx context.Context, arg dbgen.GetSignInUserParams) (dbgen.GetSignInUserRow, error)
	GetUserPassword(ctx context.Context, arg dbgen.GetUserPasswordParams) (dbgen.GetUserPasswordRow, error)
	MarkSignedIn(ctx context.Context, arg dbgen.MarkSignedInParams) error
	SetPassword(ctx context.Context, arg dbgen.SetPasswordParams) (int64, error)
	CreateSession(ctx context.Context, arg dbgen.CreateSessionParams) (int64, error)
	GetSessionByToken(ctx context.Context, arg dbgen.GetSessionByTokenParams) (dbgen.GetSessionByTokenRow, error)
	TouchSession(ctx context.Context, arg dbgen.TouchSessionParams) error
	EndSession(ctx context.Context, arg dbgen.EndSessionParams) (int64, error)
	EndUserSessions(ctx context.Context, arg dbgen.EndUserSessionsParams) (int64, error)
	EndOtherUserSessions(ctx context.Context, arg dbgen.EndOtherUserSessionsParams) (int64, error)
	ListUserSessions(ctx context.Context, arg dbgen.ListUserSessionsParams) ([]dbgen.ListUserSessionsRow, error)
	CompleteSecondFactor(ctx context.Context, arg dbgen.CompleteSecondFactorParams) (int64, error)
	LiveSessions(ctx context.Context, arg dbgen.LiveSessionsParams) ([]int64, error)
	TryLockSignInSubject(ctx context.Context, arg dbgen.TryLockSignInSubjectParams) (bool, error)
	GetThrottles(ctx context.Context, arg dbgen.GetThrottlesParams) ([]dbgen.GetThrottlesRow, error)
	RecordSignInFailure(ctx context.Context, arg dbgen.RecordSignInFailureParams) (int64, error)
	BlockSignIn(ctx context.Context, arg dbgen.BlockSignInParams) error
	ResetSignInThrottles(ctx context.Context, arg dbgen.ResetSignInThrottlesParams) error
	audit.Store
}

Queries are the queries of the package, with the insert of the Audit log.

type Roles

type Roles map[string][]Permission

Roles is the allocation of Permissions to Roles, loaded at startup from role_permissions; every check is made against a Permission, never against a Role.

func LoadRoles

func LoadRoles(ctx context.Context, q interface {
	ListRolePermissions(ctx context.Context) ([]dbgen.RolePermission, error)
}) (Roles, error)

LoadRoles reads the allocation; every Role of RoleNames must be in it.

func (Roles) Has

func (r Roles) Has(role string, p Permission) bool

Has reports whether role holds p.

func (Roles) Permissions

func (r Roles) Permissions(role string) []Permission

Permissions returns the Permissions of role, sorted; an unknown Role has none.

type SecondFactor

type SecondFactor interface {
	// Verify reports whether p is a current TOTP code of the user not used before, or one of the user's unused
	// recovery codes, and uses it up. A user without TOTP has no right code.
	Verify(ctx context.Context, userID int64, p Proof) (bool, error)
}

SecondFactor checks the TOTP of the users; internal/totp implements it.

type Service

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

Service signs people in and keeps their sessions for the Organization.

func NewService

func NewService(orgID int64, s Store, k *keyring.Keyring, w *audit.Writer, business clock.Clock, roles Roles) *Service

NewService returns the Service of the Organization orgID; clock is the business clock.

func (*Service) Attempt

func (s *Service) Attempt(ctx context.Context, sess Session, addr netip.Addr, method string,
	check func(context.Context) (bool, error)) error

Attempt checks a proof that sess's user gives on their own account — the password, a TOTP code or a recovery code — under the sign-in throttle of the account and of addr, so that a stolen session cannot guess faster than a sign-in could. An attempt the throttle refuses is a *ThrottledError and check does not run; a wrong proof counts as a failed sign-in, in muster_login_failures_total with method (local for a password, totp for a code), and is ErrInvalidCredentials.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, cookie string) (Session, error)

Authenticate returns the session of a cookie value. A value that names no session, an ended session or a user who is no longer active is ErrUnauthenticated; a session past its idle timeout or lifetime ends with the reason expired and is ErrSessionExpired, and one the identity provider's refusal ended is ErrOIDCSessionEnded. A session in use moves its idle expiry, written at most once a minute.

func (*Service) CSRFToken

func (s *Service) CSRFToken(sess Session) (string, error)

CSRFToken is the CSRF token of sess.

func (*Service) ChangePassword

func (s *Service) ChangePassword(ctx context.Context, sess Session, c PasswordChange) error

ChangePassword replaces the password of sess's user after checking the current one, and ends the user's other sessions; sess continues. A new password that is too short is ErrPasswordTooShort, a wrong current password ErrInvalidCredentials, and an account that signs in through OIDC ErrNotLocal. A wrong current password counts in the sign-in throttle of the account and the address like a failed sign-in, so that a stolen session cannot try passwords faster than a sign-in could; an attempt the throttle refuses is a *ThrottledError.

func (*Service) CheckCSRF

func (s *Service) CheckCSRF(sess Session, header string) bool

CheckCSRF reports whether header carries the CSRF token of sess.

func (*Service) CheckPassword

func (s *Service) CheckPassword(ctx context.Context, sess Session, password string) (bool, error)

CheckPassword reports whether password is the current password of sess's user; an account without a password has no right one. It does not throttle: run it inside Attempt.

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context, sess Session) ([]SessionInfo, error)

ListSessions lists the sessions of sess's user that have neither ended nor expired, marking sess.

func (*Service) LiveSessions

func (s *Service) LiveSessions(ctx context.Context, ids []int64) ([]int64, error)

LiveSessions returns the sessions of ids that are still usable — active, neither ended nor expired, of an active user — without counting the check as a use: the live-updates streams close the others.

func (*Service) OpenOIDCSession

func (s *Service) OpenOIDCSession(ctx context.Context, in OIDCSignIn) (Session, error)

OpenOIDCSession opens a session with the method oidc after an OIDC sign-in and records the sign-in as session.signed_in with the method oidc (C-03.FR-25).

func (*Service) Permissions

func (s *Service) Permissions(sess Session) []Permission

Permissions are the Permissions a session grants: its user's Role's, none while it is limited.

func (*Service) Roles

func (s *Service) Roles() Roles

Roles is the allocation of Permissions to Roles.

func (*Service) SignIn

func (s *Service) SignIn(ctx context.Context, req SignInRequest) (Session, error)

SignIn checks a login and a password and opens a session. The login is compared lowercased. A wrong login or password, a disabled or deleted account and an account without a password are all ErrInvalidCredentials, and an unknown login spends the time of a password check too. An attempt before the throttle allows one is a *ThrottledError and is not evaluated.

The session of a user with TOTP is active when the request carries a right code and totp_required without one; a wrong code is ErrInvalidCredentials and counts like a wrong password (C-03.FR-24). A user without TOTP whom the TOTP policy covers gets a session in the state totp_enrolment_required. Only a session that is active resets the throttle, so that a known password never buys more guesses at the code.

func (*Service) SignOut

func (s *Service) SignOut(ctx context.Context, sess Session, addr netip.Addr) error

SignOut ends sess.

func (*Service) SignOutEverywhere

func (s *Service) SignOutEverywhere(ctx context.Context, sess Session, addr netip.Addr) error

SignOutEverywhere ends every session of sess's user, sess included.

func (*Service) SubmitSecondFactor

func (s *Service) SubmitSecondFactor(ctx context.Context, sess Session, p Proof, addr netip.Addr) (Session, error)

SubmitSecondFactor completes a session in the state totp_required with a TOTP code or a recovery code of its user (C-03.FR-24) and returns it active. A session that waits for no code is ErrTOTPNotPending. The code is checked under the sign-in throttle of the user's account and of addr like a password: an attempt the throttle refuses is a *ThrottledError, and a wrong code is ErrInvalidCredentials, counted, recorded as session.second_factor_failed and in muster_login_failures_total{method="totp"}. A right code resets the throttle.

func (*Service) UseSecondFactor

func (s *Service) UseSecondFactor(f SecondFactor)

UseSecondFactor sets what checks the TOTP codes and recovery codes of the users; without it no code is right.

type Session

type Session struct {
	ID            int64
	PublicID      string
	State         SessionState
	Method        string
	CreatedAt     time.Time
	LastUsedAt    time.Time
	IdleExpiresAt time.Time
	ExpiresAt     time.Time
	User          Principal
	// contains filtered or unexported fields
}

Session is a session of a user. The cookie value is held only in memory, to derive the CSRF token.

func (Session) Cookie

func (s Session) Cookie() string

Cookie is the value of the session cookie.

type SessionInfo

type SessionInfo struct {
	PublicID   string
	Method     string
	Address    netip.Addr
	UserAgent  string
	CreatedAt  time.Time
	LastUsedAt time.Time
	Current    bool
}

SessionInfo is a session as the profile lists it.

type SessionState

type SessionState string

SessionState is the state of a session; a limited session can only finish the second factor or sign out.

const (
	StateActive                SessionState = "active"
	StateTOTPRequired          SessionState = "totp_required"
	StateTOTPEnrolmentRequired SessionState = "totp_enrolment_required"
)

type SignInRequest

type SignInRequest struct {
	Login     string
	Password  string
	Proof     Proof
	Address   netip.Addr
	UserAgent string
}

SignInRequest is a local sign-in attempt, with the second factor when the user finishes in one request.

type Store

type Store interface {
	Queries
	InTx(ctx context.Context, f func(Queries) error) error
}

Store runs the queries alone or in one transaction.

func NewStore

func NewStore(pool *pgxpool.Pool) Store

NewStore is the Store over the main pool.

type ThrottledError

type ThrottledError struct {
	RetryAfter time.Duration
}

ThrottledError refuses a sign-in attempt that comes before the throttle allows the next one; it is not evaluated.

func (*ThrottledError) Error

func (e *ThrottledError) Error() string

func (*ThrottledError) Seconds

func (e *ThrottledError) Seconds() int

Seconds is RetryAfter rounded up to whole seconds, at least one.

type Token

type Token struct {
	ID       int64
	PublicID string
	Name     string
	// ServiceAccount is the account of a Service account token; nil for a Personal access token.
	ServiceAccount *Principal
}

Token is the Personal access token or Service account token a request authenticated with.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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