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

134
store_tokens.go Normal file
View file

@ -0,0 +1,134 @@
package authkit
import (
"context"
"database/sql"
"time"
"git.juancwu.dev/juancwu/errx"
)
func (a *Auth) storeCreateToken(ctx context.Context, t *Token) error {
const op = "authkit.storeCreateToken"
if t.CreatedAt.IsZero() {
t.CreatedAt = a.now()
}
_, err := a.db.ExecContext(ctx, a.q.createToken,
t.Hash, string(t.Kind), uuidArg(t.UserID), chainArg(t.ChainID),
nullableTime(t.ConsumedAt), nullableInt(t.AttemptsRemaining),
t.CreatedAt, t.ExpiresAt)
if err != nil {
return errx.Wrap(op, err)
}
return nil
}
// storeConsumeToken atomically marks the matching unexpired, unconsumed token
// as consumed and returns it. Returns ErrTokenInvalid if no row matched.
// Implementations MUST do this in one statement to prevent double-spend
// under concurrent callers.
func (a *Auth) storeConsumeToken(ctx context.Context, kind TokenKind, hash []byte, now time.Time) (*Token, error) {
const op = "authkit.storeConsumeToken"
row := a.db.QueryRowContext(ctx, a.q.consumeToken, now, string(kind), hash, now)
t, err := scanToken(row)
if err != nil {
return nil, errx.Wrap(op, mapNotFound(err, ErrTokenInvalid))
}
return t, nil
}
func (a *Auth) storeGetToken(ctx context.Context, kind TokenKind, hash []byte) (*Token, error) {
const op = "authkit.storeGetToken"
row := a.db.QueryRowContext(ctx, a.q.getToken, string(kind), hash)
t, err := scanToken(row)
if err != nil {
return nil, errx.Wrap(op, mapNotFound(err, ErrTokenInvalid))
}
return t, nil
}
// storeGetActiveOTPForUser returns the most recent unconsumed, unexpired OTP
// row for a user. Used by ConsumeEmailOTP to verify a code by hash-comparing
// client input.
func (a *Auth) storeGetActiveOTPForUser(ctx context.Context, kind TokenKind, userID any, now time.Time) (*Token, error) {
const op = "authkit.storeGetActiveOTPForUser"
row := a.db.QueryRowContext(ctx, a.q.getOTPForUser, string(kind), userID, now)
t, err := scanToken(row)
if err != nil {
return nil, errx.Wrap(op, mapNotFound(err, ErrOTPInvalid))
}
return t, nil
}
// storeDecrementOTPAttempt drops attempts_remaining by 1 on the matched
// (kind, hash) row, consuming it when zero. Returns the new
// attempts_remaining (0 = consumed). ErrTokenInvalid when no row matched.
func (a *Auth) storeDecrementOTPAttempt(ctx context.Context, kind TokenKind, hash []byte, now time.Time) (int, error) {
const op = "authkit.storeDecrementOTPAttempt"
var remaining sql.NullInt32
if err := a.db.QueryRowContext(ctx, a.q.decrementOTPAttempt,
now, string(kind), hash).Scan(&remaining); err != nil {
return 0, errx.Wrap(op, mapNotFound(err, ErrTokenInvalid))
}
if !remaining.Valid {
return 0, nil
}
return int(remaining.Int32), nil
}
// storeConsumeOTPByHash marks an OTP row consumed by direct hash match. Used
// on the success path of ConsumeEmailOTP.
func (a *Auth) storeConsumeOTPByHash(ctx context.Context, kind TokenKind, hash []byte, now time.Time) (*Token, error) {
const op = "authkit.storeConsumeOTPByHash"
row := a.db.QueryRowContext(ctx, a.q.consumeOTPByID, now, string(kind), hash)
t, err := scanToken(row)
if err != nil {
return nil, errx.Wrap(op, mapNotFound(err, ErrOTPInvalid))
}
return t, nil
}
func (a *Auth) storeDeleteByChain(ctx context.Context, chainID string) (int64, error) {
const op = "authkit.storeDeleteByChain"
tag, err := a.db.ExecContext(ctx, a.q.deleteByChain, chainID)
if err != nil {
return 0, errx.Wrap(op, err)
}
n, _ := tag.RowsAffected()
return n, nil
}
func (a *Auth) storeDeleteExpiredTokens(ctx context.Context, now time.Time) (int64, error) {
const op = "authkit.storeDeleteExpiredTokens"
tag, err := a.db.ExecContext(ctx, a.q.deleteExpiredTokens, now)
if err != nil {
return 0, errx.Wrap(op, err)
}
n, _ := tag.RowsAffected()
return n, nil
}
func scanToken(row rowScanner) (*Token, error) {
var (
t Token
kind string
userIDStr string
chainID sql.NullString
consumedAt sql.NullTime
attempts sql.NullInt32
)
if err := row.Scan(&t.Hash, &kind, &userIDStr, &chainID,
&consumedAt, &attempts, &t.CreatedAt, &t.ExpiresAt); err != nil {
return nil, err
}
t.Kind = TokenKind(kind)
uid, err := scanUUID(userIDStr)
if err != nil {
return nil, err
}
t.UserID = uid
t.ChainID = scanNullStringPtr(chainID)
t.ConsumedAt = scanNullTimePtr(consumedAt)
t.AttemptsRemaining = scanNullIntPtr(attempts)
return &t, nil
}