auth

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 22 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 owns everything Outpost knows about people: users, groups, password hashes, sessions and the keys that sign identity tokens. It knows nothing about HTTP; the gateway builds on it.

It keeps its own database, auth.db, rather than sharing state.db. state.db is a cache of observed reality that `outpost apply` can rebuild from the manifests, and there is a test holding it to that. Users and password hashes are not observed reality: nothing can rebuild them, so they live somewhere that can be backed up and is never treated as disposable.

Index

Constants

View Source
const AccessTokenPrefix = "opat_"

AccessTokenPrefix starts every personal access token. It is how the gateway tells one of its own from a bearer token that belongs to the app behind it.

View Source
const AccessTokenTouchEvery = time.Hour

AccessTokenTouchEvery is how often a token's last-used time moves. Scripts can call far more often than anyone needs that time to be accurate, and each move is a database write.

View Source
const KeyGracePeriod = 24 * time.Hour

KeyGracePeriod is how long a retired key stays in the JWKS. Identity tokens live for a minute, so a day is far more than any token needs; the slack is for apps that cache the key set.

View Source
const MinPasswordLen = 12

MinPasswordLen is the only rule a password has to meet. Length is what makes a password hard to guess; composition rules mostly make it hard to remember.

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

PortalSessionTTL is how long a session lasts without being used.

View Source
const RefreshAfter = 24 * time.Hour

RefreshAfter is how stale a session's expiry has to be before a touch slides it forward. Sliding on every request would mean a database write per request for no practical gain.

Variables

View Source
var (
	ErrUserExists     = errors.New("user already exists")
	ErrNoSuchUser     = errors.New("no such user")
	ErrBadCredentials = errors.New("wrong username or password")
)
View Source
var DefaultParams = Params{Memory: 64 * 1024, Time: 3, Threads: 1, SaltLen: 16, KeyLen: 32}

DefaultParams are the settings new hashes use.

View Source
var ErrNoSuchAccessToken = errors.New("no such access token")

ErrNoSuchAccessToken covers a token that was never issued, has expired, was revoked, or belongs to a disabled user. Callers treat them all the same, and a client isn't told which.

View Source
var ErrNoSuchSession = errors.New("no such session")

ErrNoSuchSession covers a token that was never issued, has expired, was revoked, or belongs to a disabled user. Callers treat them all the same: send the browser to log in.

Functions

func HashPassword

func HashPassword(pw string, p Params) (string, error)

HashPassword hashes pw with p, in PHC string format: $argon2id$v=19$m=65536,t=3,p=1$<salt>$<key>.

func HashToken

func HashToken(tok string) string

HashToken is what the database stores in place of a token, so a copy of auth.db doesn't yield usable cookies. A plain SHA-256 is enough: the input is 256 random bits, not something a dictionary could guess.

func JWKS

func JWKS(keys []SigningKey) ([]byte, error)

JWKS renders the public halves of keys as a JSON Web Key Set (RFC 8037), which is what an app fetches to verify X-Outpost-Identity.

func NeedsRehash

func NeedsRehash(encoded string, p Params) bool

NeedsRehash reports whether encoded was made with settings other than p, so a successful login can upgrade it.

func NewToken

func NewToken() (string, error)

NewToken returns a fresh random token: 32 bytes, base64url without padding, so it can go in a cookie or a query string as is.

func ValidGroup

func ValidGroup(s string) error

ValidGroup reports whether s can be used as a group name. Groups follow the username rule because they travel the same way, in X-Outpost-Groups.

func ValidPassword

func ValidPassword(p string) error

ValidPassword checks a new password's length, counted in characters.

func ValidUsername

func ValidUsername(s string) error

ValidUsername reports whether s can be used as a username.

func VerifyPassword

func VerifyPassword(pw, encoded string) (bool, error)

VerifyPassword reports whether pw matches encoded. A wrong password is (false, nil); an error means the stored hash itself is unusable.

Types

type AccessToken

type AccessToken struct {
	ID         int64
	Username   string
	Name       string
	Apps       []string // sorted; empty means every app the user may reach
	CreatedAt  time.Time
	ExpiresAt  time.Time // zero means never
	LastUsedAt time.Time // zero means never; up to AccessTokenTouchEvery behind
}

AccessToken is one personal access token as callers see it. It carries no hash and no secret.

func (AccessToken) Expired

func (t AccessToken) Expired(now time.Time) bool

Expired reports whether the token had run out by now.

func (AccessToken) Reaches

func (t AccessToken) Reaches(app string) bool

Reaches reports whether the token's scope covers an app. It says nothing about whether the user may open the app, which is decided at each request.

type Params

type Params struct {
	Memory  uint32 // KiB
	Time    uint32
	Threads uint8
	SaltLen uint32
	KeyLen  uint32
}

Params are argon2id's cost settings. They're stored in every hash, so they can be raised later without invalidating existing passwords.

type Session

type Session struct {
	Username  string
	App       string // empty for the portal session
	CreatedAt time.Time
	ExpiresAt time.Time
}

Session is one live login.

type SignIn

type SignIn struct {
	// ID names the sign-in to the account page. It is the portal session's
	// stored hash, which can't be turned back into the token.
	ID        string
	UserAgent string
	// IP is the address the sign-in came from, "" for one from before
	// addresses were kept.
	IP        string
	CreatedAt time.Time
	// LastSeen is the latest use of the portal session or any app under it.
	LastSeen time.Time
	// Apps are the apps opened in it, by name, sorted.
	Apps []string
}

SignIn is one login: a portal session and the app sessions it handed out, which end with it.

type SigningKey

type SigningKey struct {
	ID        string // kid: base64url(sha256(pub))[:16]
	Private   ed25519.PrivateKey
	CreatedAt time.Time
	RetiredAt time.Time // zero while current
}

SigningKey is one Ed25519 key for identity tokens.

func GenerateKey

func GenerateKey(now time.Time) (SigningKey, error)

GenerateKey makes a new signing key.

func (SigningKey) Public

func (k SigningKey) Public() ed25519.PublicKey

Public returns the key's public half.

type Store

type Store struct {

	// Params are the argon2id settings for new hashes. Tests lower them.
	Params Params
	// contains filtered or unexported fields
}

Store is the SQLite-backed auth store. It is safe for concurrent use.

func Open

func Open(path string) (*Store, error)

Open opens (creating if needed) the auth database at path.

func (*Store) AddUser

func (s *Store) AddUser(u User, password string) error

AddUser creates a user. An empty password creates one who can't log in until a password is set, so an account can be made before it's handed over.

func (*Store) Authenticate

func (s *Store) Authenticate(username, password string) (User, error)

Authenticate checks a username and password. Every failure, whether the user is unknown, disabled, has no password or gave the wrong one, takes the same time and returns ErrBadCredentials, so the answer reveals nothing about which accounts exist.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) CountAccessTokens

func (s *Store) CountAccessTokens(username string) (int, error)

CountAccessTokens reports how many unexpired tokens a user has, so whatever is about to end them can say so.

func (*Store) CountAdmins

func (s *Store) CountAdmins() (int, error)

CountAdmins reports how many enabled admins there are.

func (*Store) CreateAccessToken

func (s *Store) CreateAccessToken(username, name string, apps []string, ttl time.Duration) (string, AccessToken, error)

CreateAccessToken issues a token for a user and returns its secret, which is never stored and can't be recovered. No apps means every app the user may reach. A ttl of zero means it doesn't expire.

func (*Store) CreateSession

func (s *Store) CreateSession(username, app, parentToken, userAgent string) (string, error)

CreateSession starts a session and returns its token, which is never stored. A portal session has no app and no parent. An app session names the app and the portal session it came from; ending the portal session ends it.

func (*Store) CreateSessionFrom

func (s *Store) CreateSessionFrom(username, app, parentToken, userAgent, ip string) (string, error)

CreateSessionFrom is CreateSession, also keeping the client address the sign-in came from, so the user can tell their sign-ins apart by something other than what their browser claims to be.

func (*Store) CurrentKey

func (s *Store) CurrentKey() (SigningKey, error)

CurrentKey returns the key new tokens are signed with, generating the first one on demand.

func (*Store) EndOtherSignIns

func (s *Store) EndOtherSignIns(username, keep string) (int, error)

EndOtherSignIns ends every sign-in a user has except keep, the one they are using, and reports how many ended.

func (*Store) EndSignIn

func (s *Store) EndSignIn(username, id string) error

EndSignIn ends one of a user's sign-ins, by its ID, with every app session under it. A sign-in that is already over, or isn't theirs, is ErrNoSuchSession, so one user can't end another's by guessing.

func (*Store) GetUser

func (s *Store) GetUser(username string) (User, error)

GetUser returns one user.

func (*Store) ListAccessTokens

func (s *Store) ListAccessTokens(username string) ([]AccessToken, error)

ListAccessTokens returns one user's tokens, or everyone's when username is empty, oldest first. Expired tokens stay listed until revoked, so whoever is working out why a script stopped can see the reason.

func (*Store) ListUsers

func (s *Store) ListUsers() ([]User, error)

ListUsers returns every user, sorted by username.

func (*Store) LookupAccessToken

func (s *Store) LookupAccessToken(secret string) (AccessToken, User, error)

LookupAccessToken returns the token a secret names and the user it belongs to, as they are now: the user's groups and admin bit are never a copy from when the token was made.

func (*Store) LookupSession

func (s *Store) LookupSession(token string) (Session, User, error)

LookupSession returns the session a token names and the user it belongs to. An app session is only as alive as its parent.

func (*Store) PruneExpired

func (s *Store) PruneExpired() (int, error)

PruneExpired deletes expired sessions, and app sessions whose parent is gone, and reports how many rows went.

func (*Store) PublishedKeys

func (s *Store) PublishedKeys() ([]SigningKey, error)

PublishedKeys returns the keys an app should accept: the current one, then any retired within KeyGracePeriod, newest first.

func (*Store) RemoveUser

func (s *Store) RemoveUser(username string) error

RemoveUser deletes a user; their groups, sessions and access tokens go with them.

func (*Store) RevokeAccessToken

func (s *Store) RevokeAccessToken(id int64) (AccessToken, error)

RevokeAccessToken ends one token and returns what it was.

func (*Store) RevokeFamily

func (s *Store) RevokeFamily(token string) error

RevokeFamily ends the login a session belongs to: its portal session and every app session under it. Logging out from any app host means this. A token that names no live session is not an error.

func (*Store) RevokeSession

func (s *Store) RevokeSession(token string) error

RevokeSession ends a session and every app session derived from it. Revoking a session that doesn't exist is not an error: logging out twice should just work.

func (*Store) RevokeUserAccess

func (s *Store) RevokeUserAccess(username string) (sessions, tokens int, err error)

RevokeUserAccess ends every session and access token a user has and reports how many of each. Counts are of live ones only: expired rows awaiting a prune were already over, and reporting them as ended would overstate what this did.

func (*Store) RevokeUserSessions

func (s *Store) RevokeUserSessions(username string) (int, error)

RevokeUserSessions ends every session and access token a user has and reports how many sessions.

func (*Store) RotateKey

func (s *Store) RotateKey() (SigningKey, error)

RotateKey retires the current key, makes a new one current, and deletes keys retired longer ago than KeyGracePeriod.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion() (string, error)

SchemaVersion reports the schema version recorded in the database.

func (*Store) SetAdmin

func (s *Store) SetAdmin(username string, admin bool) error

SetAdmin grants or revokes admin.

func (*Store) SetDisabled

func (s *Store) SetDisabled(username string, disabled bool) error

SetDisabled turns a user's access off or back on. Disabling ends their sessions and access tokens; enabling doesn't restore them.

func (*Store) SetPassword

func (s *Store) SetPassword(username, password string) error

SetPassword replaces a user's password and ends every session and access token they have, so a password changed because it leaked actually locks the holder out: anyone who knew it could have had a token made in the meantime.

func (*Store) SignIns

func (s *Store) SignIns(username string) ([]SignIn, error)

SignIns lists a user's live sign-ins, most recently used first.

func (*Store) TouchAccessToken

func (s *Store) TouchAccessToken(t AccessToken) error

TouchAccessToken records that a token was used, if the time recorded is due to move, so a busy script isn't a database write per request.

func (*Store) TouchFamily

func (s *Store) TouchFamily(token string) error

TouchFamily records that a session was used, sliding it and, for an app session, its portal session too, each on TouchSession's terms. Using any app counts as using the login, so someone who only ever opens one app isn't sent back to the login page when the untouched portal session runs out.

func (*Store) TouchSession

func (s *Store) TouchSession(token string) error

TouchSession records that a session was used. Its expiry slides forward to a full PortalSessionTTL, but only once it was last set more than RefreshAfter ago.

func (*Store) UpdateGroups

func (s *Store) UpdateGroups(username string, add, remove []string) ([]string, error)

UpdateGroups adds and removes group memberships and returns the result. Adding a group the user is already in, or removing one they aren't, is not an error.

type User

type User struct {
	Username    string
	DisplayName string
	Email       string
	Admin       bool
	Disabled    bool
	Groups      []string // sorted
	HasPassword bool
	CreatedAt   time.Time
	LastLoginAt time.Time
	Sessions    int // live sessions, for `user list`
}

User is one person who can log in, as callers see them. It carries no hash.

Jump to

Keyboard shortcuts

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