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

@ -13,7 +13,7 @@ import (
// preserves that chain so reuse-detection can revoke the whole family.
func (a *Auth) IssueJWT(ctx context.Context, userID uuid.UUID) (access, refresh string, err error) {
const op = "authkit.Auth.IssueJWT"
u, err := a.deps.Users.GetUserByID(ctx, userID)
u, err := a.storeGetUserByID(ctx, userID)
if err != nil {
return "", "", errx.Wrap(op, err)
}
@ -40,7 +40,7 @@ func (a *Auth) AuthenticateJWT(ctx context.Context, access string) (*Principal,
if err != nil {
return nil, errx.Wrap(op, ErrTokenInvalid)
}
u, err := a.deps.Users.GetUserByID(ctx, uid)
u, err := a.storeGetUserByID(ctx, uid)
if err != nil {
if errors.Is(err, ErrUserNotFound) {
return nil, errx.Wrap(op, ErrTokenInvalid)
@ -64,27 +64,27 @@ func (a *Auth) AuthenticateJWT(ctx context.Context, access string) (*Principal,
}, nil
}
// RefreshJWT consumes the presented refresh token and mints a new access +
// refresh pair. Reuse of an already-consumed refresh token deletes the
// entire chain (logout-everywhere on that device family) and returns
// RefreshJWT consumes the presented refresh token and mints a new
// access+refresh pair. Reuse of an already-consumed refresh token deletes
// the entire chain (logout-everywhere on that device family) and returns
// ErrTokenReused.
func (a *Auth) RefreshJWT(ctx context.Context, plaintextRefresh string) (access, refresh string, err error) {
const op = "authkit.Auth.RefreshJWT"
hash, ok := parseSecret(prefixRefresh, plaintextRefresh)
hash, ok := ParseOpaqueSecret(prefixRefresh, plaintextRefresh)
if !ok {
return "", "", errx.Wrap(op, ErrTokenInvalid)
}
now := a.now()
consumed, err := a.deps.Tokens.ConsumeToken(ctx, TokenRefresh, hash, now)
consumed, err := a.storeConsumeToken(ctx, TokenRefresh, hash, now)
if err != nil {
// Differentiate plain-invalid (never existed / expired) from
// reuse (existed, already consumed). The presence-check below is
// the reuse signal.
// Differentiate plain-invalid (never existed / expired) from reuse
// (existed, already consumed). Existence-with-consumed is the
// reuse signal.
if errors.Is(err, ErrTokenInvalid) {
if existing, gerr := a.deps.Tokens.GetToken(ctx, TokenRefresh, hash); gerr == nil && existing.ConsumedAt != nil {
if existing, gerr := a.storeGetToken(ctx, TokenRefresh, hash); gerr == nil && existing.ConsumedAt != nil {
if existing.ChainID != nil && *existing.ChainID != "" {
_, _ = a.deps.Tokens.DeleteByChain(ctx, *existing.ChainID)
_, _ = a.storeDeleteByChain(ctx, *existing.ChainID)
}
return "", "", errx.Wrap(op, ErrTokenReused)
}
@ -98,7 +98,7 @@ func (a *Auth) RefreshJWT(ctx context.Context, plaintextRefresh string) (access,
}
if chainID == "" {
// Defensive: every refresh token should be chain-bound. Fall back
// to a fresh chain so we never throw on missing metadata.
// to a fresh chain rather than throwing on missing metadata.
chainID = uuid.NewString()
}
@ -113,11 +113,9 @@ func (a *Auth) RefreshJWT(ctx context.Context, plaintextRefresh string) (access,
return access, refresh, nil
}
// mintRefreshToken stores a fresh refresh token bound to chainID and returns
// the plaintext.
func (a *Auth) mintRefreshToken(ctx context.Context, userID uuid.UUID, chainID string) (string, error) {
const op = "authkit.Auth.mintRefreshToken"
plaintext, hash, err := mintSecret(prefixRefresh, a.cfg.Random)
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixRefresh)
if err != nil {
return "", errx.Wrap(op, err)
}
@ -130,17 +128,16 @@ func (a *Auth) mintRefreshToken(ctx context.Context, userID uuid.UUID, chainID s
CreatedAt: now,
ExpiresAt: now.Add(a.cfg.RefreshTokenTTL),
}
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
}
// userSessionVersion fetches the current session_version. Errors collapse to
// 0 on the assumption that AuthenticateJWT will reject stale tokens cleanly
// — but we still need a value to embed in the freshly-minted access token.
// userSessionVersion fetches the current session_version. Errors collapse
// to 0 — a stale token will fail AuthenticateJWT cleanly anyway.
func (a *Auth) userSessionVersion(ctx context.Context, userID uuid.UUID) int {
if u, err := a.deps.Users.GetUserByID(ctx, userID); err == nil {
if u, err := a.storeGetUserByID(ctx, userID); err == nil {
return u.SessionVersion
}
return 0