Rebuild for v1.0.0: postgres-only, slug-keyed authz, predicate API

Drops the Dialect/Queries abstraction in favor of a single PostgreSQL 16+
implementation collapsed into the root authkit package, removes the
public store interfaces, and reshapes the authorization model around
seeded slugs (roles, permissions, abilities) with optional labels.

Schema is now squashed into one migrations/0001_init.sql and applied
automatically on authkit.New (opt-out via Config.SkipAutoMigrate). A
schema verifier checks tables/columns/types/nullability on startup,
tolerates extra columns, and falls back to default table names when a
configured override is missing.

Auth API: CreateUser + SetPassword replace Register; password is
nullable. Email OTP (RequestEmailOTP/ConsumeEmailOTP) joins magic links
and password reset, all with anti-enumeration silent-success defaults
and a Config.RevealUnknownEmail opt-in. Service tokens drop owner
columns and validate ability slugs against authkit_abilities at issue.
Direct user permissions live alongside role-derived ones; queries
return their UNION.

Predicate API: HasRole/HasPermission/HasAbility leaves with
AnyLogin/AllLogin/AnyServiceKey/AllServiceKey combinators. Validate
runs at middleware construction, panicking on unknown slugs.

Middleware collapses to RequireLogin (cookie + JWT), RequireGuest
(configurable OnAuthenticated), and RequireServiceKey. UserIDFromCtx /
UserFromCtx (lazy) / RefreshUserInCtx provide request-lifetime user
caching. Cookie defaults flip to Secure=true and HttpOnly=true via
*bool with BoolPtr opt-out.

CLIs ship under cmd/perms, cmd/roles, cmd/abilities for seeding the
authorization vocabulary; the library never seeds rows itself.

Tests cover unit-level (slug validation + fuzz, opaque secrets, email
normalization, extractors, predicates, OTP generator) and integration
flows gated on AUTHKIT_TEST_DATABASE_URL (every Auth method, schema
drift detection, migration idempotency, lazy user cache, all middleware
paths).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
juancwu 2026-04-26 23:27:30 +00:00
commit d3c5367492
80 changed files with 5605 additions and 4565 deletions

View file

@ -3,53 +3,61 @@ package authkit
import (
"context"
"errors"
"strings"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// normalizeEmail produces the lookup form used by UserStore.GetUserByEmail
// and the email_normalized column. Trim + lowercase is intentional; we do
// not collapse Gmail-style "+" addressing or strip dots — that's a policy
// decision callers can layer on top.
func normalizeEmail(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}
// Register creates a new user with an Argon2id-hashed password. Returns
// ErrEmailTaken if the normalized email is already registered.
func (a *Auth) Register(ctx context.Context, email, password string) (*User, error) {
const op = "authkit.Auth.Register"
if email == "" || password == "" {
// CreateUser registers a new account with the given email. Password is
// optional — accounts can be created without a credential and have one set
// later via SetPassword. Returns ErrEmailTaken if the normalized email is
// already registered.
func (a *Auth) CreateUser(ctx context.Context, email string) (*User, error) {
const op = "authkit.Auth.CreateUser"
if email == "" {
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
hash, err := a.deps.Hasher.Hash(password)
if err != nil {
return nil, errx.Wrap(op, err)
}
now := a.now()
u := &User{
ID: uuid.New(),
Email: email,
EmailNormalized: normalizeEmail(email),
PasswordHash: hash,
CreatedAt: now,
UpdatedAt: now,
}
if err := a.deps.Users.CreateUser(ctx, u); err != nil {
if err := a.storeCreateUser(ctx, u); err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// SetPassword stores a password hash for the user. Use for the
// initial-credential flow and for administrative password changes.
// Bumping session_version is the caller's responsibility; SetPassword does
// not invalidate existing sessions on its own. ChangePassword is the
// safer wrapper for end-user-driven changes.
func (a *Auth) SetPassword(ctx context.Context, userID uuid.UUID, password string) error {
const op = "authkit.Auth.SetPassword"
if password == "" {
return errx.Wrap(op, ErrInvalidCredentials)
}
hash, err := a.hasher.Hash(password)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeSetPassword(ctx, userID, hash); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// LoginPassword verifies the password and returns the authenticated user.
// Failure increments failed_logins; success resets it and stamps last_login_at.
// LoginHook (if configured) is invoked with the success outcome — use this to
// hook in rate limiting or audit logging.
// Failure does not increment any counter — consumers wanting lockout should
// implement it via LoginHook (see README). Success resets nothing and stamps
// last_login_at. LoginHook is invoked with the success outcome.
func (a *Auth) LoginPassword(ctx context.Context, email, password string) (*User, error) {
const op = "authkit.Auth.LoginPassword"
u, err := a.deps.Users.GetUserByEmail(ctx, normalizeEmail(email))
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
_ = a.fireLoginHook(ctx, email, false)
if errors.Is(err, ErrUserNotFound) {
@ -58,32 +66,29 @@ func (a *Auth) LoginPassword(ctx context.Context, email, password string) (*User
return nil, errx.Wrap(op, err)
}
if u.PasswordHash == "" {
// Password-less account (invite-only / magic-link-only). Treat the
// same as wrong password to avoid leaking account state.
_ = a.fireLoginHook(ctx, email, false)
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
ok, needsRehash, err := a.deps.Hasher.Verify(password, u.PasswordHash)
ok, needsRehash, err := a.hasher.Verify(password, u.PasswordHash)
if err != nil {
return nil, errx.Wrap(op, err)
}
if !ok {
_, _ = a.deps.Users.IncrementFailedLogins(ctx, u.ID)
_ = a.fireLoginHook(ctx, email, false)
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
now := a.now()
u.LastLoginAt = &now
u.FailedLogins = 0
if err := a.deps.Users.ResetFailedLogins(ctx, u.ID); err != nil {
return nil, errx.Wrap(op, err)
}
if err := a.deps.Users.UpdateUser(ctx, u); err != nil {
if err := a.storeUpdateUser(ctx, u); err != nil {
return nil, errx.Wrap(op, err)
}
if needsRehash {
if newHash, herr := a.deps.Hasher.Hash(password); herr == nil {
_ = a.deps.Users.SetPassword(ctx, u.ID, newHash)
if newHash, herr := a.hasher.Hash(password); herr == nil {
_ = a.storeSetPassword(ctx, u.ID, newHash)
u.PasswordHash = newHash
}
}
@ -92,46 +97,76 @@ func (a *Auth) LoginPassword(ctx context.Context, email, password string) (*User
}
// ChangePassword verifies the current password, sets the new one, and bumps
// the user's session_version so all outstanding JWT access tokens are
// instantly invalidated. Outstanding opaque sessions are also revoked.
// the user's session_version (invalidating outstanding JWTs). Outstanding
// opaque sessions are also revoked.
func (a *Auth) ChangePassword(ctx context.Context, userID uuid.UUID, oldPassword, newPassword string) error {
const op = "authkit.Auth.ChangePassword"
u, err := a.deps.Users.GetUserByID(ctx, userID)
u, err := a.storeGetUserByID(ctx, userID)
if err != nil {
return errx.Wrap(op, err)
}
if u.PasswordHash == "" {
return errx.Wrap(op, ErrInvalidCredentials)
}
ok, _, err := a.deps.Hasher.Verify(oldPassword, u.PasswordHash)
ok, _, err := a.hasher.Verify(oldPassword, u.PasswordHash)
if err != nil {
return errx.Wrap(op, err)
}
if !ok {
return errx.Wrap(op, ErrInvalidCredentials)
}
newHash, err := a.deps.Hasher.Hash(newPassword)
newHash, err := a.hasher.Hash(newPassword)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.deps.Users.SetPassword(ctx, userID, newHash); err != nil {
if err := a.storeSetPassword(ctx, userID, newHash); err != nil {
return errx.Wrap(op, err)
}
if _, err := a.deps.Users.BumpSessionVersion(ctx, userID); err != nil {
if _, err := a.storeBumpSessionVersion(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
if err := a.deps.Sessions.DeleteUserSessions(ctx, userID); err != nil {
if err := a.storeDeleteUserSessions(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// GetUser fetches the user by ID. Returns ErrUserNotFound if absent.
func (a *Auth) GetUser(ctx context.Context, userID uuid.UUID) (*User, error) {
const op = "authkit.Auth.GetUser"
u, err := a.storeGetUserByID(ctx, userID)
if err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// GetUserByEmail fetches the user by email (input is normalized internally).
func (a *Auth) GetUserByEmail(ctx context.Context, email string) (*User, error) {
const op = "authkit.Auth.GetUserByEmail"
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// DeleteUser removes the user. Cascades to sessions, tokens, role
// assignments, and direct permission grants via FK ON DELETE CASCADE.
func (a *Auth) DeleteUser(ctx context.Context, userID uuid.UUID) error {
const op = "authkit.Auth.DeleteUser"
if err := a.storeDeleteUser(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RequestEmailVerification mints a single-use email-verify token for the
// user. Return the plaintext to the caller so they can put it in an email
// link; the lookup hash is stored in TokenStore.
// user. Return the plaintext to the caller for delivery; the lookup hash
// is what's stored.
func (a *Auth) RequestEmailVerification(ctx context.Context, userID uuid.UUID) (string, error) {
const op = "authkit.Auth.RequestEmailVerification"
plaintext, hash, err := mintSecret(prefixEmailVerify, a.cfg.Random)
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixEmailVerify)
if err != nil {
return "", errx.Wrap(op, err)
}
@ -143,36 +178,42 @@ func (a *Auth) RequestEmailVerification(ctx context.Context, userID uuid.UUID) (
CreatedAt: now,
ExpiresAt: now.Add(a.cfg.EmailVerifyTTL),
}
if err := a.deps.Tokens.CreateToken(ctx, t); err != nil {
if err := a.storeCreateToken(ctx, t); err != nil {
return "", errx.Wrap(op, err)
}
return plaintext, nil
}
// ConfirmEmail consumes the verification token and marks the user's email
// verified. Returns ErrTokenInvalid if the token is missing/expired/used.
// ConfirmEmail consumes a verification token and marks the user's email
// verified. Returns ErrTokenInvalid for missing/expired/already-used tokens.
func (a *Auth) ConfirmEmail(ctx context.Context, plaintextToken string) (*User, error) {
const op = "authkit.Auth.ConfirmEmail"
hash, ok := parseSecret(prefixEmailVerify, plaintextToken)
hash, ok := ParseOpaqueSecret(prefixEmailVerify, plaintextToken)
if !ok {
return nil, errx.Wrap(op, ErrTokenInvalid)
}
now := a.now()
t, err := a.deps.Tokens.ConsumeToken(ctx, TokenEmailVerify, hash, now)
t, err := a.storeConsumeToken(ctx, TokenEmailVerify, hash, now)
if err != nil {
return nil, errx.Wrap(op, err)
}
if err := a.deps.Users.SetEmailVerified(ctx, t.UserID, now); err != nil {
if err := a.storeSetEmailVerified(ctx, t.UserID, now); err != nil {
return nil, errx.Wrap(op, err)
}
return a.deps.Users.GetUserByID(ctx, t.UserID)
return a.storeGetUserByID(ctx, t.UserID)
}
// fireLoginHook is a thin wrapper that suppresses panics from caller-supplied
// hooks; we never want a misbehaving telemetry hook to break login.
func (a *Auth) fireLoginHook(ctx context.Context, email string, success bool) error {
// fireLoginHook runs Config.LoginHook if configured. Returned errors are
// surfaced for the caller to log; they never break login. The hook is
// wrapped in recover() so a misbehaving hook can't take down the auth path.
func (a *Auth) fireLoginHook(ctx context.Context, email string, success bool) (err error) {
if a.cfg.LoginHook == nil {
return nil
}
defer func() {
if r := recover(); r != nil {
err = errx.Newf("authkit.fireLoginHook", "login hook panicked: %v", r)
}
}()
return a.cfg.LoginHook(ctx, email, success)
}