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

136
service_otp.go Normal file
View file

@ -0,0 +1,136 @@
package authkit
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"git.juancwu.dev/juancwu/errx"
)
// RequestEmailOTP mints a numeric one-time code for the email and returns
// the plaintext for delivery. Anti-enumeration: unknown email returns
// ("", nil) unless Config.RevealUnknownEmail is set.
//
// Code length is Config.EmailOTPDigits (default 6). Brute-force resistance
// comes from Config.EmailOTPMaxAttempts (default 5): after N wrong tries
// the code is invalidated, forcing the caller to request a new one.
func (a *Auth) RequestEmailOTP(ctx context.Context, email string) (string, error) {
const op = "authkit.Auth.RequestEmailOTP"
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
if errors.Is(err, ErrUserNotFound) && !a.cfg.RevealUnknownEmail {
return "", nil
}
return "", errx.Wrap(op, err)
}
code, err := generateOTPCode(a.cfg.Random, a.cfg.EmailOTPDigits)
if err != nil {
return "", errx.Wrap(op, err)
}
now := a.now()
attempts := a.cfg.EmailOTPMaxAttempts
t := &Token{
Hash: hashOTPCode(code),
Kind: TokenEmailOTP,
UserID: u.ID,
AttemptsRemaining: &attempts,
CreatedAt: now,
ExpiresAt: now.Add(a.cfg.EmailOTPTTL),
}
if err := a.storeCreateToken(ctx, t); err != nil {
return "", errx.Wrap(op, err)
}
return code, nil
}
// ConsumeEmailOTP verifies a code against the most recent active OTP for
// the user behind email. Successful match consumes the row. A wrong code
// decrements attempts_remaining and returns ErrOTPInvalid; reaching zero
// attempts invalidates the OTP. A successful consume implicitly verifies
// the email.
func (a *Auth) ConsumeEmailOTP(ctx context.Context, email, code string) (*User, error) {
const op = "authkit.Auth.ConsumeEmailOTP"
if code == "" {
return nil, errx.Wrap(op, ErrOTPInvalid)
}
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
if errors.Is(err, ErrUserNotFound) {
// Don't leak account existence — same error shape as wrong code.
return nil, errx.Wrap(op, ErrOTPInvalid)
}
return nil, errx.Wrap(op, err)
}
now := a.now()
active, err := a.storeGetActiveOTPForUser(ctx, TokenEmailOTP, uuidArg(u.ID), now)
if err != nil {
return nil, errx.Wrap(op, err)
}
if !bytes.Equal(active.Hash, hashOTPCode(code)) {
// Wrong code: decrement attempts on the active OTP. If this
// drives attempts_remaining to 0, the row is consumed atomically
// inside the same UPDATE.
_, derr := a.storeDecrementOTPAttempt(ctx, TokenEmailOTP, active.Hash, now)
if derr != nil && !errors.Is(derr, ErrTokenInvalid) {
return nil, errx.Wrap(op, derr)
}
return nil, errx.Wrap(op, ErrOTPInvalid)
}
if _, err := a.storeConsumeOTPByHash(ctx, TokenEmailOTP, active.Hash, now); err != nil {
return nil, errx.Wrap(op, err)
}
if u.EmailVerifiedAt == nil {
if err := a.storeSetEmailVerified(ctx, u.ID, now); err == nil {
u.EmailVerifiedAt = &now
}
}
return u, nil
}
// generateOTPCode produces a numeric code of length digits using a CSPRNG
// (defaults to crypto/rand if rng is nil). Uniformly distributed; rejects
// rolls that would bias the mod operator.
func generateOTPCode(rng io.Reader, digits int) (string, error) {
if digits <= 0 || digits > 12 {
return "", fmt.Errorf("invalid OTP digits: %d", digits)
}
if rng == nil {
rng = rand.Reader
}
max := uint64(1)
for i := 0; i < digits; i++ {
max *= 10
}
// Reject rolls that fall in the "leftover" partial keyspace at the top
// of uint64 to keep the distribution uniform.
limit := (^uint64(0)) - ((^uint64(0)) % max)
var buf [8]byte
for {
if _, err := io.ReadFull(rng, buf[:]); err != nil {
return "", err
}
v := binary.BigEndian.Uint64(buf[:])
if v >= limit {
continue
}
return fmt.Sprintf("%0*d", digits, v%max), nil
}
}
// hashOTPCode returns sha256(code). Codes are short and low-entropy, so the
// hash is purely a database lookup key — the brute-force defense is
// attempts_remaining, not hash strength.
func hashOTPCode(code string) []byte {
sum := sha256.Sum256([]byte(code))
return sum[:]
}