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:
- `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.
- A personal API token (`pstack_pat_…`) — per user, for scripts that should not hold root.
- 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
- func HashPassword(password string) string
- func IsError(err error) bool
- func VerifyPassword(password, encoded string) bool
- type Auth
- func (a *Auth) Bootstrap(username, password string) (*UserRow, error)
- func (a *Auth) ClearSsoConfig() (bool, error)
- func (a *Auth) CreateToken(userID int64, name string) (token string, id int64, err error)
- func (a *Auth) CreateUser(username, password string, opts CreateOpts) (*UserRow, error)
- func (a *Auth) DeleteToken(userID, id int64) (bool, error)
- func (a *Auth) DeleteUser(id int64) (bool, error)
- func (a *Auth) ExportTokens() ([]ExportToken, error)
- func (a *Auth) ExportUsers() ([]ExportUser, error)
- func (a *Auth) ListTokens(userID int64) ([]TokenRow, error)
- func (a *Auth) ListUsers() ([]UserRow, error)
- func (a *Auth) Login(username, password string) (session string, user *UserRow, err error)
- func (a *Auth) Logout(session string) error
- func (a *Auth) PruneSessions() error
- func (a *Auth) SessionUser(session string) (*UserRow, error)
- func (a *Auth) SetPassword(id int64, password string) (bool, error)
- func (a *Auth) SetSsoConfig(cfg *sso.Config, clientSecret string) error
- func (a *Auth) SsoConfig() (*SsoConfigRow, error)
- func (a *Auth) SsoLinks(userID int64) ([]SsoLink, error)
- func (a *Auth) SsoSignIn(providerKey string, identity *sso.Identity, opts SsoSignInOpts) (*SignIn, error)
- func (a *Auth) TokenUser(token string) (*UserRow, error)
- func (a *Auth) Transient() sso.TransientStore
- func (a *Auth) UserCount() (int64, error)
- type CreateOpts
- type Error
- type ExportToken
- type ExportUser
- type How
- type Kind
- type Principal
- type SignIn
- type SsoConfigRow
- type SsoLink
- type SsoSignInOpts
- type TokenRow
- type UserRow
Constants ¶
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 ¶
HashPassword is `Bun.password.hash(password, 'argon2id')`.
func VerifyPassword ¶
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 (*Auth) Bootstrap ¶
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) ClearSsoConfig ¶
ClearSsoConfig forgets the provider. The links stay: those accounts keep their password and their tokens.
func (*Auth) CreateToken ¶
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) DeleteToken ¶
DeleteToken is scoped to the owner: one user must not be able to revoke another's token by guessing ids.
func (*Auth) DeleteUser ¶
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) ListTokens ¶
ListTokens is a user's tokens, newest first.
func (*Auth) Login ¶
Login verifies credentials and mints a session. The returned value is the COOKIE value; only its hash is stored.
func (*Auth) PruneSessions ¶
PruneSessions is housekeeping — expired rows are already unusable; this just stops them accumulating.
func (*Auth) SessionUser ¶
SessionUser resolves a cookie value to its account, or nil.
func (*Auth) SetPassword ¶
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) SetSsoConfig ¶
SetSsoConfig saves. An EMPTY clientSecret keeps the stored one — 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 the first save, so an empty one is refused there.
func (*Auth) SsoConfig ¶
func (a *Auth) SsoConfig() (*SsoConfigRow, error)
SsoConfig reads the 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 ¶
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.
type CreateOpts ¶
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.
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.
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 SsoConfigRow ¶
SsoConfigRow is the stored provider: the config and the secret it is paired with.
type SsoLink ¶
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 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.