auth

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT, MIT Imports: 18 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 is accounts, sessions and personal API tokens, on top of the Store.

── THE MODEL, AND WHY COOKIES ───────────────────────────────────────────────────────────────────

Three principals can authenticate a request:

  1. `PSTACK_TOKEN` — the root/machine credential. It PREDATES accounts, `init` generates it, and CI pipelines hold it; retiring it would be a forced migration for every caller. It stays.
  2. A personal API token (`pstack_pat_…`) — per user, for scripts that should not hold root.
  3. A session — httpOnly cookie set by username+password login, OR by a completed SSO round trip (sso): an SSO login mints exactly the same row, so nothing downstream of the cookie — the gate, the terminal, personal tokens — knows the difference. Cookies are the deliberate choice, not an implementation detail: `EventSource` (the job log stream) and `WebSocket` (the terminal) cannot send an `Authorization` header from a browser, but the browser attaches cookies to both automatically on the same origin. Session auth is what makes those surfaces authenticable at all.

── STORAGE DISCIPLINE ───────────────────────────────────────────────────────────────────────────

Passwords: argon2id (phc.go). Sessions and tokens: the database stores the SHA-256 of the secret, never the secret. A database file read (or a backup lying around) must not be a session hijack or a token theft. Verification is hash-then-lookup, which also makes it constant-time-ish by construction — the lookup key is a digest, not the caller's input.

── BOOTSTRAP ────────────────────────────────────────────────────────────────────────────────────

The first admin comes from `PSTACK_ADMIN_USER`/`PSTACK_ADMIN_PASSWORD` at boot, or from `POST /api/auth/bootstrap` authenticated by `PSTACK_TOKEN`. Both are ONLY honoured while the users table is empty — after that they are inert, so a leaked compose file with the env pair in it cannot mint extra admins later.

── THE PORT ─────────────────────────────────────────────────────────────────────────────────────

bun:sqlite was synchronous, so a run of statements could not interleave with another request's. Here the multi-statement paths (SetPassword, SsoSignIn) run inside Store.Tx, and every helper takes a store.Querier so it works on the *sql.DB and on the *sql.Tx alike. Errors: *Error is the TypeScript's AuthError (the API answers 400 with its text), *sso.Error the SsoError; anything else is the database and is a 500.

Index

Constants

View Source
const SessionTTLMs = 30 * 24 * 60 * 60 * 1000

SessionTTLMs is thirty days. Fixed, not sliding — a stolen cookie should not be renewable forever.

Variables

This section is empty.

Functions

func HashPassword

func HashPassword(password string) string

HashPassword is `Bun.password.hash(password, 'argon2id')`.

func IsError

func IsError(err error) bool

IsError reports whether err is an *Error.

func VerifyPassword

func VerifyPassword(password, encoded string) bool

VerifyPassword is `Bun.password.verify(password, encoded)`: the parameters come from the string, the compare is constant-time, and anything unparsable is simply false.

Types

type Auth

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

Auth is the account layer over one Store.

func New

func New(s *store.Store) *Auth

New returns the Auth over s.

func (*Auth) Bootstrap

func (a *Auth) Bootstrap(username, password string) (*UserRow, error)

Bootstrap is the first-admin bootstrap. Only while the table is empty — see the package comment. Returns nil, nil when it declined, so the caller can distinguish "created" from "already bootstrapped" without a race.

func (*Auth) CreateToken

func (a *Auth) CreateToken(userID int64, name string) (token string, id int64, err error)

CreateToken mints a token for a user. The plaintext is returned ONCE and never retrievable again.

func (*Auth) CreateUser

func (a *Auth) CreateUser(username, password string, opts CreateOpts) (*UserRow, error)

CreateUser validates, hashes and inserts.

func (*Auth) DeleteSsoProvider added in v0.31.0

func (a *Auth) DeleteSsoProvider(key string) (bool, error)

DeleteSsoProvider forgets one provider. The links stay: those accounts keep their password and their tokens, and a re-added provider on the same upstream directory resolves to the same people.

func (*Auth) DeleteToken

func (a *Auth) DeleteToken(userID, id int64) (bool, error)

DeleteToken is scoped to the owner: one user must not be able to revoke another's token by guessing ids.

func (*Auth) DeleteUser

func (a *Auth) DeleteUser(id int64) (bool, error)

DeleteUser refuses to delete the last user: an instance with accounts and no way to log in is only recoverable by editing the database over SSH, and nothing in the UI can explain that state.

func (*Auth) ExportTokens added in v0.30.0

func (a *Auth) ExportTokens() ([]ExportToken, error)

ExportTokens is every personal token WITH its hash, oldest first.

func (*Auth) ExportUsers added in v0.30.0

func (a *Auth) ExportUsers() ([]ExportUser, error)

ExportUsers is every account WITH its password hash, by username.

func (*Auth) ListSsoProviders added in v0.31.0

func (a *Auth) ListSsoProviders() ([]SsoProviderRow, error)

ListSsoProviders is every stored provider, in key order (SQLite BINARY collation). A row that no longer validates is skipped, the way the single-provider read treated it — never a half-shape.

func (*Auth) ListTokens

func (a *Auth) ListTokens(userID int64) ([]TokenRow, error)

ListTokens is a user's tokens, newest first.

func (*Auth) ListUsers

func (a *Auth) ListUsers() ([]UserRow, error)

ListUsers is every account, by username (SQLite BINARY collation).

func (*Auth) Login

func (a *Auth) Login(username, password string) (session string, user *UserRow, err error)

Login verifies credentials and mints a session. The returned value is the COOKIE value; only its hash is stored.

func (*Auth) Logout

func (a *Auth) Logout(session string) error

Logout deletes the session row.

func (*Auth) PruneSessions

func (a *Auth) PruneSessions() error

PruneSessions is housekeeping — expired rows are already unusable; this just stops them accumulating.

func (*Auth) SessionUser

func (a *Auth) SessionUser(session string) (*UserRow, error)

SessionUser resolves a cookie value to its account, or nil.

func (*Auth) SetPassword

func (a *Auth) SetPassword(id int64, password string) (bool, error)

SetPassword changes a password.

Every session and token for that user is revoked in the same transaction. A password change is usually a response to "someone may have this" — leaving the sessions it was protecting alive would make the change theatre. The caller's own session dies with the rest; the UI signs them back in rather than pretending nothing happened.

func (*Auth) SetSsoProvider added in v0.31.0

func (a *Auth) SetSsoProvider(key string, cfg *sso.Config, clientSecret string) error

SetSsoProvider saves one provider under its slug. An EMPTY clientSecret keeps the one stored for THAT key — the read endpoint returns a mask, so a form that round-trips the mask must not overwrite the real secret with it. There is no stored secret to keep on a key's first save, so an empty one is refused there.

func (a *Auth) SsoLinks(userID int64) ([]SsoLink, error)

SsoLinks lists a user's provider links.

func (*Auth) SsoProvider added in v0.31.0

func (a *Auth) SsoProvider(key string) (*SsoProviderRow, error)

SsoProvider reads one provider, or nil when there is none or the row does not validate.

func (*Auth) SsoSignIn

func (a *Auth) SsoSignIn(providerKey string, identity *sso.Identity, opts SsoSignInOpts) (*SignIn, error)

SsoSignIn turns a verified provider identity into a session.

THE ORDER IS THE SECURITY. `(providerKey, subject)` first, because it is the only stable identity; email second and ONLY to adopt a pre-existing local account, gated on the provider having said the address is verified; a new account last. An unverified email must never reach an existing account — that is the one path in this feature that could hand over someone else's privileges, and it is why `EmailVerified == nil` (the provider never said) is not good enough.

The whole thing is one transaction: the TypeScript's single thread made its lookup-then-insert atomic for free, and two callbacks for one new subject must not both provision.

func (*Auth) TokenUser

func (a *Auth) TokenUser(token string) (*UserRow, error)

TokenUser resolves a personal token to its account, or nil, touching last_used_at on the way.

func (*Auth) Transient

func (a *Auth) Transient() sso.TransientStore

Transient is where the PKCE verifier waits out the round trip. SQLite, because that is what this service already wires up; the interface is what makes Redis or Postgres a config change later.

func (*Auth) UserCount

func (a *Auth) UserCount() (int64, error)

UserCount is how many accounts exist.

type CreateOpts

type CreateOpts struct {
	Role  string
	Email string
}

CreateOpts are the optional fields of a new account. An empty Role is 'admin'; an empty Email is stored as NULL.

type Error

type Error struct{ Msg string }

Error is the TypeScript's AuthError: the caller's fault, and its text is shown to them.

func (*Error) Error

func (e *Error) Error() string

type ExportToken added in v0.30.0

type ExportToken struct {
	Username string `json:"username"`
	Name     string `json:"name"`
	// TokenHash is the SHA-256 of the token, verbatim, so scripts holding the token keep working.
	TokenHash string `json:"tokenHash"`
	CreatedAt int64  `json:"createdAt"`
}

ExportToken is one personal token as the portable document carries it. Keyed to its owner by USERNAME, not by id: row ids are per-host and mean nothing on the other side.

type ExportUser added in v0.30.0

type ExportUser struct {
	Username string `json:"username"`
	// PasswordHash is the argon2id PHC string, verbatim, so a login keeps working on the new host.
	PasswordHash string  `json:"passwordHash"`
	Role         string  `json:"role"`
	Email        *string `json:"email"`
	CreatedAt    int64   `json:"createdAt"`
}

ExportUser is one account as the portable document carries it. The JSON tags are that document's field names.

type How

type How string

How says which of the three SsoSignIn outcomes happened, so the adoption case can be logged.

const (
	Linked  How = "linked"
	Adopted How = "adopted"
	Created How = "created"
)

The outcomes.

type Kind

type Kind string

Kind is a principal's kind.

const (
	KindRoot  Kind = "root"
	KindUser  Kind = "user"
	KindShare Kind = "share"
)

The kinds.

type Principal

type Principal struct {
	Kind Kind
	// User is set for KindUser.
	User *UserRow
	// Deployment and Views are set for KindShare.
	Deployment string
	Views      []share.View
}

Principal is who a request is. Root is PSTACK_TOKEN; a user carries its row; a share is a signed read-only link to ONE deployment (share) — it can see what its Views allow on that deployment and nothing else, which the API enforces right after the gate, before any route.

type SignIn

type SignIn struct {
	Session string
	User    *UserRow
	How     How
}

SignIn is a minted session.

type SsoLink struct {
	ProviderKey string `json:"providerKey"`
	Subject     string `json:"subject"`
	CreatedAt   int64  `json:"createdAt"`
	LastLoginAt *int64 `json:"lastLoginAt"`
}

SsoLink is one (provider, subject) → user row.

type SsoProviderRow added in v0.31.0

type SsoProviderRow struct {
	Key          string
	Config       *sso.Config
	ClientSecret string
	UpdatedAt    int64
}

SsoProviderRow is one stored provider: its slug, the config and the secret it is paired with.

type SsoSignInOpts

type SsoSignInOpts struct {
	DefaultRole         string
	AllowedEmailDomains []string
	AllowedUsernames    []string
	RequiredGroups      []string
	// GroupsErr is why the provider's group list did not arrive, or nil. The caller does the fetch
	// (it holds the access token), and this is how the failure reaches the gate INSTEAD of being
	// swallowed: a rate limit, a revoked scope and a network blip are not "you are not a member",
	// and collapsing them into one refusal sends the operator to fix the wrong thing.
	GroupsErr error
}

SsoSignInOpts are the provider's provisioning rules: the whole allow-rule set travels here, as one argument, so that adding a rule is a field rather than a third positional parameter and every one of them is enforced in the single gate at the top of SsoSignIn.

type TokenRow

type TokenRow struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	CreatedAt  int64  `json:"createdAt"`
	LastUsedAt *int64 `json:"lastUsedAt"`
}

TokenRow is a personal token as the list shows it: never the secret.

type UserRow

type UserRow struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
	Role     string `json:"role"`
	// Email is from an SSO provider's claims; null for every locally-created account.
	Email     *string `json:"email"`
	CreatedAt int64   `json:"createdAt"`
}

UserRow is an account as every response carries it.

Jump to

Keyboard shortcuts

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