Documentation
¶
Overview ¶
Package auth signs people in with their Linux account (PAM, like Cockpit), keeps browser sessions and API tokens, and decides roles: root and the admin group (default "libvirt", the group that may manage VMs anyway) are admins; optional operator and viewer groups get less (see roles.go).
Index ¶
- Constants
- Variables
- func ClearCookie(w http.ResponseWriter, r *http.Request)
- func IsExternal(name string) bool
- func OTPAuthURI(issuer, user, secret string) string
- func SelfSignedCert(dir string) (tls.Certificate, error)
- func SessionToken(r *http.Request) string
- func SetCookie(w http.ResponseWriter, r *http.Request, token string)
- func TOTPCode(secret string, t time.Time) (string, error)
- func UserGroups(name string) []string
- type Authenticator
- type CodeRequired
- type External
- func (e *External) Config(redact bool) ExternalConfig
- func (e *External) Methods() (ldapOn bool, oidcOn bool, oidcLabel string)
- func (e *External) Remember(name string, r Role)
- func (e *External) RememberUser(name string, r Role, groups []string)
- func (e *External) RoleOf(name string) Role
- func (e *External) SSOIdentity(username string, groups []string) Identity
- func (e *External) SetConfig(c ExternalConfig) error
- func (e *External) SetRoleFallback(fn func(user string, groups []string) Role)
- type ExternalConfig
- type GroupRoles
- type Groups
- type Identity
- type LDAPConfig
- type Manager
- func (m *Manager) CompleteLogin(remote, pending, code string) (Identity, string, error)
- func (m *Manager) External() *External
- func (m *Manager) Login(ctx context.Context, remote, name, password string) (string, error)
- func (m *Manager) Logout(token string)
- func (m *Manager) NewSession(id Identity) (string, error)
- func (m *Manager) RoleOf(user string) Role
- func (m *Manager) SetExternal(e *External)
- func (m *Manager) SetTwoFactor(t *TwoFactor)
- func (m *Manager) TwoFactor() *TwoFactor
- func (m *Manager) User(token string) (Identity, bool)
- func (m *Manager) Valid(token string) bool
- type OIDCConfig
- type PAM
- type RateLimiter
- type Role
- type Token
- type Tokens
- type TwoFactor
- func (t *TwoFactor) Begin(user, issuer string) (secret, uri string, err error)
- func (t *TwoFactor) Confirm(user, code string) ([]string, error)
- func (t *TwoFactor) Disable(user string) error
- func (t *TwoFactor) Enabled(user string) bool
- func (t *TwoFactor) Status(user string) TwoFactorStatus
- func (t *TwoFactor) Users() []string
- func (t *TwoFactor) Verify(user, code string) error
- type TwoFactorStatus
Constants ¶
const ( CookieName = "virtomir_session" // IdleTimeout ends a session nobody used for a while; MaxAge ends any session. IdleTimeout = 2 * time.Hour MaxAge = 24 * time.Hour )
const ( MaxFailures = 5 FailureWindow = 5 * time.Minute )
Login rate limit: after MaxFailures failed attempts from one address within FailureWindow, further attempts are refused until the oldest one ages out.
const ( SuffixLDAP = "@ldap" SuffixSSO = "@sso" )
const PAMAvailable = false
PAMAvailable reports whether this binary was built with PAM support (-tags pam, cgo).
const TokenPrefix = "vmt_"
TokenPrefix makes leaked tokens easy to recognize (e.g. by secret scanners).
Variables ¶
var ErrBadCode = errors.New("wrong or expired code")
ErrBadCode: a wrong, expired or already used code.
var ErrBadCredentials = errors.New("wrong user name or password")
ErrBadCredentials is the only failure a login form shows, so it never reveals whether the user exists.
var ErrNotAllowed = errors.New("this account is not allowed to use VirtoMir")
ErrNotAllowed: the password was right but the account has no VirtoMir role.
var (
ErrTokenRole = errors.New("a token cannot have more rights than its owner")
)
var ErrTooManyAttempts = errors.New("too many failed sign-in attempts, try again in a few minutes")
ErrTooManyAttempts means the address is temporarily locked out.
Functions ¶
func ClearCookie ¶
func ClearCookie(w http.ResponseWriter, r *http.Request)
func IsExternal ¶
IsExternal reports whether a user name belongs to LDAP or SSO.
func OTPAuthURI ¶
OTPAuthURI is the key-uri format authenticator apps read from the QR code.
func SelfSignedCert ¶
func SelfSignedCert(dir string) (tls.Certificate, error)
SelfSignedCert loads dir/cert.pem + dir/key.pem, creating them on first use. Browsers will warn about a self-signed certificate; replacing the files with a real one (or passing -tls-cert/-tls-key) removes the warning. Passwords never travel unencrypted.
func SessionToken ¶
SessionToken returns the session cookie of a request ("" when none).
func SetCookie ¶
func SetCookie(w http.ResponseWriter, r *http.Request, token string)
SetCookie stores the session in the browser: HttpOnly (no script access) and SameSite=Strict (not sent with cross-site requests, which blocks CSRF).
func TOTPCode ¶
TOTPCode is the code an authenticator app shows for secret at time t (tests, tools).
func UserGroups ¶
UserGroups lists the names of the Linux groups a user belongs to (quota rules by group).
Types ¶
type Authenticator ¶
Authenticator checks a user name and password.
type CodeRequired ¶
type CodeRequired struct{ Pending string }
CodeRequired is Login's answer when the password was right and the account has two-factor sign-in: the client sends the code with Pending to CompleteLogin.
func (*CodeRequired) Error ¶
func (e *CodeRequired) Error() string
type External ¶
type External struct {
// contains filtered or unexported fields
}
External holds the external sign-in configuration (in -state-dir/signin.json, 0600).
func OpenExternal ¶
func (*External) Config ¶
func (e *External) Config(redact bool) ExternalConfig
Config returns the configuration; with redact, secrets are replaced by a placeholder.
func (*External) Remember ¶ added in v0.9.0
Remember keeps an external user's role from their last sign-in.
func (*External) RememberUser ¶ added in v0.9.0
RememberUser keeps an external user's role and groups from their last sign-in. Global roles (Viewer, Operator, Admin) are persisted in Roles; project-derived Member roles are not persisted, so removing a user from a project revokes access immediately.
func (*External) RoleOf ¶
RoleOf is an external user's role: persistent global role if set, otherwise evaluated dynamically against roleFallback using the user's remembered groups.
func (*External) SSOIdentity ¶
SSOIdentity turns verified OIDC claims into an identity (user@sso) and remembers its role.
func (*External) SetConfig ¶
func (e *External) SetConfig(c ExternalConfig) error
SetConfig stores a new configuration. Secrets left as the placeholder keep their value.
type ExternalConfig ¶
type ExternalConfig struct {
LDAP LDAPConfig `json:"ldap"`
OIDC OIDCConfig `json:"oidc"`
}
type GroupRoles ¶
type GroupRoles struct {
Admin []string `json:"admin"`
Operator []string `json:"operator"`
Viewer []string `json:"viewer"`
}
GroupRoles maps directory groups (names or full DNs) to roles.
func (GroupRoles) RoleFor ¶
func (g GroupRoles) RoleFor(groups []string) Role
RoleFor is the highest role any of groups gives. Matching ignores case and accepts a group's CN for a full DN ("cn=vm-admins,ou=groups,dc=x" matches "vm-admins").
type Groups ¶
type Groups struct {
Admin, Operator, Viewer string
}
Groups maps Linux groups to roles. Root is always Admin. Each field may list several groups separated by commas; empty names and groups the host does not have are skipped.
type Identity ¶
type Identity struct {
Name string `json:"user"`
Role Role `json:"role"`
// Token is the API token name when the request used one.
Token string `json:"token,omitempty"`
// Via is the cluster member that forwarded the request (ADR-0020); the user signed in there.
Via string `json:"via,omitempty"`
}
Identity is a signed-in user (or the owner of an API token) and their role.
type LDAPConfig ¶
type LDAPConfig struct {
Enabled bool `json:"enabled"`
// URL: ldaps://dc1.example.com or ldap://… (with StartTLS).
URL string `json:"url"`
StartTLS bool `json:"startTLS"`
InsecureSkipVerify bool `json:"insecureSkipVerify"`
// BindDN/BindPassword: a service account to search with (empty: anonymous search).
BindDN string `json:"bindDN"`
BindPassword string `json:"bindPassword,omitempty"`
// UserBase and UserFilter find the user; %s is the (escaped) user name.
UserBase string `json:"userBase"`
UserFilter string `json:"userFilter"`
// GroupAttr on the user entry lists their groups (memberOf).
GroupAttr string `json:"groupAttr"`
Roles GroupRoles `json:"roles"`
}
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager owns sessions and the login rate limit. The zero value is not usable; use New.
func New ¶
func New(authn Authenticator, roleOf func(string) Role) *Manager
New returns a manager. roleOf decides each user's role at sign-in (NoAccess refuses).
func (*Manager) CompleteLogin ¶
CompleteLogin finishes a sign-in that needed a one-time code. Wrong codes count towards the address's lockout like wrong passwords, and a pending sign-in dies after a few of them.
func (*Manager) NewSession ¶
NewSession starts a session for someone already authenticated (OpenID Connect).
func (*Manager) RoleOf ¶
RoleOf is the user's current role: Linux groups are re-read; LDAP/SSO users keep the role of their last sign-in.
func (*Manager) SetExternal ¶
SetExternal adds LDAP / OpenID Connect sign-in (local accounts keep working first).
func (*Manager) SetTwoFactor ¶
SetTwoFactor enables one-time codes for the accounts that turned them on.
func (*Manager) User ¶
User returns the session's identity and refreshes its idle timer. The role of a local account is its role now, read again every minute: someone taken out of the admin group, or whose account is gone, does not stay an administrator until the session runs out a day later (API tokens follow their owner's role in the same way).
type OIDCConfig ¶
type OIDCConfig struct {
Enabled bool `json:"enabled"`
Label string `json:"label"` // button text, e.g. "Sign in with Keycloak"
Issuer string `json:"issuer"` // https://idp.example.com/realms/main
ClientID string `json:"clientId"`
ClientSecret string `json:"clientSecret,omitempty"`
// UsernameClaim (preferred_username) and GroupsClaim (groups) in the ID token.
UsernameClaim string `json:"usernameClaim"`
GroupsClaim string `json:"groupsClaim"`
Roles GroupRoles `json:"roles"`
}
type RateLimiter ¶ added in v0.7.0
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token-bucket rate limiter per client IP and /24 subnet.
func NewRateLimiter ¶ added in v0.7.0
func NewRateLimiter(limit int, window time.Duration) *RateLimiter
NewRateLimiter returns a rate limiter allowing up to limit requests per window per IP.
func (*RateLimiter) Allow ¶ added in v0.7.0
func (rl *RateLimiter) Allow(remote string) (bool, int)
Allow checks if the given remote address is allowed to proceed. If allowed, it records the request and returns true, 0. If denied, it returns false along with the retry-after duration in seconds.
func (*RateLimiter) Middleware ¶ added in v0.7.0
func (rl *RateLimiter) Middleware(next http.Handler) http.Handler
Middleware wraps an http.Handler with rate limiting. If rate limited, it responds with 429 Too Many Requests and sets the Retry-After header.
type Role ¶
type Role int
Role is what a user may do. Higher roles include the lower ones.
const ( NoAccess Role = iota // Member has no global role, but belongs to one or more projects (ADR-0060). Member // Viewer sees everything (machines, metrics, XML) but changes nothing. Viewer // Operator runs machines day to day: power, console, media, snapshots. Operator // Admin may change everything: create, delete, edit, storage, networks, users' tokens. Admin )
func (Role) MarshalJSON ¶
func (*Role) UnmarshalJSON ¶
type Token ¶
type Token struct {
ID string `json:"id"`
Name string `json:"name"`
Owner string `json:"owner"`
Role Role `json:"role"`
Created time.Time `json:"created"`
Expires *time.Time `json:"expires,omitempty"`
LastUsed *time.Time `json:"lastUsed,omitempty"`
Hash string `json:"hash,omitempty"`
}
Token is an API token for scripts and tools (Terraform, CI, monitoring). Only a hash of the secret is stored; the secret is shown once, when the token is created.
type Tokens ¶
type Tokens struct {
// contains filtered or unexported fields
}
Tokens stores API tokens in a JSON file (0600).
func OpenTokens ¶
OpenTokens loads path; a missing file means no tokens yet.
func (*Tokens) Create ¶
func (t *Tokens) Create(owner Identity, name string, role Role, ttl time.Duration) (string, Token, error)
Create makes a token for owner. role may not exceed the owner's role.
type TwoFactor ¶
type TwoFactor struct {
// contains filtered or unexported fields
}
TwoFactor keeps every user's TOTP secret in -state-dir/twofactor.json (0600).
func OpenTwoFactor ¶
func (*TwoFactor) Begin ¶
Begin creates a new secret for the user (not active until Confirm). It returns the secret and the otpauth:// URI for the QR code. While 2FA is on, it cannot be replaced this way.
func (*TwoFactor) Confirm ¶
Confirm turns 2FA on once the user proves their app has the secret, and returns fresh recovery codes (shown once).
func (*TwoFactor) Disable ¶
Disable turns 2FA off for the user (the caller checked who may do that).
func (*TwoFactor) Status ¶
func (t *TwoFactor) Status(user string) TwoFactorStatus