Documentation
¶
Overview ¶
Package gotrue is muster's client for its own GoTrue instance (accounts PR 4): the password and refresh grants, logout, the admin user calls, and — the part every request depends on — Verify, which decides whether an access token GoTrue minted is one muster will act on.
🔴 THE BROWSER NEVER TALKS TO GoTrue. GoTrue is ClusterIP-only; muster calls it server-side and keeps the tokens in HttpOnly cookies. That is why muster, not GoTrue, is the verifier of record, and why Verify is strict.
🔴 HS256 IS THE ONLY ALGORITHM, AND THE CHECK IS AN EQUALITY, NOT A LOOKUP. GoTrue signs with one shared secret; muster holds the same secret. A verifier that consults the token's own `alg` header to choose how to check it is the classic JWT hole — `alg: none` skips the check, and an asymmetric `alg` makes the shared secret a public key. Verify refuses any header whose alg is not the literal "HS256" BEFORE it computes anything (TestVerifyRejectsEveryOtherAlg).
No JWT library is used: the format muster accepts is one algorithm and a handful of claims, and a library's flexibility is exactly what Verify must not have.
Index ¶
- Constants
- Variables
- func IsClientError(err error) bool
- func RequireUserVerification(options json.RawMessage, registration bool) (json.RawMessage, error)
- func Sign(secret []byte, claims any) (string, error)
- type AMR
- type AMREntry
- type APIError
- type Audience
- type AuthFlags
- type Claims
- type Client
- func (c *Client) AdminAppMetadata(ctx context.Context, clientIP, userID string) (map[string]any, error)
- func (c *Client) AdminCreateUser(ctx context.Context, clientIP, email, password string) (string, error)
- func (c *Client) AdminDeleteAllPasskeys(ctx context.Context, clientIP, userID string) (int, error)
- func (c *Client) AdminDeletePasskey(ctx context.Context, clientIP, userID, passkeyID string) error
- func (c *Client) AdminDeleteUser(ctx context.Context, clientIP, userID string) error
- func (c *Client) AdminPasskeys(ctx context.Context, clientIP, userID string) ([]Passkey, error)
- func (c *Client) AdminRecoveryLink(ctx context.Context, clientIP, email string) (string, error)
- func (c *Client) AdminSetAppMetadata(ctx context.Context, clientIP, userID, key string, value any) error
- func (c *Client) AdminSetBanned(ctx context.Context, clientIP, userID string, banned bool) error
- func (c *Client) AdminSetPassword(ctx context.Context, clientIP, userID, password string) error
- func (c *Client) AdminSignOutEverywhere(ctx context.Context, clientIP, userID string) error
- func (c *Client) DeletePasskey(ctx context.Context, clientIP, accessToken, passkeyID string) error
- func (c *Client) Logout(ctx context.Context, clientIP, accessToken string, scope LogoutScope) error
- func (c *Client) PasskeyRegisterOptions(ctx context.Context, clientIP, accessToken string) (PasskeyOptions, error)
- func (c *Client) PasskeyRegisterVerify(ctx context.Context, clientIP, accessToken, challengeID string, ...) (Passkey, error)
- func (c *Client) PasskeySignInOptions(ctx context.Context, clientIP string) (PasskeyOptions, error)
- func (c *Client) PasskeySignInVerify(ctx context.Context, clientIP, challengeID string, credential json.RawMessage) (Session, error)
- func (c *Client) Passkeys(ctx context.Context, clientIP, accessToken string) ([]Passkey, error)
- func (c *Client) PasswordGrant(ctx context.Context, clientIP, email, password string) (Session, error)
- func (c *Client) Refresh(ctx context.Context, clientIP, refreshToken string) (Session, error)
- func (c *Client) ServiceToken() (string, error)
- func (c *Client) Settings(ctx context.Context, clientIP string) (Settings, error)
- func (c *Client) VerifyRecovery(ctx context.Context, clientIP, tokenHash string) (Session, error)
- type LogoutScope
- type Passkey
- type PasskeyOptions
- type Session
- type Settings
- type Verifier
Constants ¶
const Algorithm = "HS256"
Algorithm is the one JWS algorithm Verify accepts.
const ClientIPHeader = "X-Muster-Client-IP"
ClientIPHeader is the header GoTrue buckets its rate limits on (GOTRUE_RATE_LIMIT_HEADER in the deployment).
🔴 EVERY CALL THIS CLIENT MAKES CARRIES IT, AND A CALL WITHOUT ONE IS REFUSED HERE RATHER THAN SENT. Measured against GoTrue v2.189.0 and v2.197.0: a request with no such header is NOT rejected, it is served — and bucketed with every other headerless request, so one guesser exhausts everyone's budget, or (worse) nobody is limited at all. GoTrue cannot enforce that muster sets it; this client does (TestEveryCallCarriesTheClientIP).
const DefaultSkew = 30 * time.Second
DefaultSkew is the clock tolerance Verify applies to exp (and nbf/iat).
const MinPasswordLength = 12
MinPasswordLength is the shortest password muster will hand GoTrue to set.
🔴 ENFORCED HERE, NOT LEFT TO GoTrue. Measured against v2.189.0: POST /admin/users accepted an 11-character password with GOTRUE_PASSWORD_MIN_LENGTH=12 set. v2.197.0 refuses it (422 weak_password), but that is a property of the image and the deployment's env, either of which can change; every password muster sets goes through the admin path, so the floor stays here as well and nothing short is ever sent.
const ServiceTokenTTL = 60 * time.Second
ServiceTokenTTL is how long the service_role token an admin call carries lives. Each admin call mints a fresh one.
Variables ¶
var ( ErrMalformed = errors.New("gotrue: malformed token") ErrAlgorithm = errors.New("gotrue: token algorithm is not " + Algorithm) ErrSignature = errors.New("gotrue: token signature does not verify") ErrIssuer = errors.New("gotrue: token issuer is not the expected one") ErrAudience = errors.New("gotrue: token audience is not the expected one") ErrExpired = errors.New("gotrue: token expired") ErrNotYet = errors.New("gotrue: token not valid yet") ErrNoSubject = errors.New("gotrue: token names no subject") )
Verify's refusals. They are coarse on purpose: a caller treats every one as "no session", and only ErrExpired is acted on differently (a refresh is attempted). None of them is ever shown to the client.
var ErrBadCredential = errors.New("gotrue: the passkey credential could not be read")
ErrBadCredential: the browser's credential is not a WebAuthn credential muster can read. Nothing is forwarded.
var ErrNoClientIP = errors.New("gotrue: refusing a call with no " + ClientIPHeader + " value")
ErrNoClientIP is the refusal of a call with no client IP (see ClientIPHeader).
var ErrWeakPassword = fmt.Errorf("gotrue: password must be at least %d characters", MinPasswordLength)
ErrWeakPassword is AdminCreateUser's refusal of a password shorter than MinPasswordLength. Nothing is sent to GoTrue.
Functions ¶
func IsClientError ¶
IsClientError reports whether err is a 4xx from GoTrue: the credential or the request was refused, as opposed to GoTrue being unreachable or failing.
func RequireUserVerification ¶
func RequireUserVerification(options json.RawMessage, registration bool) (json.RawMessage, error)
RequireUserVerification rewrites GoTrue's WebAuthn options so the browser asks for user verification: options.userVerification for a sign-in, options.authenticatorSelection.userVerification for a registration. It is the browser-side half only — what enforces UV is the flag check above.
Types ¶
type AMR ¶
type AMR []AMREntry
AMR is GoTrue's `amr` claim.
MEASURED on GoTrue v2.189.0 and again on v2.197.0: a password grant mints `[{"method":"password","timestamp":<sign-in second>}]`, and a refresh grant carries the SAME entry forward unchanged while `iat` moves on — so the timestamp is when the person last proved who they are, not when this token was minted. A new sign-in is a new session with a new timestamp.
🔴 PARSING IT NEVER FAILS A TOKEN. Verify decodes the whole payload in one json.Unmarshal; an `amr` shaped differently from what was measured (RFC 8176's plain strings, a future GoTrue's extra fields, garbage) must not turn every signed-in browser into ErrMalformed — i.e. sign everyone out. Anything that is not an object with a positive integer timestamp is dropped, and an absent or unreadable claim is simply an empty AMR: "authentication time unknown", which the step-up gate treats as NOT fresh (fail closed for that gate only).
func (*AMR) UnmarshalJSON ¶
UnmarshalJSON keeps every well-formed entry and drops the rest; it never returns an error.
type AMREntry ¶
AMREntry is one authentication event of a session: the method ("password", "otp", a passkey/webauthn method, …) and the unix second it happened.
type APIError ¶
type APIError struct {
Status int
// Code is GoTrue's machine-readable code (error_code, or the OAuth `error`).
Code string
Msg string
}
APIError is a non-2xx answer from GoTrue.
type Audience ¶
type Audience []string
Audience is a JWT `aud`, which the spec allows to be a string or an array.
func (Audience) MarshalJSON ¶
MarshalJSON writes a single audience as a string, as GoTrue does.
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON accepts both shapes.
type AuthFlags ¶
type AuthFlags struct {
UserPresent, UserVerified, BackupEligible, BackedUp bool
}
AuthFlags are the authenticator-data flags muster acts on.
func CanonicalAssertion ¶
func CanonicalAssertion(raw json.RawMessage) (AuthFlags, json.RawMessage, error)
CanonicalAssertion reads a sign-in credential (PublicKeyCredential JSON) and returns its flags and the re-encoding to forward to GoTrue.
func CanonicalAttestation ¶
func CanonicalAttestation(raw json.RawMessage) (AuthFlags, json.RawMessage, error)
CanonicalAttestation reads a registration credential and returns the flags of the authenticator data inside its attestation object, and the re-encoding to forward to GoTrue.
type Claims ¶
type Claims struct {
Subject string `json:"sub,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience Audience `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Role string `json:"role,omitempty"`
Email string `json:"email,omitempty"`
// SessionID is GoTrue's session the token belongs to. muster's own logout
// revocation is keyed on it (see internal/api's sessionRevocations).
SessionID string `json:"session_id,omitempty"`
// AMR is how — and WHEN — the session's user authenticated: GoTrue's
// `amr` claim, one entry per method used ({"method":"password",
// "timestamp":…}). It is what the step-up gate reads (AuthenticatedAt).
AMR AMR `json:"amr,omitempty"`
}
Claims is what muster reads from a GoTrue access token.
func (Claims) AuthenticatedAt ¶
AuthenticatedAt is the most recent authentication the token records — the latest `amr` timestamp, whatever its method — and false when it records none.
ANY METHOD COUNTS, by design: the gate asks "did this person prove who they are recently", and a passkey (webauthn) sign-in answers that as well as a password does. A method muster has never heard of still counts, because GoTrue signed it.
type Client ¶
type Client struct {
// BaseURL is GoTrue's root, e.g. http://auth.example.com:9999.
BaseURL string
// Secret is the shared HS256 secret; admin calls sign their service_role
// token with it.
Secret []byte
// Issuer is put on the service_role token (GOTRUE_JWT_ISSUER).
Issuer string
// HTTP is the transport; nil means a client with a 10 s timeout.
HTTP *http.Client
// Now is the clock; nil means time.Now.
Now func() time.Time
}
Client talks to one GoTrue instance.
func (*Client) AdminAppMetadata ¶
func (c *Client) AdminAppMetadata(ctx context.Context, clientIP, userID string) (map[string]any, error)
AdminAppMetadata reads user userID's app_metadata (admin-writable only; a user cannot change it).
func (*Client) AdminCreateUser ¶
func (c *Client) AdminCreateUser(ctx context.Context, clientIP, email, password string) (string, error)
AdminCreateUser creates a CONFIRMED user and returns its id (the `sub`).
🔴 email_confirm IS SENT, ALWAYS. Measured against v2.189.0 and v2.197.0: /admin/users ignores GOTRUE_MAILER_AUTOCONFIRM, and a user created without it cannot sign in (400 email_not_confirmed). muster has no SMTP, so nobody would ever confirm.
func (*Client) AdminDeleteAllPasskeys ¶
AdminDeleteAllPasskeys deletes every passkey user userID has and returns how many it deleted. GoTrue has no bulk delete: it lists, then deletes each, and stops at the first failure — a caller that must not leave a passkey behind treats any error as "some may remain".
func (*Client) AdminDeletePasskey ¶
AdminDeletePasskey deletes one of user userID's passkeys.
func (*Client) AdminDeleteUser ¶
AdminDeleteUser deletes a user. muster uses it only to compensate a GoTrue user whose muster-side binding failed to commit.
func (*Client) AdminPasskeys ¶
AdminPasskeys lists user userID's passkeys.
func (*Client) AdminRecoveryLink ¶
AdminRecoveryLink mints a single-use recovery token for email and returns its hashed form (GoTrue's `hashed_token`), which /verify accepts as token_hash.
func (*Client) AdminSetAppMetadata ¶
func (c *Client) AdminSetAppMetadata(ctx context.Context, clientIP, userID, key string, value any) error
AdminSetAppMetadata sets ONE top-level key of user userID's app_metadata. GoTrue merges app_metadata by top-level key, so the other keys are kept; a nil value removes the key.
func (*Client) AdminSetBanned ¶
AdminSetBanned bans (or un-bans) a user. A ban also makes GoTrue refuse that user's refresh tokens.
func (*Client) AdminSetPassword ¶
AdminSetPassword sets userID's password through the admin path.
func (*Client) AdminSignOutEverywhere ¶
AdminSignOutEverywhere revokes every GoTrue session (refresh token) of user userID, as a disable must.
🔴 GoTrue HAS NO ADMIN "SIGN OUT USER" ENDPOINT, AND A BAN DOES NOT END A SESSION — measured on v2.189.0 and v2.197.0: a refresh token from before a ban is accepted again once the ban is lifted. What does end them is the user's own global sign-out, and muster holds the HS256 secret GoTrue verifies with, so it mints a short-lived token FOR the user (no session_id: GoTrue refuses a session_id that is not a real session's UUID) and calls /logout?scope=global with it. Measured: 204, and the user's refresh tokens are then refresh_token_not_found (v2.189.0 and v2.197.0).
🔴 CALL IT BEFORE THE BAN. Since v2.197.0 GoTrue refuses /logout for a banned user (403 user_banned) — measured; v2.189.0 answered 204 — so a sign-out after the ban does nothing (see SetUserDisabledAs).
func (*Client) DeletePasskey ¶
DeletePasskey deletes one of the passkeys of the account accessToken belongs to. GoTrue answers 404 for a passkey that is not that account's.
func (*Client) Logout ¶
Logout revokes the session accessToken belongs to (ScopeLocal) or every session of its user (ScopeGlobal).
func (*Client) PasskeyRegisterOptions ¶
func (c *Client) PasskeyRegisterOptions(ctx context.Context, clientIP, accessToken string) (PasskeyOptions, error)
PasskeyRegisterOptions starts adding a passkey to the account accessToken belongs to.
func (*Client) PasskeyRegisterVerify ¶
func (c *Client) PasskeyRegisterVerify(ctx context.Context, clientIP, accessToken, challengeID string, credential json.RawMessage) (Passkey, error)
PasskeyRegisterVerify finishes adding a passkey. credential must already be canonical (CanonicalAttestation).
func (*Client) PasskeySignInOptions ¶
PasskeySignInOptions starts a usernameless (discoverable-credential) sign-in.
func (*Client) PasskeySignInVerify ¶
func (c *Client) PasskeySignInVerify(ctx context.Context, clientIP, challengeID string, credential json.RawMessage) (Session, error)
PasskeySignInVerify finishes a passkey sign-in: GoTrue verifies the assertion against the challenge and, for the user its userHandle names, issues a session. credential must already be canonical (CanonicalAssertion).
func (*Client) PasswordGrant ¶
func (c *Client) PasswordGrant(ctx context.Context, clientIP, email, password string) (Session, error)
PasswordGrant signs a user in.
func (*Client) Refresh ¶
Refresh exchanges a refresh token for a new pair.
⚠ GoTrue ROTATES on every refresh: the token passed in is spent. Measured (rotation on, no reuse interval; v2.189.0 and again on v2.197.0, unchanged): replaying the PARENT of the current token is accepted, replaying an older one revokes the whole session. internal/api coalesces concurrent refreshes of one token so two tabs do not walk a session into that revocation.
func (*Client) ServiceToken ¶
ServiceToken mints the service_role token an admin call carries.
type LogoutScope ¶
type LogoutScope string
LogoutScope is GoTrue's /logout scope.
const ( // ScopeLocal revokes the session this access token belongs to. ScopeLocal LogoutScope = "local" // ScopeGlobal revokes every session of the user ("sign out everywhere"). ScopeGlobal LogoutScope = "global" )
type Passkey ¶
type Passkey struct {
ID string `json:"id"`
FriendlyName string `json:"friendly_name,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}
Passkey is one registered passkey as GoTrue lists it.
type PasskeyOptions ¶
type PasskeyOptions struct {
ChallengeID string `json:"challenge_id"`
Options json.RawMessage `json:"options"`
ExpiresAt int64 `json:"expires_at"`
}
PasskeyOptions is GoTrue's answer to an options call: a single-use challenge (bound server-side to the WebAuthn session data) and the options to hand to navigator.credentials.get / create.
type Session ¶
type Session struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
User struct {
ID string `json:"id"`
Email string `json:"email"`
} `json:"user"`
}
Session is a token pair GoTrue issued.
type Settings ¶
type Settings struct {
PasskeysEnabled bool `json:"passkeys_enabled"`
}
Settings is the part of GoTrue's public /settings muster reads.
type Verifier ¶
type Verifier struct {
Secret []byte
Issuer string
Audience string
// Skew is the clock tolerance; zero means DefaultSkew.
Skew time.Duration
// Now is the clock; nil means time.Now.
Now func() time.Time
}
Verifier checks access tokens against one secret, issuer and audience.
func (Verifier) Verify ¶
Verify parses and checks token, returning its claims.
Order, and why it is this order: the alg is checked first (nothing else is computed for a token muster would never accept); then the signature, with hmac.Equal, BEFORE any claim is trusted; then iss, aud, sub; then time. A token that is merely expired returns its claims WITH ErrExpired, so the caller can log who it was — it must still not act on them.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package gotruetest is an in-memory GoTrue for muster's tests: the endpoints internal/gotrue calls, with the behaviours muster depends on modelled on the MEASURED behaviour of GoTrue v2.197.0 (see internal/gotrue's comments; the same probe run against v2.189.0 differed only where noted below).
|
Package gotruetest is an in-memory GoTrue for muster's tests: the endpoints internal/gotrue calls, with the behaviours muster depends on modelled on the MEASURED behaviour of GoTrue v2.197.0 (see internal/gotrue's comments; the same probe run against v2.189.0 differed only where noted below). |