auth

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 22 Imported by: ? 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 decides who may use a Beacon app. Pilot, Prism, Haul and Pulse share it, so the rules and the settings page are the same in all four.

There is one setting with three values:

  • none (the default): anyone on the local network gets in without logging in; connections from anywhere else are refused.
  • disabled_for_local: the local network gets in without logging in; connections from anywhere else log in with a username and password.
  • enabled: everyone logs in.

"Local" means loopback, the private address ranges, link-local, and any extra ranges the owner lists (Settings.LocalNetworks).

The app's API key, in an X-Api-Key header or an apikey query parameter, is accepted in every mode: it is how scripts and the other apps get in.

Index

Constants

View Source
const (
	// RequiredNone needs no login on the local network and refuses
	// everyone else. The default.
	RequiredNone = "none"
	// RequiredOutside needs no login on the local network; everyone
	// else logs in.
	RequiredOutside = "disabled_for_local"
	// RequiredEverywhere needs a login from every address.
	RequiredEverywhere = "enabled"
)

The values of Settings.Required.

View Source
const DefaultSessionTTL = 30 * 24 * time.Hour

DefaultSessionTTL is how long a browser session stays valid after login.

Variables

View Source
var ErrWrongPassword = errors.New("the current password is wrong")

ErrWrongPassword is returned by ConfirmPassword.

View Source
var PasswordIterations = 600_000

PasswordIterations is the PBKDF2-SHA256 work factor for new hashes (OWASP 2023 guidance). Existing hashes keep the count they were made with, so raising this never locks anyone out. Tests lower it.

Functions

func CheckPassword

func CheckPassword(hash, password string) bool

CheckPassword reports whether password matches a hash from HashPassword. A malformed hash never matches.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns "pbkdf2-sha256$<iterations>$<salt>$<hash>".

func ListFromEnv

func ListFromEnv(name string) []string

ListFromEnv reads a comma-separated list from an environment variable, for apps that take AllowedHosts or LocalNetworks that way.

func LoadOrCreateKey

func LoadOrCreateKey(path string) (key string, created bool, err error)

LoadOrCreateKey returns the API key kept in path, making a new random one the first time. Apps that aren't given a key in their config use it so the key, and with it every login session, survives a restart.

func ParseNetworks

func ParseNetworks(list []string) ([]netip.Prefix, error)

ParseNetworks reads a list of address ranges, skipping blanks and duplicates. It fails on the first entry that isn't one, and on a range so wide it would make the whole internet local.

func ViaAPIKey

func ViaAPIKey(ctx context.Context) bool

ViaAPIKey reports whether the request behind ctx was made with the app's API key, as scripts and the other apps do, rather than from a browser let in by address or by a login. Handlers use it to keep secrets out of answers to browsers. ctx must come from a request that passed Middleware.

Types

type Auth

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

Auth authenticates requests for one app.

Sec-Fetch-Site is deliberately not a credential: any non-browser client can set it. It is only used as a cross-site check on requests let in by a cookie or by address, where the browser guarantees its value.

Sessions are stateless HMAC-signed tokens. The signing key is derived from the API key and the password hash, so rotating the API key or changing the password ends every session.

func New

func New(opts Options, settings Settings) *Auth

New builds an Auth. Invalid entries in settings.LocalNetworks are dropped.

func Open

func Open(opts Options, dir string, seed Settings) (*Auth, error)

Open builds an Auth whose settings live in dir/auth.json. When nothing has been saved there yet it starts from seed (for example values an older version kept in the app's config file).

func (*Auth) CallerAddress

func (a *Auth) CallerAddress(ctx context.Context) (addr string, local bool)

CallerAddress is the address the app saw the request come from, and whether it counts as local. The settings page shows it, because behind some container setups and proxies it is not the address the owner expects. ctx must come from a request that passed Middleware.

func (*Auth) ConfirmPassword

func (a *Auth) ConfirmPassword(ctx context.Context, password string) error

ConfirmPassword checks the current password before a change to the login settings, so a device that is merely on the network (let in without a login) can't replace the password and lock the owner out. A request made with the API key doesn't need it: the key is the stronger credential and is how a forgotten password gets reset. With no login set up there is nothing to confirm.

ctx must come from a request that passed Middleware.

func (*Auth) CookieName

func (a *Auth) CookieName() string

CookieName is the name of the session cookie.

func (*Auth) LoginHandler

func (a *Auth) LoginHandler() http.HandlerFunc

LoginHandler exchanges a username and password for a session cookie.

POST /api/v1/auth/login  {"username": "...", "password": "..."}

func (*Auth) LogoutHandler

func (a *Auth) LogoutHandler() http.HandlerFunc

LogoutHandler clears the session cookie. Sessions are stateless, so a copied cookie stays valid until it expires, the API key is rotated or the password changes.

POST /api/v1/auth/logout

func (*Auth) Middleware

func (a *Auth) Middleware(next http.Handler) http.Handler

Middleware rejects requests that are not authenticated. Mount it on the route group that holds every protected route, not as a global path-prefix filter, so a route can't slip past it through path tricks.

func (*Auth) SetAllowedHosts

func (a *Auth) SetAllowedHosts(hosts []string)

SetAllowedHosts replaces the extra host names trusted for access without a login.

func (*Auth) SetSettings

func (a *Auth) SetSettings(s Settings) error

SetSettings replaces the settings and saves them to the Store. Changing the password hash ends every session.

func (*Auth) Settings

func (a *Auth) Settings() Settings

Settings returns the current settings.

func (*Auth) StatusHandler

func (a *Auth) StatusHandler() http.HandlerFunc

StatusHandler tells the UI whether it is signed in and whether a login form makes sense. Unauthenticated.

GET /api/v1/auth/status

func (*Auth) WouldLockOut

func (a *Auth) WouldLockOut(ctx context.Context, next Settings) bool

WouldLockOut reports whether the caller behind ctx could no longer reach the app under next: it got in by address, and next neither counts that address as local nor offers a login.

type ErrTooManyAttempts

type ErrTooManyAttempts struct{ Wait time.Duration }

ErrTooManyAttempts is returned by ConfirmPassword and carries how long to wait.

func (ErrTooManyAttempts) Error

func (e ErrTooManyAttempts) Error() string

type FileStore

type FileStore struct {
	Path string
}

FileStore keeps the login settings in one JSON file next to the app's database, readable only by the app's user. Deleting the file puts the app back to no login, which is how a forgotten password is recovered by someone with access to the files.

func (FileStore) Load

func (f FileStore) Load() (s Settings, found bool, err error)

Load reads the saved settings. found is false when nothing has been saved yet.

func (FileStore) Save

func (f FileStore) Save(s Settings) error

Save writes the settings, replacing the file in one step so a crash can't leave half of it.

type Method

type Method int

Method is how a request was let in.

const (
	MethodNone Method = iota
	MethodAPIKey
	MethodSession
	MethodLocal
)

The ways a request can be let in.

func (Method) String

func (m Method) String() string

String is the name reported by the status endpoint.

type Options

type Options struct {
	// App is the app's display name, used in messages ("Pilot").
	App string
	// CookieName names the session cookie. Defaults to "<app>_session".
	CookieName string
	// APIKey is the app's API key. Without one, API-key access and
	// logins are unavailable (sessions are signed with it); local
	// access still works.
	APIKey string
	// AllowedHosts are extra host names the app may be opened under
	// without a login from the local network (see host.go).
	AllowedHosts []string
	// LocalNetworks are address ranges (CIDR) from the app's config file
	// or environment that always count as local, on top of the ones in
	// Settings. They can't be removed from the settings page.
	LocalNetworks []string
	// Store, when set, is where SetSettings persists changes.
	Store Store
}

Options configures an Auth.

type Settings

type Settings struct {
	// Required is RequiredNone, RequiredOutside or RequiredEverywhere.
	// Anything else is treated as RequiredNone.
	Required string `json:"required"`
	// Username and PasswordHash (from HashPassword) are the login. Both
	// empty means no login is set up.
	Username     string `json:"username"`
	PasswordHash string `json:"password_hash"`
	// LocalNetworks are extra address ranges (CIDR) that count as the
	// local network, for homes that don't use a private range or setups
	// where the app sees an unusual address (a VPN, some container
	// networks).
	LocalNetworks []string `json:"local_networks"`
}

Settings is the part of authentication the owner can change.

func (Settings) CredentialsConfigured

func (s Settings) CredentialsConfigured() bool

CredentialsConfigured reports whether a username and password are set.

func (Settings) Mode

func (s Settings) Mode() string

Mode is the rule actually applied. A mode that needs a login falls back to RequiredNone when no login is set up, so nobody is locked out by a half-finished change.

type Store

type Store interface {
	Save(Settings) error
}

Store saves settings changed from the settings page.

Directories

Path Synopsis
Package authapi is the login settings API, the same in every Beacon app.
Package authapi is the login settings API, the same in every Beacon app.

Jump to

Keyboard shortcuts

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