auth

package
v0.0.0-...-610d9af Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: GPL-3.0 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 contains the security primitives of the service: password hashing (Argon2id), signed JWTs (stateless bearer auth), opaque random tokens (database-backed sessions, email verification, password reset) and the GitHub OAuth client. It knows nothing about HTTP routing or the database.

Index

Constants

View Source
const MaxPasswordBytes = 128

MaxPasswordBytes bounds the password length we are willing to hash. Argon2 has no inherent limit (bcrypt silently stops at 72 bytes), but without any cap a client could send megabytes per login and make us hash them. 128 bytes is far beyond any human-typed password or password-manager output. It mirrors domain.MaxPasswordBytes: duplicated on purpose so this package enforces the rule itself.

View Source
const MinSecretBytes = 32

MinSecretBytes mirrors config.MinSecretBytes. Duplicated deliberately: this package enforces the rule itself instead of trusting its caller (defense in depth).

Variables

View Source
var (
	// ErrInvalidHash: not a well-formed argon2id PHC string, or parameters outside the sane window.
	ErrInvalidHash = errors.New("auth: invalid password hash")
	// ErrUnsupportedAlgorithm: a well-formed PHC/crypt string for another algorithm. This is what
	// a legacy bcrypt hash ("$2a$12$...") looks like. See the README on migrating such users.
	ErrUnsupportedAlgorithm = errors.New("auth: unsupported password hash algorithm")
	// ErrIncompatibleVersion: argon2id, but not Argon2 version 0x13 (19), the only one we implement.
	ErrIncompatibleVersion = errors.New("auth: incompatible argon2 version")
	// ErrPasswordTooLong is returned by Hash for input over MaxPasswordBytes.
	ErrPasswordTooLong = errors.New("auth: password too long")
)

Errors returned by Verify for stored hashes it cannot use. They describe a problem with the STORED value, never with the user's input.

View Source
var DefaultParams = Params{Memory: 19 * 1024, Iterations: 2, Parallelism: 1, SaltLen: 16, KeyLen: 32}

DefaultParams follows the OWASP Password Storage Cheat Sheet's first-choice Argon2id setting: m=19 MiB (19456 KiB), t=2, p=1. OWASP lists several equivalent trade-offs (for example m=46 MiB, t=1 or m=12 MiB, t=3) so you can trade memory for time on a small box.

RFC 9106 describes a stronger "second recommended" profile for memory-constrained servers: m=64 MiB, t=3, p=4 (and a 2 GiB profile when you can afford it). Use it if your login volume and RAM allow; every request that hashes needs that much RAM for its duration, which is why PasswordHasher limits concurrent hashes. Re-measure on your own hardware: aim for roughly 50-250 ms per hash. When you raise these numbers, existing hashes keep working and are upgraded transparently at next login (Verify's needsRehash result).

View Source
var ErrInvalidToken = errors.New("invalid token")

ErrInvalidToken is returned for EVERY token problem (malformed, bad signature, wrong algorithm, expired, wrong issuer...). Callers cannot and should not distinguish them: telling a client precisely why a token failed only helps an attacker.

Functions

func HashToken

func HashToken(token string) string

HashToken returns the lowercase-hex SHA-256 of token. This is the value stored in (and looked up from) session.token_hash and verification.value.

func NewPKCEVerifier

func NewPKCEVerifier() string

NewPKCEVerifier returns a fresh random PKCE code verifier (43 URL-safe characters).

func NewToken

func NewToken() (token, hash string, err error)

NewToken returns a fresh random token and the value to store in the database.

The token is what goes to the client (a session cookie, an emailed link). The database keeps only HashToken(token). Better Auth stores the raw session token; we deliberately do not: if the database leaks (backup, SQL injection, a curious DBA), raw tokens would be live logins for everybody, while SHA-256 digests cannot be turned back into a working cookie.

Why SHA-256 and not Argon2id here? Passwords are low-entropy human choices, so the hash must be slow to make guessing expensive. A 256-bit random token cannot be guessed at all, so a fast hash is enough, and it keeps the per-request session lookup cheap (it runs on EVERY authenticated request).

Types

type Claims

type Claims struct {
	UserID    string
	ExpiresAt time.Time
}

Claims is what we extract from a valid token.

type GitHub

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

GitHub implements "Sign in with GitHub" using the OAuth 2.0 authorization-code flow with PKCE.

The flow, and who talks to whom:

  1. Browser -> us: GET /oauth/github. We generate a random `state` and a PKCE `verifier`, remember both in a short-lived cookie, and redirect the browser to GitHub with state + code_challenge = SHA-256(verifier).
  2. Browser -> GitHub: the user logs in and approves. GitHub redirects back to us with ?code=...&state=...
  3. Browser -> us: GET /oauth/github/callback. We compare `state` with the cookie (defends against login CSRF: an attacker making YOUR browser complete THEIR flow).
  4. Us -> GitHub: exchange code (+ the verifier) for an access token, server to server. GitHub checks SHA-256(verifier) == the challenge from step 1, so a stolen `code` is useless without the verifier that never left our cookie. (PKCE was designed for public clients, but RFC 9700 recommends it for confidential ones too.)
  5. Us -> GitHub API: fetch the profile and verified email, then create/link the user.

func NewGitHub

func NewGitHub(c GitHubConfig) (*GitHub, error)

NewGitHub validates cfg, applies defaults and builds the client.

func (*GitHub) AuthCodeURL

func (g *GitHub) AuthCodeURL(state, verifier string) string

AuthCodeURL returns the GitHub URL to redirect the browser to (step 1).

func (*GitHub) Profile

func (g *GitHub) Profile(ctx context.Context, code, verifier string) (OAuthProfile, error)

Profile completes the flow (steps 4 and 5): it exchanges code for a token and loads the user's identity. It returns an error unless GitHub reports a verified primary email.

type GitHubConfig

type GitHubConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string // our callback URL, must match the one registered in the GitHub OAuth app

	AuthURL    string       // default https://github.com/login/oauth/authorize
	TokenURL   string       // default https://github.com/login/oauth/access_token
	APIBaseURL string       // default https://api.github.com
	HTTPClient *http.Client // default: 10 second timeout
}

GitHubConfig configures the GitHub client. Only ClientID, ClientSecret and RedirectURL are required; the URLs default to github.com and are fields so tests can point the whole flow at an httptest fake of GitHub.

type Issuer

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

Issuer creates and verifies HS256 JWTs.

HS256 is a symmetric scheme: the same secret signs and verifies. That is right for a single service that is both issuer and verifier. If other services must verify tokens without being able to mint them, switch to an asymmetric algorithm (RS256/EdDSA) and publish the public key.

func NewIssuer

func NewIssuer(secret []byte, ttl time.Duration, now func() time.Time) (*Issuer, error)

NewIssuer builds an Issuer. now may be nil (defaults to time.Now); tests inject a fake clock to exercise expiry without sleeping.

func (*Issuer) Issue

func (i *Issuer) Issue(userID string) (string, time.Time, error)

Issue signs a token for userID and returns it with its expiry time.

func (*Issuer) Parse

func (i *Issuer) Parse(token string) (Claims, error)

Parse verifies the signature, algorithm, issuer and expiry, and returns the claims.

type OAuthProfile

type OAuthProfile struct {
	Provider  string // "github"
	AccountID string // the provider's stable user id (GitHub: numeric id; NOT the changeable login)
	Email     string
	// EmailVerified is true only when the provider itself vouches for ownership of Email.
	// Account linking by email is only safe for verified addresses.
	EmailVerified bool
	Name          string
	Image         string

	// Provider credentials, stored in the account table like Better Auth does.
	AccessToken           string
	RefreshToken          string
	IDToken               string
	AccessTokenExpiresAt  *time.Time
	RefreshTokenExpiresAt *time.Time
	Scope                 string
}

OAuthProfile is what we learn about a user from an OAuth provider, in provider-neutral form.

type Params

type Params struct {
	Memory      uint32 // KiB of RAM per hash ("m")
	Iterations  uint32 // passes over that memory ("t")
	Parallelism uint8  // lanes/threads ("p")
	SaltLen     uint32 // bytes of random salt
	KeyLen      uint32 // bytes of output hash
}

Params are the tunable Argon2id cost parameters.

Why Argon2id and not bcrypt? Password hashing exists to make an OFFLINE attack on a stolen database slow. Attackers do not use CPUs, they use GPUs and ASICs with thousands of cores. bcrypt needs only 4 KiB of memory, so those cores run it nearly for free. Argon2 is "memory-hard": every guess must fill and repeatedly read Memory KiB of RAM, and RAM per core is exactly what a GPU or ASIC lacks. That is what the Memory parameter buys you; Iterations then adds sequential time on top. (Argon2id is the hybrid variant: it resists both side-channel attacks, like Argon2i, and GPU/TMTO attacks, like Argon2d. It is the one RFC 9106 and OWASP recommend. It also has no 72-byte input limit, unlike bcrypt.)

type PasswordHasher

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

PasswordHasher hashes and verifies passwords with Argon2id. Parameters are a field (not constants) so tests can use tiny, fast ones and production can raise them over time.

func NewPasswordHasher

func NewPasswordHasher(p Params) (*PasswordHasher, error)

NewPasswordHasher returns a hasher using p. Use DefaultParams in production.

func (*PasswordHasher) Hash

func (h *PasswordHasher) Hash(password string) (string, error)

Hash returns the PHC-format string

$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>

PHC ("Password Hashing Competition") string format is self-describing: algorithm, version, cost parameters and salt travel with the hash, so no separate salt column is needed and old hashes stay verifiable after you change the parameters. Every call draws a fresh random salt from crypto/rand, so hashing the same password twice gives different strings; salts defeat precomputed (rainbow) tables and make identical passwords look different.

func (*PasswordHasher) Verify

func (h *PasswordHasher) Verify(password, encoded string) (ok, needsRehash bool, err error)

Verify checks password against a stored PHC string.

  • ok reports whether the password matches. A wrong password is (false, false, nil): it is the normal "no", not an error.
  • needsRehash is true when the password matched but the stored hash was made with different parameters than this hasher's current ones. The caller should then Hash the password again and store the new string: that is how you raise the cost of every account over time without a forced password reset ("rehash on login": the plaintext is only available at login).
  • err is non-nil only when the STORED hash is unusable (ErrInvalidHash, ErrUnsupportedAlgorithm, ErrIncompatibleVersion). Parsing is strict.

The recomputed key is compared with crypto/subtle.ConstantTimeCompare so the comparison time does not reveal how many leading bytes matched.

Directories

Path Synopsis
Package githubtest is a minimal fake of GitHub's OAuth and REST endpoints for tests.
Package githubtest is a minimal fake of GitHub's OAuth and REST endpoints for tests.

Jump to

Keyboard shortcuts

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