auth

package
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 33 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 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

View Source
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
)
View Source
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.

View Source
const (
	SuffixLDAP = "@ldap"
	SuffixSSO  = "@sso"
)
View Source
const PAMAvailable = false

PAMAvailable reports whether this binary was built with PAM support (-tags pam, cgo).

View Source
const TokenPrefix = "vmt_"

TokenPrefix makes leaked tokens easy to recognize (e.g. by secret scanners).

Variables

View Source
var ErrBadCode = errors.New("wrong or expired code")

ErrBadCode: a wrong, expired or already used code.

View Source
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.

View Source
var ErrNotAllowed = errors.New("this account is not allowed to use VirtoMir")

ErrNotAllowed: the password was right but the account has no VirtoMir role.

View Source
var (
	ErrTokenRole = errors.New("a token cannot have more rights than its owner")
)
View Source
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

func IsExternal(name string) bool

IsExternal reports whether a user name belongs to LDAP or SSO.

func OTPAuthURI

func OTPAuthURI(issuer, user, secret string) string

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

func SessionToken(r *http.Request) string

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

func TOTPCode(secret string, t time.Time) (string, error)

TOTPCode is the code an authenticator app shows for secret at time t (tests, tools).

func UserGroups

func UserGroups(name string) []string

UserGroups lists the names of the Linux groups a user belongs to (quota rules by group).

Types

type Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context, user, password string) error
}

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 OpenExternal(path string) (*External, error)

func (*External) Config

func (e *External) Config(redact bool) ExternalConfig

Config returns the configuration; with redact, secrets are replaced by a placeholder.

func (*External) Methods

func (e *External) Methods() (ldapOn bool, oidcOn bool, oidcLabel string)

OIDCEnabled and LDAPEnabled tell the sign-in page what to offer.

func (*External) Remember added in v0.9.0

func (e *External) Remember(name string, r Role)

Remember keeps an external user's role from their last sign-in.

func (*External) RememberUser added in v0.9.0

func (e *External) RememberUser(name string, r Role, groups []string)

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

func (e *External) RoleOf(name string) Role

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

func (e *External) SSOIdentity(username string, groups []string) Identity

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.

func (*External) SetRoleFallback added in v0.9.0

func (e *External) SetRoleFallback(fn func(user string, groups []string) Role)

SetRoleFallback sets a fallback function when LDAP/OIDC groups do not map to a global role.

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.

func (Groups) RoleOf

func (g Groups) RoleOf(name string) Role

RoleOf returns the highest role the user's group memberships give.

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

func (m *Manager) CompleteLogin(remote, pending, code string) (Identity, string, error)

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) External

func (m *Manager) External() *External

External is the external sign-in configuration (nil when not set up).

func (*Manager) Login

func (m *Manager) Login(ctx context.Context, remote, name, password string) (string, error)

Login checks the credentials and returns a new session token.

func (*Manager) Logout

func (m *Manager) Logout(token string)

func (*Manager) NewSession

func (m *Manager) NewSession(id Identity) (string, error)

NewSession starts a session for someone already authenticated (OpenID Connect).

func (*Manager) RoleOf

func (m *Manager) RoleOf(user string) Role

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

func (m *Manager) SetExternal(e *External)

SetExternal adds LDAP / OpenID Connect sign-in (local accounts keep working first).

func (*Manager) SetTwoFactor

func (m *Manager) SetTwoFactor(t *TwoFactor)

SetTwoFactor enables one-time codes for the accounts that turned them on.

func (*Manager) TwoFactor

func (m *Manager) TwoFactor() *TwoFactor

TwoFactor is the code store (nil when not available).

func (*Manager) User

func (m *Manager) User(token string) (Identity, bool)

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).

func (*Manager) Valid

func (m *Manager) Valid(token string) bool

Valid reports whether the session still exists, without refreshing it (for long streams).

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 PAM

type PAM struct{ Service string }

PAM is unavailable in this build; see pam.go.

func (PAM) Authenticate

func (PAM) Authenticate(context.Context, string, string) error

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 ParseRole

func ParseRole(s string) (Role, error)

func (Role) MarshalJSON

func (r Role) MarshalJSON() ([]byte, error)

func (Role) String

func (r Role) String() string

func (*Role) UnmarshalJSON

func (r *Role) UnmarshalJSON(b []byte) error

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

func OpenTokens(path string) (*Tokens, error)

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.

func (*Tokens) List

func (t *Tokens) List(owner string) []Token

List returns the tokens of owner, or all tokens when owner is "".

func (*Tokens) Revoke

func (t *Tokens) Revoke(by Identity, id string) error

Revoke deletes token id. Non-admins may only revoke their own tokens.

func (*Tokens) Verify

func (t *Tokens) Verify(presented string) (Token, bool)

Verify checks a presented token and returns its owner and role (without the secret hash).

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 OpenTwoFactor(path string) (*TwoFactor, error)

func (*TwoFactor) Begin

func (t *TwoFactor) Begin(user, issuer string) (secret, uri string, err error)

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

func (t *TwoFactor) Confirm(user, code string) ([]string, error)

Confirm turns 2FA on once the user proves their app has the secret, and returns fresh recovery codes (shown once).

func (*TwoFactor) Disable

func (t *TwoFactor) Disable(user string) error

Disable turns 2FA off for the user (the caller checked who may do that).

func (*TwoFactor) Enabled

func (t *TwoFactor) Enabled(user string) bool

Enabled reports whether the user must give a code when signing in.

func (*TwoFactor) Status

func (t *TwoFactor) Status(user string) TwoFactorStatus

func (*TwoFactor) Users

func (t *TwoFactor) Users() []string

Users lists who has 2FA on (admins see it next to their reset button).

func (*TwoFactor) Verify

func (t *TwoFactor) Verify(user, code string) error

Verify checks a sign-in code: a TOTP code, or one of the recovery codes (used up).

type TwoFactorStatus

type TwoFactorStatus struct {
	Enabled      bool      `json:"enabled"`
	Since        time.Time `json:"since,omitzero"`
	RecoveryLeft int       `json:"recoveryLeft"`
	PendingSetup bool      `json:"pendingSetup"`
}

TwoFactorStatus is what the account page shows.

Jump to

Keyboard shortcuts

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