auth

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 24 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 defines the authenticated principal and the role model (Konzept 12.2, FA-AUTH-09). The tenant always comes from the principal, never from request parameters (FA-TEN-02).

Index

Constants

View Source
const (
	// APITokenPrefix starts every API token secret. It lets secret scanners
	// find leaked tokens and separates tokens from JWTs.
	APITokenPrefix = "uct_"
	// APITokenIDPrefix starts the public ID of an API token.
	APITokenIDPrefix = "tok_"
	// APITokenScopeTenant is the only scope until a later ADR adds more.
	APITokenScopeTenant = cluster.APITokenScopeTenant
	// APITokenCommandLevel is the command level from which the cluster
	// stores API tokens (ADR 0031). Tokens are not accepted below it.
	APITokenCommandLevel = cluster.AuditCommandLevel
)

API tokens (ADR 0031, FA-AUTH-10) are long-lived service tokens of a tenant. The secret is "uct_" followed by 256 random bits; only its SHA-256 is stored and replicated.

View Source
const (
	Issuer    = "pulsequorum"
	Audience  = "pulsequorum"
	AccessTTL = 15 * time.Minute
)

Access tokens are JWTs signed with Ed25519 (ADR 0008, FA-AUTH-02). The implementation is deliberately small: one algorithm, fixed header, strict claim checks; anything unexpected is rejected.

View Source
const (
	// RefreshTTL is the sliding lifetime of a refresh token family.
	RefreshTTL = 14 * 24 * time.Hour
	// KeyRotation is how often a new signing key is created.
	KeyRotation = 30 * 24 * time.Hour
)
View Source
const (
	MinPasswordLen = 12
	MaxPasswordLen = 256
)

Password length limits (bytes); the upper bound caps hashing cost.

View Source
const TicketTTL = 30 * time.Second

TicketTTL is the validity of a WebSocket ticket (FA-AUTH-11).

Variables

View Source
var (
	ErrInvalidCredentials = errors.New("invalid username or password")
	ErrInvalidSession     = errors.New("session is not valid")
	ErrSetupUnavailable   = errors.New("setup is not available")
	ErrWeakPassword       = fmt.Errorf("password must have %d to %d characters", MinPasswordLen, MaxPasswordLen)
)

Errors of the local authentication. Callers map them to one generic message so responses never reveal whether an account exists.

View Source
var DefaultArgon2 = Argon2Params{MemoryKiB: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}

DefaultArgon2 is the OWASP minimum: m=19 MiB, t=2, p=1.

View Source
var ErrAuthUnavailable = errors.New("authentication is temporarily unavailable")

ErrAuthUnavailable means credentials cannot be checked right now, e.g. the identity provider's keys were never loaded. It is answered with 503.

View Source
var ErrForbidden = errors.New("access denied")

ErrForbidden means valid credentials that grant no access: no usable role, an organization without tenant, or a suspended tenant (FA-AUTH-06). Errors wrapping it are answered with 403; their message is shown to the caller and must not contain token contents.

View Source
var ErrInvalidAPIToken = fmt.Errorf("%w: invalid or expired API token", ErrUnauthenticated)

ErrInvalidAPIToken is the single answer for unknown, malformed and expired tokens, so a caller cannot tell which case applies.

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

ErrInvalidHash is returned for hashes that are not a supported PHC string.

View Source
var ErrInvalidTicket = errors.New("invalid or expired stream ticket")

ErrInvalidTicket is returned for unknown, expired or already used tickets.

View Source
var ErrInvalidToken = errors.New("invalid access token")

ErrInvalidToken is returned for every token that must not be accepted. The reason is not exposed to callers.

View Source
var ErrOpaqueToken = fmt.Errorf("%w: opaque access tokens are not supported; configure the identity provider to issue JWT access tokens", ErrUnauthenticated)

ErrOpaqueToken rejects a bearer token that is not a JWT (FA-AUTH-05). It wraps ErrUnauthenticated, so it is answered with 401 and this message.

View Source
var ErrTenantSuspended = fmt.Errorf("%w: tenant is suspended", ErrForbidden)

ErrTenantSuspended rejects the users of a suspended tenant (ADR 0029). It wraps ErrForbidden and is answered with 403.

View Source
var ErrTokenNotAllowed = fmt.Errorf("%w: this operation is not available to API tokens", ErrForbidden)

ErrTokenNotAllowed rejects API tokens on operations reserved for interactive logins (ADR 0031): token and user management, admin and auth endpoints.

View Source
var ErrTooManyTickets = errors.New("too many pending stream tickets")

ErrTooManyTickets is returned when the store is full of unexpired tickets.

View Source
var ErrUnauthenticated = errors.New("authentication required")

ErrUnauthenticated means no valid credentials were presented.

Functions

func CanAssignRole

func CanAssignRole(actor Principal, role Role) bool

CanAssignRole reports whether actor may give role to a user of its tenant: only platform admins create platform admins (FA-AUTH-09).

func CheckPassword

func CheckPassword(password string) error

CheckPassword enforces the length policy (NFA-SEC-03, OWASP).

func DummyVerify

func DummyVerify(password string)

DummyVerify spends the same work as VerifyPassword and always fails.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns an Argon2id hash in PHC format ($argon2id$v=19$m=…,t=…,p=…$salt$hash); parameters travel with the hash so they can be raised later.

func HashToken

func HashToken(token string) string

HashToken returns the stored form of an opaque token. A plain SHA-256 is enough: the tokens carry 256 bits of entropy, so there is nothing to guess.

func IsAPITokenSecret

func IsAPITokenSecret(bearer string) bool

IsAPITokenSecret reports whether a bearer value is meant as an API token. It only looks at the prefix; Authenticate checks the rest.

func NewAPIToken

func NewAPIToken() (id, secret, secretHash string, err error)

NewAPIToken returns a new public ID, the secret that is shown once and the hash that is stored.

func NewOpaqueToken

func NewOpaqueToken() (string, error)

NewOpaqueToken returns 256 random bits, base64url-encoded, for refresh and setup tokens (ADR 0008).

func RequireInteractive

func RequireInteractive(p Principal) error

RequireInteractive rejects API tokens (ADR 0031). Token and user management, admin endpoints and tenant administration call it so that a leaked token can neither extend itself nor create accounts.

func SignAccessToken

func SignAccessToken(kid string, key ed25519.PrivateKey, c Claims) (string, error)

SignAccessToken returns a signed token for the claims.

func TokenMatches

func TokenMatches(token, hash string) bool

TokenMatches compares a token with a stored hash in constant time.

func ValidAPITokenRole

func ValidAPITokenRole(role string) bool

ValidAPITokenRole reports whether role may be given to an API token: tenant roles only, never platform-admin (ADR 0031, option 2A). The FSM applies the same rule.

func ValidRole

func ValidRole(r Role) bool

ValidRole reports whether r is one of the four roles (FA-AUTH-09).

func VerifyPassword

func VerifyPassword(password, encoded string) (ok, needsRehash bool, err error)

VerifyPassword checks password against an encoded hash in constant time. needsRehash reports weaker parameters than DefaultArgon2.

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal stores the principal in the context.

Types

type APITokenState

type APITokenState interface {
	GetAPITokenBySecretHash(ctx context.Context, secretHash string) (store.APIToken, error)
	GetTenant(ctx context.Context, id string) (store.Tenant, error)
	CommandLevel(ctx context.Context) (uint32, error)
}

APITokenState is what the token authenticator reads from state.db.

type Applier

type Applier interface {
	Apply(ctx context.Context, cmd *pb.Command) (cluster.ApplyResult, error)
}

Applier proposes Raft commands (*cluster.Node).

type Argon2Params

type Argon2Params struct {
	MemoryKiB uint32
	Time      uint32
	Threads   uint8
	SaltLen   uint32
	KeyLen    uint32
}

Argon2Params are the Argon2id cost parameters (ADR 0008, FA-AUTH-01).

type Authenticator

type Authenticator interface {
	Authenticate(r *http.Request) (Principal, error)
}

Authenticator verifies the credentials of a request.

func WithAPITokens

func WithAPITokens(next Authenticator, state APITokenState, now func() time.Time) Authenticator

WithAPITokens accepts API tokens in front of another authenticator. Bearer values with the token prefix are checked against state.db; all other requests go to next unchanged.

type Claims

type Claims struct {
	Issuer    string   `json:"iss"`
	Audience  string   `json:"aud"`
	Subject   string   `json:"sub"` // user ID
	TenantID  string   `json:"tid"`
	Roles     []string `json:"roles"`
	IssuedAt  int64    `json:"iat"`
	NotBefore int64    `json:"nbf"`
	ExpiresAt int64    `json:"exp"`
	ID        string   `json:"jti"`
}

Claims are the access token claims.

func VerifyAccessToken

func VerifyAccessToken(token string, keys KeyLookup, now time.Time) (Claims, error)

VerifyAccessToken checks signature, header and claims at now and returns the claims. Every failure is ErrInvalidToken.

type DenyAll

type DenyAll struct{}

DenyAll rejects every request. It is used until local authentication (AP-1.12) is available, so protected endpoints are never open by accident.

func (DenyAll) Authenticate

func (DenyAll) Authenticate(*http.Request) (Principal, error)

Authenticate implements Authenticator.

type KeyLookup

type KeyLookup func(kid string) (ed25519.PublicKey, bool)

KeyLookup returns the public key for a key ID, or false if the key is unknown or no longer valid for verification.

type Keyring

type Keyring interface {
	Encrypt(plaintext []byte, aad string) (string, error)
	Decrypt(ctx context.Context, ciphertext, aad string) ([]byte, error)
}

Keyring encrypts the private signing keys (*secrets.Keyring, ADR 0011).

type Local

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

Local implements Authenticator for AUTH_MODE=local.

func NewLocal

func NewLocal(opts LocalOptions) *Local

NewLocal creates the local authentication.

func (*Local) Authenticate

func (l *Local) Authenticate(r *http.Request) (Principal, error)

Authenticate implements Authenticator: a valid bearer token of an existing, enabled user. The role comes from the current user record, so role changes apply immediately.

func (*Local) ChangePassword

func (l *Local) ChangePassword(ctx context.Context, p Principal, current, next string) (Tokens, error)

ChangePassword verifies the current password and stores the new one; the FSM revokes all sessions of the user (the caller starts a new one).

func (*Local) EnsureSigningKey

func (l *Local) EnsureSigningKey(ctx context.Context) error

EnsureSigningKey creates a signing key if there is none or the active one is older than KeyRotation, and retires the previous keys. Leader only.

func (*Local) Login

func (l *Local) Login(ctx context.Context, username, password, clientIP string) (Tokens, error)

Login checks the credentials with throttling per account and per IP (FA-AUTH-04) and starts a session.

func (*Local) Logout

func (l *Local) Logout(ctx context.Context, refreshToken string) error

Logout revokes the token family of a refresh token; unknown tokens are ignored.

func (*Local) PrepareSetup

func (l *Local) PrepareSetup(ctx context.Context) (string, bool, error)

PrepareSetup creates the one-time setup token if no user exists yet (FA-AUTH-01). The token is returned for the startup log; only its hash is kept, for one hour.

func (*Local) Refresh

func (l *Local) Refresh(ctx context.Context, refreshToken string) (Tokens, error)

Refresh rotates the refresh token (FA-AUTH-03). A reused token revokes its whole family in the FSM and fails here.

func (*Local) ReloadKeys

func (l *Local) ReloadKeys(ctx context.Context) error

ReloadKeys reads the signing keys from the replicated state.

func (*Local) RunKeyMaintenance

func (l *Local) RunKeyMaintenance(ctx context.Context, isLeader func() bool, interval time.Duration)

RunKeyMaintenance keeps the signing keys current: the leader rotates them, every node reloads them regularly. While no active key is loaded, for example on a voter that has not caught up with the leader yet, it retries every keyRetryInterval instead.

func (*Local) Setup

func (l *Local) Setup(ctx context.Context, token, username, displayName, password string) (Tokens, error)

Setup creates the first platform admin with the setup token and logs it in.

type LocalOptions

type LocalOptions struct {
	State   store.State
	Cluster Applier
	Keyring Keyring
	Logger  *slog.Logger
	Now     func() time.Time
}

LocalOptions configure the local authentication.

type Principal

type Principal struct {
	UserID   string
	Username string
	TenantID string
	Roles    []Role
	// ExpiresAt is when the presented credentials expire; zero if unknown.
	ExpiresAt time.Time
	// ViaToken is set when the caller authenticated with an API token
	// (ADR 0031); UserID is then the token ID and Username the token name.
	ViaToken bool
}

Principal is the authenticated caller.

func FromContext

func FromContext(ctx context.Context) (Principal, bool)

FromContext returns the principal of the request.

func (Principal) CanAdmin

func (p Principal) CanAdmin() bool

CanAdmin reports permission to manage channels, users and tenant settings.

func (Principal) CanEdit

func (p Principal) CanEdit() bool

CanEdit reports permission to change monitors and run checks.

func (Principal) CanRead

func (p Principal) CanRead() bool

CanRead reports read access to the principal's tenant.

func (Principal) Has

func (p Principal) Has(roles ...Role) bool

Has reports whether the principal holds one of the roles.

type Role

type Role string

Role is a role from the role model.

const (
	RolePlatformAdmin Role = "platform-admin"
	RoleTenantAdmin   Role = "tenant-admin"
	RoleTenantEditor  Role = "tenant-editor"
	RoleTenantViewer  Role = "tenant-viewer"
)

Roles (Konzept 12.2).

type Throttle

type Throttle struct {
	Free  int           // failures without delay
	Base  time.Duration // first delay
	Max   time.Duration // longest delay
	Limit int           // entries kept; oldest are dropped first
	// contains filtered or unexported fields
}

Throttle slows down password guessing per account and per IP (FA-AUTH-04, PF-33). From the Free-th failure on, every failure imposes a wait that doubles from Base up to Max (ADR 0008: "5 Fehlversuche → progressive Verzögerung"). Failures are forgotten after Max without a new failure. State is per node; in a cluster an attacker gains at most a factor of the number of voters.

func NewThrottle

func NewThrottle(free int) *Throttle

NewThrottle returns a throttle with the given number of free failures.

func (*Throttle) Fail

func (t *Throttle) Fail(key string, now time.Time)

Fail records a failed attempt.

func (*Throttle) Succeed

func (t *Throttle) Succeed(key string)

Succeed clears the failures of key.

func (*Throttle) Wait

func (t *Throttle) Wait(key string, now time.Time) time.Duration

Wait returns how long key must wait before the next attempt (0 = allowed).

type ThrottledError

type ThrottledError struct{ RetryAfter time.Duration }

ThrottledError asks the client to wait.

func (*ThrottledError) Error

func (e *ThrottledError) Error() string

type Ticket

type Ticket struct {
	Principal Principal
	// SessionEnd is when the credentials the ticket was issued for expire;
	// the stream is closed then (FA-AUTH-11).
	SessionEnd time.Time
}

Ticket is a redeemed WebSocket ticket.

type Tickets

type Tickets struct {
	TTL   time.Duration
	Limit int // tickets kept at most; issuing fails beyond that
	Now   func() time.Time
	// contains filtered or unexported fields
}

Tickets issues short-lived, single-use tickets that let a browser open the WebSocket stream without putting a long-lived token into the URL (PF-32). Tickets live in memory of the issuing node; only their SHA-256 hash is kept.

func NewTickets

func NewTickets() *Tickets

NewTickets returns a ticket store with TicketTTL.

func (*Tickets) Issue

func (t *Tickets) Issue(p Principal, sessionEnd time.Time) (string, time.Time, error)

Issue creates a ticket for p, valid until TTL or sessionEnd, whichever is earlier.

func (*Tickets) Redeem

func (t *Tickets) Redeem(token string) (Ticket, error)

Redeem consumes a ticket. Every ticket can be redeemed at most once.

type Tokens

type Tokens struct {
	AccessToken    string
	AccessExpires  time.Time
	RefreshToken   string
	RefreshExpires time.Time
}

Tokens are the result of a login, setup or refresh. RefreshToken goes into the HttpOnly cookie only.

Directories

Path Synopsis
Package oidc authenticates requests with JWT access tokens of an external OpenID Connect provider (ADR 0027).
Package oidc authenticates requests with JWT access tokens of an external OpenID Connect provider (ADR 0027).
Package oidctest provides a fake OpenID Connect identity provider for tests.
Package oidctest provides a fake OpenID Connect identity provider for tests.

Jump to

Keyboard shortcuts

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