auth

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package auth holds backd's identity model: users, their sign-in identities and password handling. It is storage-neutral; MongoDB specifics live behind Store in internal/mongodb.

A user carries no credentials. Each way of signing in is an Identity (provider + subject), so adding login providers later only adds identities: a password user has a "password" identity, and a user who signs in only through another provider needs none.

Index

Constants

View Source
const (
	AuditUserCreate      = "user.create"   // by an administrator (or bootstrap)
	AuditUserSignup      = "user.signup"   // self-service sign-up
	AuditUserPassword    = "user.password" // set by an administrator
	AuditPasswordChange  = "user.password_change"
	AuditUserVerifyEmail = "user.verify_email" // details: verified
	AuditUserDisable     = "user.disable"
	AuditUserEnable      = "user.enable"
	AuditUserDelete      = "user.delete"
	AuditAccountDelete   = "user.delete_account" // self-service
	AuditUserNetworks    = "user.networks"       // details: admin_networks, login_networks
	AuditRoleAdd         = "role.add"            // details: role
	AuditRoleRemove      = "role.remove"         // details: role
	AuditAPIKeyCreate    = "apikey.create"       // details: role, expires_at, networks
	AuditAPIKeyRevoke    = "apikey.revoke"
	AuditInviteCreate    = "invitation.create" // details: bound_to_email, expires_at
	AuditInviteRevoke    = "invitation.revoke"
	AuditAdminLogin      = "admin.login"   // login of a user holding an admin role
	AuditAdminRefused    = "admin.refused" // details: reason
	AuditBootstrap       = "realm.bootstrap"
	AuditSecretSet       = "secret.set"        // details: database ("": realm scope); never the value
	AuditSecretDelete    = "secret.delete"     // details: database
	AuditSecretsRotated  = "secret.rotate_key" // by backd secret rotate-key; details: count
)

Audit actions: security-sensitive changes and events, recorded in the realm's append-only audit trail.

View Source
const (
	// ActorConfig applies realm.yaml's role and network seeds.
	ActorConfig = "config:realm.yaml"
	// ActorBootstrap is `backd bootstrap`.
	ActorBootstrap = "cli:bootstrap"
	// ActorAnonymous is a caller without credentials.
	ActorAnonymous = "anonymous"
)

Actors that aren't a credential.

View Source
const (
	IdempotencyRunning = "running"
	IdempotencyDone    = "done"
)

Idempotency record statuses.

View Source
const (
	DefaultInvitationTTL = 7 * 24 * time.Hour
	MaxInvitationTTL     = 90 * 24 * time.Hour
)

Invitation lifetimes.

View Source
const (
	JobQueued  = "queued"
	JobRunning = "running"
	JobDone    = "done"
)

Job statuses.

View Source
const APIKeyPrefix = "bdk_"

APIKeyPrefix starts every API key; see SessionTokenPrefix.

View Source
const CallbackTokenPrefix = "bdf_"

CallbackTokenPrefix starts every callback token: the credential a function uses to reach the realm's data (ctx.db, ctx.admin.db) for the duration of one invocation.

View Source
const InvitationPrefix = "bdi_"

InvitationPrefix starts every invitation token.

View Source
const MaxPasswordLength = 128

MaxPasswordLength is the longest accepted password, in characters.

View Source
const ProviderPassword = "password"

ProviderPassword is the identity provider for email + password sign-in. Its subject is the user's id, so it doesn't depend on the email.

View Source
const SessionTokenPrefix = "bds_"

SessionTokenPrefix starts every session token, so tokens are easy to recognize (e.g. by secret scanners) and to tell apart from API keys.

Variables

View Source
var (
	ErrKeyNameTaken = errors.New("an API key with this name already exists")
	ErrKeyNotFound  = errors.New("API key not found")
)
View Source
var (
	ErrNotFound   = errors.New("user not found")
	ErrEmailTaken = errors.New("email is already registered")
	// ErrBusy means no password-hashing slot freed up before the deadline.
	ErrBusy = errors.New("too many password operations in progress; try again later")
)
View Source
var (
	// ErrInvitationRequired means the realm only accepts sign-ups with an invitation.
	ErrInvitationRequired = errors.New("sign-up requires an invitation")
	// ErrInvalidInvitation covers unknown, used, expired and mismatched
	// invitations alike.
	ErrInvalidInvitation = errors.New("invalid or expired invitation")
)
View Source
var (
	// ErrInvalidCredentials is the one answer to a failed login, whatever
	// the reason (unknown email, wrong password, no password, disabled).
	ErrInvalidCredentials = errors.New("invalid email or password")
	// ErrUnauthenticated means the token is unknown, expired, revoked or
	// belongs to a disabled user.
	ErrUnauthenticated = errors.New("invalid or expired token")
	// ErrSignupClosed means the realm doesn't allow self sign-up.
	ErrSignupClosed = errors.New("sign-up is not open in this realm")
)
View Source
var DefaultArgon2Params = Argon2Params{Memory: 64 * 1024, Time: 3, Threads: 1}

DefaultArgon2Params follow RFC 9106's second recommendation (64 MiB, 3 passes), with one thread per hash: concurrency is capped per instance instead.

View Source
var ErrInvalidCallback = errors.New("invalid or expired callback token")

ErrInvalidCallback means a callback token is malformed, forged or expired.

View Source
var ErrJobExists = errors.New("job already exists")

ErrJobExists means a job with that id was already enqueued.

View Source
var ErrNetworksOutsideRealm = errors.New("admin networks must lie within the realm's admin.allowed_networks")

ErrNetworksOutsideRealm means a user's admin networks aren't all inside the realm's admin.allowed_networks.

View Source
var ErrNotAllowedOnBehalf = errors.New("only API keys can act on behalf of a user")

ErrNotAllowedOnBehalf means a caller other than an API key tried to act on behalf of a user.

View Source
var ErrSecretNotFound = errors.New("secret not found")

ErrSecretNotFound means no secret is stored at that scope and name.

View Source
var ErrSecretsNotConfigured = errors.New("the secrets master key is not configured (BACKD_SECRETS_KEY)")

ErrSecretsNotConfigured means BACKD_SECRETS_KEY isn't set: secrets can be neither stored nor read.

View Source
var ErrUndeclaredRole = errors.New("role is not declared in realm.yaml")

ErrUndeclaredRole means a role isn't declared in the realm's realm.yaml.

View Source
var ErrUserDisabled = errors.New("user is disabled")

ErrUserDisabled means the user an API key acts for is disabled.

Functions

func CheckPassword

func CheckPassword(password string, minLength int) (string, error)

CheckPassword applies the length policy and returns the password in Unicode NFKC form, which is what gets hashed. Lengths count characters.

func DefaultHashConcurrency

func DefaultHashConcurrency(p Argon2Params) int

DefaultHashConcurrency is how many password hashes may run at once when PASSWORD_HASH_CONCURRENCY isn't set: no more than the Go scheduler's processors (GOMAXPROCS, which follows the container's CPU limit), and no more than fit in half the memory limit (the cgroup's, or GOMEMLIMIT), so a flood of logins can't get the process killed for running out of memory. runtime.NumCPU is not used: in a container it reports the host's CPUs.

func HashToken

func HashToken(token string) string

HashToken is the stored form of a token: hex SHA-256. Tokens are random and long, so a fast hash is enough.

func IPKey

func IPKey(ip string) string

IPKey groups client addresses for throttling: IPv4 addresses one by one, IPv6 by /64, since one client usually controls a whole /64.

func IdempotencyID

func IdempotencyID(database, name, callerSubject, key string) string

IdempotencyID builds a record's id: unique per function, per caller (Caller.Subject(), so ownership can never cross callers), per key.

func NewSessionToken

func NewSessionToken() (string, error)

NewSessionToken returns a new random session token (256 bits).

func ScheduledJobID

func ScheduledJobID(database, function string, scheduledAt time.Time) string

ScheduledJobID is the deterministic id of a scheduled run.

func SignCallback

func SignCallback(key []byte, c CallbackClaims) string

SignCallback returns a callback token for c, signed with key.

func WithAuditSource

func WithAuditSource(ctx context.Context, source func() AuditSource) context.Context

WithAuditSource returns a context whose audit records take their actor, request id and client address from source, called when a record is written (the actor may be known only after authentication).

Types

type APIKey

type APIKey struct {
	Name       string
	Role       KeyRole           // "" (stored before roles existed) counts as data
	Networks   registry.Networks // where the key may be used from; empty: anywhere
	Prefix     string            // first characters of the key, for recognizing it
	Hash       string
	CreatedAt  time.Time
	LastUsedAt *time.Time
	ExpiresAt  *time.Time // nil: never expires
}

APIKey is a realm API key for server-side callers. Only a hash of the key is stored.

func (APIKey) Expired

func (k APIKey) Expired(now time.Time) bool

Expired reports whether the key has expired at now.

func (APIKey) IsAdmin

func (k APIKey) IsAdmin() bool

IsAdmin reports whether the key may use the admin API.

type Argon2Params

type Argon2Params struct {
	Memory  uint32 // KiB
	Time    uint32
	Threads uint8
}

Argon2Params are argon2id cost parameters.

type Attempts

type Attempts struct {
	Failures      int
	LastFailureAt time.Time
}

Attempts is the failure counter of one key ("account:<email>" or "ip:<addr>").

type AuditFilter

type AuditFilter struct {
	Action, Actor, Target string
	Since, Until          time.Time // At >= Since, At < Until
	Limit, Skip           int
}

AuditFilter selects audit records. Zero fields match everything.

type AuditRecord

type AuditRecord struct {
	ID        string
	At        time.Time
	ExpiresAt time.Time // removed after this (the realm's retention)
	Action    string
	Actor     string // "user:<id>", "key:<name>", "anonymous", or an Actor* constant
	Target    string // "user:<id>", "key:<name>", "invitation:<id>", or ""
	Details   map[string]any
	RequestID string
	ClientIP  string
}

AuditRecord is one entry of the audit trail. It names users by id, keys by name and invitations by id, and never holds secrets: no passwords or hashes, tokens, keys, emails or request bodies.

type AuditSource

type AuditSource struct {
	Actor, RequestID, ClientIP string
}

AuditSource says who is acting and from where. The HTTP layer puts it in the request context; commands set their own.

type CallbackClaims

type CallbackClaims struct {
	Realm    string    `json:"r"`
	Function string    `json:"f"` // <database>/<name>
	UserID   string    `json:"u,omitempty"`
	KeyHash  string    `json:"k,omitempty"`
	Admin    bool      `json:"a,omitempty"`
	Expires  time.Time `json:"e"`
}

CallbackClaims are what a callback token carries: the function, the caller it acts as (a user, an API key, both for a key acting on behalf of a user, or neither for an anonymous caller) or full access (Admin), and when it expires (the invocation's deadline).

func VerifyCallback

func VerifyCallback(key []byte, token string, now time.Time) (CallbackClaims, error)

VerifyCallback checks a callback token's signature and expiry.

type Caller

type Caller struct {
	User *Principal  // the user whose rules apply
	Key  *APIKey     // set for API key callers
	Func *FuncCaller // set for a function's callbacks
}

Caller is whoever makes a request to a realm with auth enabled: a user with a session, a server-side caller with an API key, an API key acting on behalf of a user (both set), or anonymous (neither). A function calling back (Func set) acts as the caller that invoked it, or, with admin access, as itself.

func (Caller) Actor

func (c Caller) Actor() string

Actor names the caller for logs: the subject, and for an API key acting on behalf of a user, "key:<name> as user:<id>".

func (Caller) BypassesRules

func (c Caller) BypassesRules() bool

BypassesRules reports whether the caller has full access: an API key that isn't acting on behalf of a user, or a function's admin access.

func (Caller) Subject

func (c Caller) Subject() string

Subject is who the caller acts as, for ownership fields: "user:<id>", "key:<name>" or "anonymous".

type FuncCaller

type FuncCaller struct {
	Name  string // <realm>/<database>/<function>
	Admin bool   // ctx.admin.db: full access, recorded as the function
}

FuncCaller marks a caller as a function acting through a callback token.

type Hasher

type Hasher struct {
	Params Argon2Params
	// contains filtered or unexported fields
}

Hasher hashes and verifies passwords with argon2id. At most a fixed number of hashes run at once; callers queue for a slot until their context ends, which bounds memory under a flood of requests.

func NewHasher

func NewHasher(concurrency int, params Argon2Params) *Hasher

NewHasher returns a Hasher running at most concurrency hashes at once (DefaultHashConcurrency when concurrency < 1).

func (*Hasher) Concurrency

func (h *Hasher) Concurrency() int

Concurrency is how many hashes may run at once.

func (*Hasher) Hash

func (h *Hasher) Hash(ctx context.Context, password string) (string, error)

Hash returns the PHC-format argon2id hash of an already checked password.

func (*Hasher) Verify

func (h *Hasher) Verify(ctx context.Context, password, encoded string) (bool, error)

Verify reports whether password matches encoded. The password is normalized like CheckPassword does. Parameters are read from encoded, so hashes made with older parameters keep working.

type IdempotencyRecord

type IdempotencyRecord struct {
	ID          string // see IdempotencyID
	Function    string // <database>/<name>, for display
	CallerActor string
	InputHash   string     // sha256 of the exact input bytes
	Mode        string     // sync | async
	Status      string     // running | done
	Result      *JobResult // nil until done; a sync call's outcome
	JobID       string     // set once done, for async; "" for sync
	CreatedAt   time.Time
	ExpiresAt   time.Time
}

IdempotencyRecord ties one Idempotency-Key to its outcome, scoped to the function and the caller: two different callers can never collide on the same client-chosen key, even if they happen to pick the same string. Never stores input or output for keyless calls — this is the one deliberate exception, for calls that declare a key.

type Identity

type Identity struct {
	ID           string
	UserID       string
	Provider     string
	Subject      string // unique per provider
	PasswordHash string // ProviderPassword only: argon2id, PHC string format
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

Identity is one way a user signs in.

type Invitation

type Invitation struct {
	ID        string
	TokenHash string
	Email     string // "" if anyone holding the token may use it
	CreatedBy string // "key:<name>"
	CreatedAt time.Time
	ExpiresAt time.Time
}

Invitation lets one person sign up in a realm with `signup: invite`. Only a hash of its token is stored.

type InvocationFilter

type InvocationFilter struct {
	Function, RequestID string
	Since, Until        time.Time
	Limit, Skip         int
}

InvocationFilter selects invocation records. Zero fields match everything.

type InvocationRecord

type InvocationRecord struct {
	ID         string
	At         time.Time
	ExpiresAt  time.Time // removed after this (the realm's log retention)
	Function   string    // <database>/<name>
	Actor      string    // "user:<id>", "key:<name>", "anonymous", or "func:<name> as ..."
	Mode       string    // sync today; async, webhook later
	Status     string    // executor.Status* (ok, function_error, timeout, memory, cpu, crash, ...)
	Code       string    // the function's own error code, when Status is function_error
	DurationMS int64
	RequestID  string
	JobID      string // async jobs (roadmap F11); empty until then
	Logs       []LogLine
}

InvocationRecord is one function call, recorded in the realm's system database (roadmap F10). Inputs and outputs are never stored — only what's needed to debug what happened and read the function's own logs.

type Job

type Job struct {
	ID            string
	Database      string
	Function      string // name only; Database plus this is the function
	Input         json.RawMessage
	CallerActor   string // for display: "user:<id>", "key:<name>", "anonymous"
	CallerUserID  string // "" unless the caller was a signed-in user
	CallerKeyHash string // "" unless the caller was an API key
	Scheduled     bool   // created by the function's cron schedule, acts as the function itself
	TimeoutMS     int64  // the function's timeout at enqueue time, for the worker's lease
	RequestID     string
	Status        string // queued | running | done
	Attempts      int
	CreatedAt     time.Time
	CompletedAt   time.Time // zero until done
	ExpiresAt     time.Time
	Result        *JobResult // nil until done
}

Job is one async function call (roadmap F11), stored in the realm's system database until it's claimed, run, and its result read or expired. Unlike sync calls, whose input and output are never stored, a job's input and result are — there's nowhere else to keep them until the caller reads them back.

type JobFilter

type JobFilter struct {
	Database, Function string    // Function is the name only; "" matches every function
	Status             string    // queued, running or done
	Scheduled          *bool     // nil: both; true: cron runs only; false: called ones only
	Since, Until       time.Time // on created_at: from Since, before Until
	Limit, Skip        int
}

JobFilter selects jobs to list. Zero fields match everything.

type JobResult

type JobResult struct {
	Status     string
	Output     json.RawMessage
	Code       string
	Message    string
	Details    json.RawMessage
	DurationMS int64
	// HTTPStatus is the function's own chosen status (ctx.error's first
	// argument) when Status is "function_error"; unused otherwise. A
	// job never answers HTTP itself, but an idempotent sync replay
	// (roadmap F12) needs it to reconstruct the original response.
	HTTPStatus int
}

JobResult is how a job's run ended: the same vocabulary as a sync call's executor.Result (executor.Status*), flattened here so this package doesn't need to import the executor.

type KeyOptions

type KeyOptions struct {
	TTL      time.Duration     // 0: never expires
	Role     KeyRole           // "" means data
	Networks registry.Networks // where the key may be used from; empty: anywhere
}

KeyOptions are the settings of a new API key.

type KeyRole

type KeyRole string

KeyRole is what an API key may do.

const (
	// KeyRoleData keys reach data routes, bypassing rules, and may act on
	// behalf of a user. The default: what services need.
	KeyRoleData KeyRole = "data"
	// KeyRoleAdmin keys also reach the admin API (/_admin): users, roles,
	// invitations and API keys. For management tooling only.
	KeyRoleAdmin KeyRole = "admin"
)

func ParseKeyRole

func ParseKeyRole(s string) (KeyRole, error)

ParseKeyRole returns the role named s ("" means data).

type LogLine

type LogLine struct {
	Level string
	Line  string
}

LogLine is one line of a function's captured console output, already masked by the executor.

type PolicyError

type PolicyError struct{ Reason string }

PolicyError is a password that doesn't meet the realm's policy.

func (*PolicyError) Error

func (e *PolicyError) Error() string

type Principal

type Principal struct {
	User    User
	Session Session
}

Principal is the authenticated caller of a request.

type RoleReport

type RoleReport struct {
	// DBOnly maps emails to roles assigned only in the database, which a
	// rebuild from realm.yaml wouldn't restore.
	DBOnly map[string][]string
	// Undeclared maps emails to roles realm.yaml no longer declares.
	Undeclared map[string][]string
	// NetworksDBOnly lists users with network restrictions that realm.yaml
	// doesn't set, which a rebuild from realm.yaml wouldn't restore.
	NetworksDBOnly []string
	// Admins counts the people who can use the admin API with a session:
	// emails seeded into an admin role in realm.yaml, and users holding
	// one in the database, each counted once.
	Admins int
}

RoleReport lists role assignments that realm.yaml doesn't account for.

type Secret

type Secret struct {
	Database   string // "": realm scope
	Name       string
	Ciphertext string // base64
	Nonce      string // base64
	KeyID      string // fingerprint of the key it was encrypted with
	CreatedAt  time.Time
	UpdatedAt  time.Time
	UpdatedBy  string
}

Secret is one encrypted value, bound to a realm (implicitly, by which Users it's stored through), a scope and a name. Database empty means the realm scope; otherwise it's the database scope.

type SecretCache

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

SecretCache holds decrypted secret values (and confirmed-missing lookups) for secretCacheTTL, shared across every realm's Users: NewSecretCache once, assigned to each Users.Cache. Each key includes the realm, so it's safe for every realm to share one instance.

func NewSecretCache

func NewSecretCache() *SecretCache

NewSecretCache returns an empty cache.

type SecretCipher

type SecretCipher struct {
	KeyID string
	// contains filtered or unexported fields
}

SecretCipher encrypts and decrypts secret values with AES-256-GCM, under a key derived from the operator's master key (never the master key's raw bytes directly, so an accidental log of the derived key alone can't be turned back into the configured secret). KeyID is a fingerprint safe to store and log: it identifies which master key a value was encrypted with, for rotation, without revealing it.

func NewSecretCipher

func NewSecretCipher(raw []byte) (*SecretCipher, error)

NewSecretCipher derives a cipher from raw master key material (any length, at least 32 characters is enforced by settings). The same raw material always derives the same cipher and KeyID.

func (*SecretCipher) Open

func (c *SecretCipher) Open(ciphertext, nonce, keyID string) (string, error)

Open decrypts a value sealed with a cipher whose KeyID matches keyID.

func (*SecretCipher) Seal

func (c *SecretCipher) Seal(plaintext string) (ciphertext, nonce string, err error)

Seal encrypts plaintext, returning base64 ciphertext and nonce.

type SecretMeta

type SecretMeta struct {
	Database  string
	Name      string
	CreatedAt time.Time
	UpdatedAt time.Time
	UpdatedBy string
}

SecretMeta is a secret without its value, as listed: names, scope and who last changed it, never the value.

type Session

type Session struct {
	ID         string // public id, used to list and revoke sessions
	UserID     string
	TokenHash  string
	CreatedAt  time.Time
	LastUsedAt time.Time
	ExpiresAt  time.Time
}

Session is a signed-in session. Only a hash of its token is stored.

type Store

type Store interface {
	// CreateUser inserts a user; ErrEmailTaken if the email exists.
	CreateUser(ctx context.Context, u User) error
	UserByEmail(ctx context.Context, email string) (User, error)
	// UserByID returns the user with that id; ErrNotFound if none.
	UserByID(ctx context.Context, id string) (User, error)
	ListUsers(ctx context.Context) ([]User, error)
	// AddRoles adds roles the user doesn't have yet, setting UpdatedAt.
	AddRoles(ctx context.Context, userID string, roles []string, now time.Time) error
	// RemoveRole removes a role from the user, setting UpdatedAt.
	RemoveRole(ctx context.Context, userID, role string, now time.Time) error
	// UpdateUser applies upd and sets UpdatedAt to now.
	UpdateUser(ctx context.Context, id string, upd UserUpdate, now time.Time) error
	// DeleteUser removes the user with their identities and sessions.
	DeleteUser(ctx context.Context, id string) error
	// PutIdentity creates the identity, or, when one with the same provider
	// and subject exists, updates its credentials and UpdatedAt (keeping its
	// ID and CreatedAt).
	PutIdentity(ctx context.Context, id Identity) error
	Identity(ctx context.Context, provider, subject string) (Identity, error)
	// DeleteSessions revokes every session of the user.
	DeleteSessions(ctx context.Context, userID string) error

	CreateSession(ctx context.Context, s Session) error
	// SessionByTokenHash returns the session and its user; ErrNotFound if
	// either doesn't exist.
	SessionByTokenHash(ctx context.Context, hash string) (Session, User, error)
	// TouchSession records a use of the session and its new expiry.
	TouchSession(ctx context.Context, id string, lastUsed, expires time.Time) error
	// ListSessions returns the user's sessions, newest first.
	ListSessions(ctx context.Context, userID string) ([]Session, error)
	// DeleteSession revokes one session of the user; ErrNotFound if the
	// user has no session with that id.
	DeleteSession(ctx context.Context, userID, id string) error
	// DeleteOtherSessions revokes every session of the user except keepID.
	DeleteOtherSessions(ctx context.Context, userID, keepID string) error

	// CreateAPIKey stores a key; ErrKeyNameTaken if the name exists.
	CreateAPIKey(ctx context.Context, k APIKey) error
	// APIKeyByHash returns the key with that hash; ErrKeyNotFound if none.
	APIKeyByHash(ctx context.Context, hash string) (APIKey, error)
	ListAPIKeys(ctx context.Context) ([]APIKey, error)
	// DeleteAPIKey removes the named key; ErrKeyNotFound if none.
	DeleteAPIKey(ctx context.Context, name string) error
	// TouchAPIKey records a use of the key.
	TouchAPIKey(ctx context.Context, hash string, at time.Time) error

	// AppendAudit adds a record to the audit trail, which is never
	// modified: records are only removed when they expire.
	AppendAudit(ctx context.Context, rec AuditRecord) error
	// ListAudit returns records matching f, newest first, and whether
	// more follow.
	ListAudit(ctx context.Context, f AuditFilter) ([]AuditRecord, bool, error)

	CreateInvitation(ctx context.Context, inv Invitation) error
	// ClaimInvitation atomically deletes and returns the unexpired
	// invitation with that token hash; ErrNotFound if none.
	ClaimInvitation(ctx context.Context, hash string, now time.Time) (Invitation, error)
	// ListInvitations returns all invitations, newest first.
	ListInvitations(ctx context.Context) ([]Invitation, error)
	// DeleteInvitation removes an invitation by id; ErrNotFound if none.
	DeleteInvitation(ctx context.Context, id string) error

	// LoginAttempts returns the failure counter of key (zero if none).
	LoginAttempts(ctx context.Context, key string) (Attempts, error)
	// RecordLoginFailure increments key's counter atomically, setting its
	// last failure to at; the counter is deleted at expires.
	RecordLoginFailure(ctx context.Context, key string, at, expires time.Time) error
	// ClearLoginAttempts deletes key's counter.
	ClearLoginAttempts(ctx context.Context, key string) error

	// IncrementCounter atomically increments key's counter (creating it,
	// or restarting it at 1 if its window has already ended) and returns
	// the new count and when it resets. The same generic "N events per
	// window" primitive login throttling uses, reused for function rate
	// limits (roadmap F9), which is why it lives in the same collection.
	IncrementCounter(ctx context.Context, key string, at, expires time.Time) (count int, resetAt time.Time, err error)

	// RecordInvocation appends a function call record (roadmap F10).
	// backd never updates or deletes them; MongoDB removes them when
	// they expire.
	RecordInvocation(ctx context.Context, r InvocationRecord) error
	// ListInvocations returns records matching f, newest first, and
	// whether more follow.
	ListInvocations(ctx context.Context, f InvocationFilter) ([]InvocationRecord, bool, error)

	// EnqueueJob stores a new async job (roadmap F11), queued for a worker.
	EnqueueJob(ctx context.Context, j Job) error
	// ClaimJob atomically claims the oldest job that's never been claimed,
	// or whose lease has expired, leasing it to workerID until at plus
	// the job's own timeout plus margin. found is false when there is
	// none to claim.
	ClaimJob(ctx context.Context, workerID string, at time.Time, margin time.Duration) (j Job, found bool, err error)
	// CompleteJob records a job's result; expiresAt starts its retention
	// countdown (MongoDB removes it once past).
	CompleteJob(ctx context.Context, id string, result JobResult, completedAt, expiresAt time.Time) error
	// ListJobs returns the jobs matching f, newest first, and whether
	// more follow.
	ListJobs(ctx context.Context, f JobFilter) ([]Job, bool, error)
	// GetJob returns one job by id; found is false if there is none.
	GetJob(ctx context.Context, id string) (j Job, found bool, err error)

	// ClaimIdempotency (roadmap F12) atomically inserts rec if its id
	// isn't already used, or returns the existing record (running or
	// done) if it is. claimed is false in the second case.
	ClaimIdempotency(ctx context.Context, rec IdempotencyRecord) (existing IdempotencyRecord, claimed bool, err error)
	// CompleteIdempotency stores a claimed key's outcome: result for a
	// sync call, jobID for async (mutually exclusive). expiresAt starts
	// its retention countdown.
	CompleteIdempotency(ctx context.Context, id string, result *JobResult, jobID string, completedAt, expiresAt time.Time) error
	// ReleaseIdempotency removes a claim that shouldn't be remembered
	// (an infrastructure failure, not a real outcome), so a retry can
	// go through cleanly instead of being stuck "running" forever.
	ReleaseIdempotency(ctx context.Context, id string) error

	// UpsertSecret creates or replaces the secret at (database, name),
	// keeping its original CreatedAt on an update.
	UpsertSecret(ctx context.Context, s Secret) error
	// SecretByScope returns one secret; ErrSecretNotFound if none.
	SecretByScope(ctx context.Context, database, name string) (Secret, error)
	// ListSecrets returns every secret's metadata, sorted by database
	// (realm scope, "", first) then name.
	ListSecrets(ctx context.Context) ([]Secret, error)
	// DeleteSecret removes one; ErrSecretNotFound if none.
	DeleteSecret(ctx context.Context, database, name string) error
}

Store persists users, identities and sessions of one realm.

type ThrottledError

type ThrottledError struct{ RetryAfter time.Duration }

ThrottledError means the caller must wait before trying again.

func (*ThrottledError) Error

func (e *ThrottledError) Error() string

type User

type User struct {
	ID            string
	Email         string // normalized: trimmed, lowercased
	EmailVerified bool
	Roles         []string
	Disabled      bool
	// AdminNetworks restrict the user's admin API requests; LoginNetworks
	// their login and every request with their session. Empty: no
	// restriction beyond the realm's.
	AdminNetworks registry.Networks
	LoginNetworks registry.Networks
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

User is a realm user. It holds only identity data; profiles belong in application collections.

type UserUpdate

type UserUpdate struct {
	EmailVerified *bool
	Disabled      *bool
	AdminNetworks *registry.Networks // set (empty clears)
	LoginNetworks *registry.Networks // set (empty clears)
}

UserUpdate changes the set fields of a user.

type Users

type Users struct {
	Store    Store
	Hasher   *Hasher
	Settings registry.RealmSettings
	Now      func() time.Time // defaults to time.Now
	Realm    string           // the realm's name, for logs
	Log      *slog.Logger     // audit records are also logged here; nil: not logged

	// Cipher encrypts and decrypts secrets (roadmap F5); nil when
	// BACKD_SECRETS_KEY isn't configured, in which case every secret
	// resolves as missing. Cache holds decrypted values briefly, shared
	// across every realm's Users (NewSecretCache); nil disables caching.
	Cipher *SecretCipher
	Cache  *SecretCache
}

Users manages the users of one realm.

func (*Users) AddRole

func (s *Users) AddRole(ctx context.Context, email, role string) error

AddRole assigns a declared role to a user.

func (*Users) ApplyRoleSeeds

func (s *Users) ApplyRoleSeeds(ctx context.Context) (int, error)

ApplyRoleSeeds adds the roles realm.yaml assigns to existing users. It never removes roles. Users who don't exist yet get theirs when created. It returns how many users were updated.

func (*Users) Audit

func (s *Users) Audit(ctx context.Context, action, target string, details map[string]any)

Audit appends a record to the realm's audit trail and writes it to the log. A record that can't be stored is logged as an error; the action it describes has already happened, so it isn't undone.

func (*Users) AuditAs

func (s *Users) AuditAs(ctx context.Context, actor, action, target string, details map[string]any)

AuditAs is Audit with an explicit actor (when not empty), for events whose actor isn't the caller yet, such as a login.

func (*Users) AuditTrail

func (s *Users) AuditTrail(ctx context.Context, f AuditFilter) ([]AuditRecord, bool, error)

AuditTrail returns records matching f, newest first, and whether more follow.

func (*Users) Authenticate

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

Authenticate resolves a session token to its user. It extends the session's idle timeout, writing at most once per minute.

func (*Users) AuthenticateKey

func (s *Users) AuthenticateKey(ctx context.Context, key string) (APIKey, error)

AuthenticateKey resolves an API key. It records the use at most once a minute.

func (*Users) CallbackCaller

func (s *Users) CallbackCaller(ctx context.Context, c CallbackClaims) (Caller, error)

CallbackCaller resolves a verified token into the caller it acts as, checking the user and key still exist and may act: a user disabled or a key revoked during the invocation loses access at once.

func (*Users) ChangePassword

func (s *Users) ChangePassword(ctx context.Context, p Principal, current, next string) error

ChangePassword replaces the caller's password after checking the current one, and ends all of their other sessions.

func (*Users) ClaimIdempotency

func (s *Users) ClaimIdempotency(ctx context.Context, rec IdempotencyRecord) (IdempotencyRecord, bool, error)

ClaimIdempotency atomically claims a key for a new call, or returns the existing record (running or done) if one already exists.

func (*Users) ClaimJob

func (s *Users) ClaimJob(ctx context.Context, workerID string) (Job, bool, error)

ClaimJob atomically claims the oldest claimable job: never claimed, or whose lease has expired (a dead worker's jobs are picked up again), leasing it to workerID for the function's own timeout plus a margin.

func (*Users) CompleteIdempotency

func (s *Users) CompleteIdempotency(ctx context.Context, id string, result *JobResult, jobID string) error

CompleteIdempotency stores a claimed key's outcome.

func (*Users) CompleteJob

func (s *Users) CompleteJob(ctx context.Context, id string, result JobResult) error

CompleteJob records a job's result and starts its retention countdown.

func (*Users) Create

func (s *Users) Create(ctx context.Context, email string, password *string) (User, error)

Create adds a user, as an administrator. With password nil the user has no password identity and can't sign in with a password until one is set.

func (*Users) CreateAPIKey

func (s *Users) CreateAPIKey(ctx context.Context, name string, opts KeyOptions) (APIKey, string, error)

CreateAPIKey creates a key named name with opts. The key itself is returned only here.

func (*Users) CreateInvitation

func (s *Users) CreateInvitation(ctx context.Context, email string, ttl time.Duration, createdBy string) (Invitation, string, error)

CreateInvitation creates an invitation valid for ttl (0: the default), optionally bound to email. The token is returned only here.

func (*Users) Delete

func (s *Users) Delete(ctx context.Context, email string) error

Delete removes the user, their identities and sessions. Documents they own are kept.

func (*Users) DeleteAccount

func (s *Users) DeleteAccount(ctx context.Context, p Principal, password string) error

DeleteAccount deletes the caller after checking their password.

func (*Users) DeleteSecret

func (s *Users) DeleteSecret(ctx context.Context, database, name string) error

DeleteSecret removes the value at scope and name; ErrSecretNotFound if none. Functions that declare it start answering secret_missing again.

func (*Users) EnqueueJob

func (s *Users) EnqueueJob(ctx context.Context, j Job) (Job, error)

EnqueueJob stores a new job, queued for a worker to claim, and returns it with its id and timestamps filled in.

func (*Users) EnqueueScheduledJob

func (s *Users) EnqueueScheduledJob(ctx context.Context, j Job, scheduledAt time.Time) (bool, error)

EnqueueScheduledJob enqueues the run of a scheduled function for scheduledAt, under an id derived from the function and that time, so however many workers try, exactly one job is created (roadmap F18). It returns false when the run already exists.

func (*Users) Find

func (s *Users) Find(ctx context.Context, email string) (User, error)

Find returns the user with that email, or ErrNotFound.

func (*Users) GetJob

func (s *Users) GetJob(ctx context.Context, id string) (Job, bool, error)

GetJob returns a job by id, for its caller to poll its status.

func (*Users) Identify

func (s *Users) Identify(ctx context.Context, credential string) (Caller, error)

Identify resolves a bearer credential (a session token or an API key) to its caller. An empty credential is the anonymous caller.

func (*Users) Invitations

func (s *Users) Invitations(ctx context.Context) ([]Invitation, error)

Invitations lists the realm's unexpired invitations, newest first.

func (*Users) Invocations

func (s *Users) Invocations(ctx context.Context, f InvocationFilter) ([]InvocationRecord, bool, error)

Invocations returns invocation records matching f, newest first, and whether more follow.

func (*Users) IsSeeded

func (s *Users) IsSeeded(email, role string) bool

IsSeeded reports whether realm.yaml assigns role to email.

func (*Users) Jobs

func (s *Users) Jobs(ctx context.Context, f JobFilter) ([]Job, bool, error)

Jobs returns the jobs matching f, newest first, and whether more follow.

func (*Users) List

func (s *Users) List(ctx context.Context) ([]User, error)

List returns every user of the realm.

func (*Users) ListAPIKeys

func (s *Users) ListAPIKeys(ctx context.Context) ([]APIKey, error)

ListAPIKeys returns the realm's API keys, sorted by name.

func (*Users) ListSecrets

func (s *Users) ListSecrets(ctx context.Context) ([]SecretMeta, error)

ListSecrets returns every secret's metadata (never a value), sorted by database then name (realm-scope secrets, database "", first).

func (*Users) Login

func (s *Users) Login(ctx context.Context, email, password, ip string) (Principal, string, error)

Login checks an email and password and starts a session. Every failure returns ErrInvalidCredentials after the same amount of hashing work, so neither the answer nor its timing reveals whether the email exists. Repeated failures for the email or from the client ip (may be empty) are throttled with a *ThrottledError.

func (*Users) Logout

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

Logout ends the caller's session.

func (*Users) LogoutAll

func (s *Users) LogoutAll(ctx context.Context, p Principal) error

LogoutAll ends every session of the caller, including the current one.

func (*Users) NetworksInConfig

func (s *Users) NetworksInConfig(email string) bool

NetworksInConfig reports whether realm.yaml sets network restrictions for email; seeding would then overwrite changes made elsewhere.

func (*Users) OnBehalfOf

func (s *Users) OnBehalfOf(ctx context.Context, c Caller, userID string) (Caller, error)

OnBehalfOf makes an API key caller act as the user with id: that user's rules and ownership apply. It returns ErrNotFound for unknown users.

func (*Users) RateLimit

func (s *Users) RateLimit(ctx context.Context, key string, limit int, window time.Duration) error

RateLimit increments key's counter and returns *ThrottledError if the resulting count is over limit within window: shared across every backd instance (roadmap F9), unlike concurrency limits (F8), because the counter lives in Store, not in process memory. Reuses the same "N events per window" primitive as login throttling (Store's IncrementCounter), under its own key namespace so the two never collide.

func (*Users) RecordInvocation

func (s *Users) RecordInvocation(ctx context.Context, rec InvocationRecord)

RecordInvocation stores one function call. A record that can't be stored is logged as an error; the call already happened and isn't undone by a failed write, the same philosophy as Audit.

func (*Users) ReleaseIdempotency

func (s *Users) ReleaseIdempotency(ctx context.Context, id string) error

ReleaseIdempotency removes a claim that shouldn't be remembered (the executor was unreachable or busy — nothing about the call's own outcome to replay), so a retry can go through cleanly.

func (*Users) RemoveRole

func (s *Users) RemoveRole(ctx context.Context, email, role string) error

RemoveRole takes a role away from a user. An assignment seeded in realm.yaml comes back at the next seeding.

func (*Users) ReportRoles

func (s *Users) ReportRoles(ctx context.Context) (RoleReport, error)

ReportRoles compares the stored assignments with realm.yaml.

func (*Users) ResolveSecrets

func (s *Users) ResolveSecrets(ctx context.Context, refs []registry.SecretRef, database string) (values map[string]string, missing []string, err error)

ResolveSecrets decrypts the values a function declared (refs), for database (its own). It returns values keyed exactly as declared (SecretRef.String(): NAME or realm.NAME) and, separately, the refs with no stored value, so the caller can answer secret_missing. Decrypted values are cached for a short time, so a rotation or a changed value applies within a minute without restarting anything.

func (*Users) RevokeAPIKey

func (s *Users) RevokeAPIKey(ctx context.Context, name string) error

RevokeAPIKey deletes a key; it stops working at once.

func (*Users) RevokeInvitation

func (s *Users) RevokeInvitation(ctx context.Context, id string) error

RevokeInvitation deletes an invitation; ErrNotFound if none has that id.

func (*Users) RevokeSession

func (s *Users) RevokeSession(ctx context.Context, p Principal, id string) error

RevokeSession ends one of the caller's sessions; ErrNotFound if the caller has no session with that id.

func (*Users) Sessions

func (s *Users) Sessions(ctx context.Context, p Principal) ([]Session, error)

Sessions lists the caller's unexpired sessions, newest first.

func (*Users) SetDisabled

func (s *Users) SetDisabled(ctx context.Context, email string, disabled bool) error

SetDisabled disables or re-enables the user. Disabling revokes all of their sessions.

func (*Users) SetEmailVerified

func (s *Users) SetEmailVerified(ctx context.Context, email string, verified bool) error

SetEmailVerified marks the user's email as verified or not.

func (*Users) SetNetworks

func (s *Users) SetNetworks(ctx context.Context, email string, admin, login registry.Networks) (User, error)

SetNetworks replaces the user's network restrictions: admin limits their admin API requests (within the realm's allowed networks), login their login and session use. Empty lists remove the restriction. Settings realm.yaml doesn't hold live only in the database.

func (*Users) SetPassword

func (s *Users) SetPassword(ctx context.Context, email, password string) error

SetPassword sets or replaces the user's password and revokes all of their sessions.

func (*Users) SetSecret

func (s *Users) SetSecret(ctx context.Context, database, name, value, by string) error

SetSecret creates or replaces the value at scope (database, or "" for the realm) and name, encrypting it with Cipher. by is the actor for UpdatedBy (see Caller.Actor).

func (*Users) Signup

func (s *Users) Signup(ctx context.Context, email, password, invitation string) (Principal, string, error)

Signup creates a user with a password and signs them in. Realms with `signup: open` accept anyone; `signup: invite` needs a valid invitation token (used up by a successful sign-up); `signup: closed` refuses.

func (*Users) UserByID

func (s *Users) UserByID(ctx context.Context, id string) (User, error)

UserByID returns the user with that id, or ErrNotFound.

Directories

Path Synopsis
Package authtest provides an in-memory auth.Store for tests.
Package authtest provides an in-memory auth.Store for tests.

Jump to

Keyboard shortcuts

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