auth

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 19 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 implements accounts, sessions, API tokens, the setup code, brute-force limits and the audit entries of these actions (spec 10). It owns the write domain auth (spec 7.5) and talks to storage only through storage.AuthStore.

Index

Constants

View Source
const (
	ViaSession = "session"
	ViaToken   = "token"
	ViaCLI     = "cli"
)

Ways a principal authenticated.

View Source
const (
	ReasonTooShort  = "too_short"
	ReasonTooLong   = "too_long"
	ReasonTooCommon = "too_common"
)

Password policy reasons of a PasswordError.

View Source
const (
	ActionSetup        = "setup"
	ActionLogin        = "login"
	ActionLoginFailed  = "login_failed"
	ActionLogout       = "logout"
	ActionUserAdd      = "user_add"
	ActionUserDelete   = "user_delete"
	ActionUserPassword = "user_password"
	ActionTokenCreate  = "token_create"
	ActionTokenRevoke  = "token_revoke"
)

Audit actions.

View Source
const (
	MinPasswordLen = 12
)

Password policy (spec 10).

View Source
const ScopeAdmin = "admin"

Scope of API tokens (spec 10; "control" is reserved).

View Source
const SessionCookie = "pvmon_session"

SessionCookie is the name of the session cookie (spec 10).

Variables

View Source
var (
	ErrUnauthorized  = errors.New("auth: unauthorized")
	ErrBadCredential = errors.New("auth: invalid name or password")
	ErrSetupCode     = errors.New("auth: invalid setup code")
	ErrSetupDone     = errors.New("auth: setup already done")
	ErrNameTaken     = errors.New("auth: name already taken")
	ErrInvalid       = errors.New("auth: invalid input")
	ErrNotFound      = errors.New("auth: not found")
	ErrLastUser      = errors.New("auth: the last user cannot be deleted")
)

Errors for branching in handlers and CLI jobs.

Functions

func CheckPassword

func CheckPassword(pw string) error

CheckPassword applies the password policy without hashing, so CLI jobs can reject a weak password before they make a backup.

func IsClientError

func IsClientError(err error) bool

IsClientError reports whether err is the caller's fault (validation, policy, not found).

func WithClient

func WithClient(ctx context.Context, c Client) context.Context

WithClient returns ctx carrying c.

func WithPrincipal

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

WithPrincipal returns ctx carrying p.

Types

type AuditInfo

type AuditInfo struct {
	ID     int64           `json:"id"`
	At     time.Time       `json:"at"`
	Actor  string          `json:"actor,omitempty"`
	Action string          `json:"action"`
	Detail json.RawMessage `json:"detail,omitempty"` // JSON object, never secrets
}

AuditInfo is one audit entry.

type Client

type Client struct {
	IP    string // remote address, or the forwarded client of a trusted proxy
	HTTPS bool   // direct TLS or X-Forwarded-Proto https from a trusted proxy
}

Client describes where a request came from, resolved by the proxy middleware.

func ClientFrom

func ClientFrom(ctx context.Context) Client

ClientFrom returns the client of ctx; the zero Client when none was set.

type Deps

type Deps struct {
	Store storage.AuthStore
	Clock util.Clock
	Rand  io.Reader // crypto/rand.Reader in production
	Log   zerolog.Logger
}

Deps are the dependencies of the service.

type Login

type Login struct {
	Token   string // session token for the cookie; never logged
	User    UserInfo
	Expires time.Time // absolute end of the session
}

Login is the result of a successful login or setup.

type NewToken

type NewToken struct {
	TokenInfo
	Token string `json:"token"`
}

NewToken is a created token; Token is shown exactly once.

type PasswordError

type PasswordError struct{ Reason string }

PasswordError reports a password that does not meet the policy.

func (*PasswordError) Error

func (e *PasswordError) Error() string

type Principal

type Principal struct {
	UserID  int64
	Name    string // user name, or token name for tokens
	Via     string // ViaSession, ViaToken or ViaCLI
	TokenID string
	// contains filtered or unexported fields
}

Principal is an authenticated caller.

func CLI

func CLI() Principal

CLI is the principal of CLI jobs.

func PrincipalFrom

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

PrincipalFrom returns the principal of ctx; ok is false for anonymous requests.

func (Principal) Actor

func (p Principal) Actor() string

Actor is the audit actor of p: "user:<name>", "token:<id>" or "cli".

type RateLimitError

type RateLimitError struct{ RetryAfter time.Duration }

RateLimitError means too many failed attempts; retry after RetryAfter.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type Service

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

Service implements authentication and account management.

func New

func New(s Settings, d Deps) (*Service, error)

New builds the service and draws the setup code of this process (spec 10).

func (*Service) AddUser

func (s *Service) AddUser(ctx context.Context, by Principal, name, pw, lang string,
) (UserInfo, error)

AddUser creates an admin.

func (*Service) Audit

func (s *Service) Audit(ctx context.Context, from, to time.Time) ([]AuditInfo, error)

Audit returns the audit entries in [from, to), newest first (at most 1000).

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, token string) (Principal, error)

Authenticate resolves a session token; expired or unknown sessions are ErrUnauthorized.

func (*Service) AuthenticateToken

func (s *Service) AuthenticateToken(ctx context.Context, token string) (Principal, error)

AuthenticateToken resolves an API token pvm_<id>_<secret>.

func (*Service) CreateToken

func (s *Service) CreateToken(ctx context.Context, by Principal, name string,
	expires time.Duration,
) (NewToken, error)

CreateToken creates an admin token; expires 0 = never.

func (*Service) DeleteUser

func (s *Service) DeleteUser(ctx context.Context, by Principal, id int64) error

DeleteUser deletes a user with its sessions and tokens; never the last one.

func (*Service) Login

func (s *Service) Login(ctx context.Context, name, pw, ip string) (Login, error)

Login checks name and password. Unknown names and wrong passwords answer the same way and take the same time (spec 10).

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, p Principal) error

Logout deletes the session of p server-side.

func (*Service) RevokeToken

func (s *Service) RevokeToken(ctx context.Context, by Principal, id string) error

RevokeToken deletes a token.

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, by Principal, id int64, pw string) error

SetPassword replaces a user's password and ends all of their sessions.

func (*Service) Setup

func (s *Service) Setup(ctx context.Context, r SetupRequest) (Login, error)

Setup creates the first admin with the setup code and logs them in.

func (*Service) SetupCode

func (s *Service) SetupCode() string

SetupCode returns the setup code of this process; "" once it was used.

func (*Service) SetupRequired

func (s *Service) SetupRequired(ctx context.Context) (bool, error)

SetupRequired reports whether no user exists yet.

func (*Service) Tokens

func (s *Service) Tokens(ctx context.Context) ([]TokenInfo, error)

Tokens lists all API tokens.

func (*Service) UserByName

func (s *Service) UserByName(ctx context.Context, name string) (UserInfo, error)

UserByName returns one user (CLI jobs).

func (*Service) Users

func (s *Service) Users(ctx context.Context) ([]UserInfo, error)

Users lists all users.

type Settings

type Settings struct {
	SessionIdle time.Duration
	SessionMax  time.Duration
}

Settings are the session lifetimes (auth.session_idle, auth.session_max).

type SetupRequest

type SetupRequest struct {
	Code, Name, Password, Lang, IP string
}

SetupRequest creates the first admin (POST /api/v1/setup).

type TokenInfo

type TokenInfo struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	Scope     string     `json:"scope"`
	CreatedAt time.Time  `json:"created_at"`
	ExpiresAt *time.Time `json:"expires_at"`
	LastUsed  *time.Time `json:"last_used"`
}

TokenInfo is an API token without its secret.

type UserInfo

type UserInfo struct {
	ID        int64      `json:"id"`
	Name      string     `json:"name"`
	Lang      string     `json:"lang,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	LastLogin *time.Time `json:"last_login"`
}

UserInfo is a user without its password hash.

Jump to

Keyboard shortcuts

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