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
- Variables
- func CanAssignRole(actor Principal, role Role) bool
- func CheckPassword(password string) error
- func DummyVerify(password string)
- func HashPassword(password string) (string, error)
- func HashToken(token string) string
- func IsAPITokenSecret(bearer string) bool
- func NewAPIToken() (id, secret, secretHash string, err error)
- func NewOpaqueToken() (string, error)
- func RequireInteractive(p Principal) error
- func SignAccessToken(kid string, key ed25519.PrivateKey, c Claims) (string, error)
- func TokenMatches(token, hash string) bool
- func ValidAPITokenRole(role string) bool
- func ValidRole(r Role) bool
- func VerifyPassword(password, encoded string) (ok, needsRehash bool, err error)
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type APITokenState
- type Applier
- type Argon2Params
- type Authenticator
- type Claims
- type DenyAll
- type KeyLookup
- type Keyring
- type Local
- func (l *Local) Authenticate(r *http.Request) (Principal, error)
- func (l *Local) ChangePassword(ctx context.Context, p Principal, current, next string) (Tokens, error)
- func (l *Local) EnsureSigningKey(ctx context.Context) error
- func (l *Local) Login(ctx context.Context, username, password, clientIP string) (Tokens, error)
- func (l *Local) Logout(ctx context.Context, refreshToken string) error
- func (l *Local) PrepareSetup(ctx context.Context) (string, bool, error)
- func (l *Local) Refresh(ctx context.Context, refreshToken string) (Tokens, error)
- func (l *Local) ReloadKeys(ctx context.Context) error
- func (l *Local) RunKeyMaintenance(ctx context.Context, isLeader func() bool, interval time.Duration)
- func (l *Local) Setup(ctx context.Context, token, username, displayName, password string) (Tokens, error)
- type LocalOptions
- type Principal
- type Role
- type Throttle
- type ThrottledError
- type Ticket
- type Tickets
- type Tokens
Constants ¶
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.
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.
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 )
const ( MinPasswordLen = 12 MaxPasswordLen = 256 )
Password length limits (bytes); the upper bound caps hashing cost.
const TicketTTL = 30 * time.Second
TicketTTL is the validity of a WebSocket ticket (FA-AUTH-11).
Variables ¶
var ( ErrInvalidCredentials = errors.New("invalid username or password") ErrInvalidSession = errors.New("session is not valid") 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.
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.
ErrAuthUnavailable means credentials cannot be checked right now, e.g. the identity provider's keys were never loaded. It is answered with 503.
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.
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.
var ErrInvalidHash = errors.New("invalid password hash")
ErrInvalidHash is returned for hashes that are not a supported PHC string.
var ErrInvalidTicket = errors.New("invalid or expired stream ticket")
ErrInvalidTicket is returned for unknown, expired or already used tickets.
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.
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.
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.
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.
var ErrTooManyTickets = errors.New("too many pending stream tickets")
ErrTooManyTickets is returned when the store is full of unexpired tickets.
var ErrUnauthenticated = errors.New("authentication required")
ErrUnauthenticated means no valid credentials were presented.
Functions ¶
func CanAssignRole ¶
CanAssignRole reports whether actor may give role to a user of its tenant: only platform admins create platform admins (FA-AUTH-09).
func CheckPassword ¶
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 ¶
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 ¶
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 ¶
IsAPITokenSecret reports whether a bearer value is meant as an API token. It only looks at the prefix; Authenticate checks the rest.
func NewAPIToken ¶
NewAPIToken returns a new public ID, the secret that is shown once and the hash that is stored.
func NewOpaqueToken ¶
NewOpaqueToken returns 256 random bits, base64url-encoded, for refresh and setup tokens (ADR 0008).
func RequireInteractive ¶
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 ¶
SignAccessToken returns a signed token for the claims.
func TokenMatches ¶
TokenMatches compares a token with a stored hash in constant time.
func ValidAPITokenRole ¶
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 VerifyPassword ¶
VerifyPassword checks password against an encoded hash in constant time. needsRehash reports weaker parameters than DefaultArgon2.
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 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 ¶
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.
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.
type KeyLookup ¶
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 (*Local) Authenticate ¶
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 ¶
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 ¶
Login checks the credentials with throttling per account and per IP (FA-AUTH-04) and starts a session.
func (*Local) Logout ¶
Logout revokes the token family of a refresh token; unknown tokens are ignored.
func (*Local) PrepareSetup ¶
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 ¶
Refresh rotates the refresh token (FA-AUTH-03). A reused token revokes its whole family in the FSM and fails here.
func (*Local) ReloadKeys ¶
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.
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 ¶
FromContext returns the principal of the request.
func (Principal) CanAdmin ¶
CanAdmin reports permission to manage channels, users and tenant settings.
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 ¶
NewThrottle returns a throttle with the given number of free failures.
type ThrottledError ¶
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.
Source Files
¶
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. |