auth

package
v0.46.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT, MIT Imports: 19 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.

A user additionally holds one of four ordered ROLES — viewer < developer < maintainer < admin. The type and its ranking live below (see "roles"); WHAT each rank may reach is one table in internal/api/permissions.go, never a check scattered through the handlers.

── 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 RolesText = "viewer, developer, maintainer, admin"

RolesText is the four as one comma list, for a validation message.

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 HashToken added in v0.34.0

func HashToken(token string) string

HashToken is how a token becomes the thing the tokens table stores. Exported so an import can accept a plaintext token and arrive at the same digest `CreateToken` would have written — the two must never drift, which is why this is one function and not two call sites of sha256.

func IsError

func IsError(err error) bool

IsError reports whether err is an *Error.

func UsableHash added in v0.46.0

func UsableHash(encoded string) bool

UsableHash is whether VerifyPassword could ever accept a password for this stored hash. Config import checks it so it never stores an account nobody can log into.

func ValidRole added in v0.32.0

func ValidRole(s string) bool

ValidRole reports whether s names one of the four.

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.

── AND IT REFUSES TO DELETE THE LAST ADMIN ─────────────────────────────────────────────────────

"Last" counts ROWS, and WHO IS ASKING IS IRRELEVANT — root included. Root cannot be counted as an admin: PSTACK_TOKEN is a machine credential that may live only in a CI secret store, or have been rotated away from every human on the team. Once a host has zero admin accounts, nothing in the API can create one (POST /api/users is admin-only), so the recovery is a hand-edited database over SSH. Root that genuinely wants this account gone promotes a replacement first.

The count and the write share one transaction: two concurrent deletes each reading "2 admins" is exactly how a host reaches zero.

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) SessionHashUser added in v0.40.0

func (a *Auth) SessionHashUser(idHash string) (*UserRow, error)

SessionHashUser resolves a stored session hash (sessions.id_hash) to its account, or nil.

Only the Grafana cookie reaches it: that cookie carries the hash under a MAC, never the session. A hash is not a credential anywhere else — principal and Logout hash whatever they are given, so an id_hash presented as pstack_session is hashed again and matches nothing. One query for both callers, so an expired or revoked pstack session is a dead Grafana one on the next request.

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) SetRole added in v0.32.0

func (a *Auth) SetRole(id int64, role Role) (bool, error)

SetRole changes an account's role, and refuses to demote the last admin for the reason DeleteUser gives. False (with no error) means there is no such account.

Sessions and tokens are deliberately NOT revoked: SessionUser and TokenUser join `users` and read the role on every request, so a demotion takes effect on the demoted caller's very next request. Revoking would only log them out, which is a worse signal, not a stronger one.

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 Email is stored as NULL.

AN EMPTY ROLE IS STILL 'admin', and that is deliberate at THIS layer: Bootstrap — the first account on a host, and the only one that can then create others — comes through here with no role, and a viewer first account is an unusable host. Callers that must not mint an admin pass the role they mean; POST /api/users defaults to viewer in the route, not here.

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"`
	// Token is a PLAINTEXT token, accepted on import and NEVER written on export — the host does not
	// have it to write, which is the whole point of storing a hash.
	//
	// It exists for the document nobody exported: a config an operator AUTHORS, declaring the
	// credentials a rebuilt host should come up holding, so a migration does not mean re-issuing
	// every token and re-pasting it into every CI secret. Without it that document has to carry a
	// hash the author computed by hand, which is friction on exactly the path that is supposed to
	// remove friction.
	//
	// It is not a new exposure class: the document already carries host-variable secrets in
	// plaintext and is sealed as a whole. It IS a stronger grant than a hash — a hash cannot be
	// replayed and this can — so `Trusts()` names it separately, and an export never emits it.
	Token     string `json:"token,omitempty"`
	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.

func (*Principal) Allows added in v0.32.0

func (p *Principal) Allows(min Role) bool

Allows reports whether this principal meets a minimum role.

  • ROOT always may. It is the machine credential and sits above every role.
  • A SHARE NEVER may, whatever the minimum. A share is not a role: it is a signed read-only link to ONE deployment, and internal/api's shareAllows has already decided what it may reach before any route runs (invariant 16). Ranking it here would be a second, weaker copy of that gate, and the two would drift.
  • A USER compares rank, and an unrankable MINIMUM is met by nobody — the same fail-closed direction as an unrankable role on the row.

type Role added in v0.32.0

type Role string

── roles ───────────────────────────────────────────────────────────────────────────────────────

FOUR ORDERED ROLES, and the order IS the model: viewer < developer < maintainer < admin, each including everything below it. `root` — the PSTACK_TOKEN bearer — sits above all four. A `share` is not a role at any rank; see Allows.

AN UNKNOWN ROLE RANKS LOWEST, NOT HIGHEST. `users.role` is a plain TEXT column with no CHECK, and this project expects an operator to repair a database over SSH — so a row hand-edited to "superuser" must LOSE access, never gain it. Rank answers 0 for anything but the four, and Allows additionally refuses a minimum that is itself unrankable, so an unknown role passes no gate.

Nobody is locked out by roles arriving: migration 1's DDL is `role TEXT NOT NULL DEFAULT 'admin'` and createUser inserts `COALESCE(?, 'admin')`, so every row written before this change is an admin — verified by reading store/migrations.go, entry 1.

const (
	Viewer     Role = "viewer"
	Developer  Role = "developer"
	Maintainer Role = "maintainer"
	Admin      Role = "admin"
)

The four.

func (Role) Rank added in v0.32.0

func (r Role) Rank() int

Rank orders the roles, weakest first. ZERO means "not one of the four", which is below every one of them — see the note above.

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