apitokens

package
v0.294.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 14 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 apitokens is muster's PERSONAL API TOKEN store (accounts PR 6): the `api_tokens` table from migration 0006, under the row-level security 0009 put on it (a user reads and writes only rows whose user_id is its own).

A personal token is `mst_` + 43 base64url characters (32 random bytes). Only its sha256 is stored; the token itself is returned ONCE, by Create, and nothing can read it back. It authenticates the machine tier (internal/api's requireHookToken family) AS ITS OWNER — that user's id and role — which is what lets a person run the CLI, or a script, against muster's machine routes — on the LAN machine port AND on the browser (edge) listener, which is internet-facing — without the shared hook secret that acts as the machine user. Tokens are minted only from a signed-in browser session.

🔴 THE MANAGEMENT METHODS (Create, List, Revoke) RUN AS THE CALLER'S OWN PRINCIPAL, AND THE DATABASE IS WHAT KEEPS THEM TO THE CALLER'S ROWS. Each also names the user in its WHERE clause, but that is a second wall, not the first: TestRowLevelSecurityKeepsTokensToTheirOwner reads the table with raw SQL as another user (and as an admin) and must see nothing.

🔴 Authenticate IS THE ONE LOOKUP THAT CANNOT RUN AS ITS OWNER, because it is how the owner is LEARNED. Its caller hands it a System context (internal/api.(*Server).apiTokenUser, a System-ledger entry) for that one call; nothing it reads is handed on except the owner's id.

⚠ NO CACHE, ON PURPOSE. Every authentication reads the row and the owner's users.disabled_at, so a revoke or a disable takes effect on the very next request. The cost is one indexed lookup per request (token_hash is UNIQUE), which is the price of "revocation is immediate".

Index

Constants

View Source
const (
	// ScopeFull acts as the owner on every route a personal token reaches.
	ScopeFull = "full"
	// ScopeSummary reaches GET /api/attention/summary and nothing else: what a
	// status bar polls (internal/api's tokenScopeRoutes).
	ScopeSummary = "summary"
	// ScopeAgentCreate reaches POST /api/agents and nothing else (migration
	// 0095): the owner creating an agent from a machine, which a full token
	// does NOT reach (internal/api's explicitScopeRoutes). It is minted
	// deliberately, at /account/tokens.
	ScopeAgentCreate = "agent-create"
	// ScopeAccountUsage reaches GET /api/cc-accounts/usage and nothing else
	// (migration 0109): the read-only view of the owner's Claude accounts'
	// utilization, for a service that should read that and reach nothing else.
	ScopeAccountUsage = "account-usage"
)

The token scopes (api_tokens.scope, migration 0068).

View Source
const LastUsedGranularity = time.Minute

LastUsedGranularity is how stale last_used_at may get before an authentication rewrites it. A token used in a tight loop would otherwise cost a row write per request; within this window the column is not touched.

View Source
const MaxNameLen = 100

MaxNameLen bounds a token's label, in characters.

View Source
const Prefix = "mst_"

Prefix starts every personal token. It is how the machine tier tells a personal token from the shared hook secret before any database read, and how a leaked token is recognisable in a log or a paste.

Variables

View Source
var (
	// ErrBadToken: the value is not a live token — malformed, unknown, or
	// revoked. ONE error for all three, so nothing about a refusal says which.
	ErrBadToken = errors.New("apitokens: invalid or revoked token")
	// ErrUserDisabled: the token is live but its owner is disabled.
	ErrUserDisabled = errors.New("apitokens: the token's user is disabled")
	// ErrSessionEnded: the browser session asking to mint was issued at or
	// before the user's session cutoff (a password reset or a disable moved
	// it), so it is no longer a session that may mint.
	ErrSessionEnded = errors.New("apitokens: the session that asked to mint has been ended")
	// ErrNoUser: a management call with no user principal on its context (or
	// with the System principal, which is nobody's).
	ErrNoUser = errors.New("apitokens: no user principal on this context")
	// ErrBadScope: the scope is not ScopeFull, ScopeSummary, ScopeAgentCreate or
	// ScopeAccountUsage.
	ErrBadScope = errors.New("apitokens: unknown token scope")
	// ErrNameTooLong: the label is longer than MaxNameLen characters.
	ErrNameTooLong = fmt.Errorf("apitokens: a token name is at most %d characters", MaxNameLen)
)

Functions

func CleanName

func CleanName(name string) (string, error)

CleanName trims a label and checks its length. Exported so a handler can refuse a bad one with a 400 before minting.

func CleanScope added in v0.123.0

func CleanScope(scope string) (string, error)

CleanScope is scope as stored: "" is ScopeFull (a mint that names none is what every mint was before 0068); anything not a known scope is ErrBadScope. Exported so a handler can refuse a bad one with a 400 before minting.

func Hash

func Hash(token string) []byte

Hash is the stored form of a token: its sha256 (api_tokens.token_hash is a 32-byte BYTEA).

func LooksLike

func LooksLike(s string) bool

LooksLike reports whether s carries the personal-token prefix. It decides which DOOR a credential is for, not whether it is valid: a value with the prefix is a personal token or nothing (see ShapeOK).

func New

func New() (string, error)

New mints a fresh token: Prefix + 43 base64url characters (256 bits).

func Object

func Object(id int64) string

Object is the audit_log `object` a token's rows carry.

func ShapeOK

func ShapeOK(token string) bool

ShapeOK reports whether token is shaped like one New mints. It is a FILTER, not authentication: it lets the machine tier refuse junk without a database read. The hash lookup is the security property.

Types

type PGStore

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

PGStore is Store over Postgres.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns the store over pool.

func (*PGStore) Authenticate

func (s *PGStore) Authenticate(ctx context.Context, token string) (Token, error)

Authenticate implements Store.

🔴 THE SHAPE CHECK COMES FIRST AND COSTS NO I/O: a value that is not Prefix + 43 base64url characters is refused before the pool is touched (TestAMalformedTokenIsRefusedWithoutADatabaseRead).

🔴 REVOKED AND DISABLED ARE READ ON EVERY CALL — nothing is cached — so both take effect on the next request.

⚠ last_used_at IS BEST-EFFORT. It is rewritten only when it is older than LastUsedGranularity, and a failure to write it does NOT refuse the token: a bookkeeping column must never turn a valid credential into a 401.

func (*PGStore) Create

func (s *PGStore) Create(ctx context.Context, name string, sessionIssuedAt int64, scope string) (string, Token, error)

Create implements Store. The token row and its audit row are one transaction: a token is never live without its "created" record.

🔴 IT TAKES THE OWNER'S CREDENTIALS LOCK, THEN RE-READS disabled_at, BEFORE INSERTING. Every revoke-them-all path (a disable, a password reset) takes the same lock (users.LockCredentialsTx), so a mint racing a disable either commits first and is revoked by it, or waits for it and is refused ErrUserDisabled — never a token inserted after the revoke ran that comes back on re-enable (TestAMintRacingADisableNeverSurvivesIt).

🔴 AND THE SESSION CUTOFF, UNDER THE SAME LOCK. A password reset revokes the tokens but leaves the user enabled, so disabled_at alone let a mint queued behind a reset insert a live token. The minting session's iat is compared with users.sessions_not_before by the session tier's own rule (at or before the cutoff's second is refused): a session the reset ended cannot mint, and the session the reset signs in can (TestAMintQueuedBehindAResetIsRefused).

func (*PGStore) List

func (s *PGStore) List(ctx context.Context) ([]Token, error)

List implements Store.

func (*PGStore) Revoke

func (s *PGStore) Revoke(ctx context.Context, id int64) (found, wasLive bool, err error)

Revoke implements Store.

type Store

type Store interface {
	// Authenticate resolves token to its record. ErrBadToken for a malformed,
	// unknown or revoked token (a malformed one WITHOUT a database read);
	// ErrUserDisabled when the owner is disabled. ctx must be able to read any
	// user's row (authz.System): the owner is what it learns.
	Authenticate(ctx context.Context, token string) (Token, error)
	// Create mints a token named name, of scope (CleanScope), for ctx's user,
	// records it in audit_log, and returns the token ONCE with its record.
	// sessionIssuedAt is the minting browser session's iat (unix seconds): a
	// session issued at or before the user's session cutoff is refused
	// ErrSessionEnded. Zero means the caller is not a GoTrue session (password
	// mode, a fixture) and there is no cutoff to compare.
	Create(ctx context.Context, name string, sessionIssuedAt int64, scope string) (string, Token, error)
	// List returns ctx's user's tokens, newest first, revoked included.
	List(ctx context.Context) ([]Token, error)
	// Revoke revokes ctx's user's token id. found is false when the user has
	// no such token (another user's id included); wasLive is false when it
	// was already revoked. A revoke that changed something is audited.
	Revoke(ctx context.Context, id int64) (found, wasLive bool, err error)
}

Store is the personal-token store.

type Token

type Token struct {
	ID         int64      `json:"id"`
	UserID     int64      `json:"userId"`
	Name       string     `json:"name"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt *time.Time `json:"lastUsedAt"`
	RevokedAt  *time.Time `json:"revokedAt"`
	// Scope is what the token may reach (migration 0068): ScopeFull, or a
	// narrower scope. It is chosen when the token is minted and never changes;
	// a token minted before 0068 is ScopeFull. Which routes a scope reaches is
	// decided at the door (internal/api.admitAPIToken), not here.
	Scope string `json:"scope"`
}

Token is one token's record. It never carries the token or its hash.

func (Token) Revoked

func (t Token) Revoked() bool

Revoked reports whether the token is revoked.

Jump to

Keyboard shortcuts

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