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

@ -8,16 +8,20 @@ import (
)
// RequestPasswordReset mints a single-use password-reset token for the user
// behind email and returns the plaintext for the caller to deliver via email.
// Returns ErrUserNotFound when the email isn't registered (per project
// policy of distinct errors over anti-enumeration).
// behind email and returns the plaintext for delivery.
//
// Default behavior is anti-enumeration: unknown email returns ("", nil).
// Set Config.RevealUnknownEmail = true to surface ErrUserNotFound.
func (a *Auth) RequestPasswordReset(ctx context.Context, email string) (string, error) {
const op = "authkit.Auth.RequestPasswordReset"
u, err := a.deps.Users.GetUserByEmail(ctx, normalizeEmail(email))
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)
}
plaintext, hash, err := mintSecret(prefixPasswordRset, a.cfg.Random)
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixPasswordRset)
if err != nil {
return "", errx.Wrap(op, err)
}
@ -29,40 +33,37 @@ func (a *Auth) RequestPasswordReset(ctx context.Context, email string) (string,
CreatedAt: now,
ExpiresAt: now.Add(a.cfg.PasswordResetTTL),
}
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
}
// ConfirmPasswordReset consumes the reset token, sets the new password,
// bumps the user's session_version, and revokes outstanding sessions so the
// reset constitutes a global logout.
// bumps session_version, and revokes outstanding sessions so the reset is
// a global logout.
func (a *Auth) ConfirmPasswordReset(ctx context.Context, plaintextToken, newPassword string) error {
const op = "authkit.Auth.ConfirmPasswordReset"
hash, ok := parseSecret(prefixPasswordRset, plaintextToken)
hash, ok := ParseOpaqueSecret(prefixPasswordRset, plaintextToken)
if !ok {
return errx.Wrap(op, ErrTokenInvalid)
}
now := a.now()
t, err := a.deps.Tokens.ConsumeToken(ctx, TokenPasswordReset, hash, now)
t, err := a.storeConsumeToken(ctx, TokenPasswordReset, hash, now)
if err != nil {
return errx.Wrap(op, err)
}
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, t.UserID, newHash); err != nil {
if errors.Is(err, ErrUserNotFound) {
return errx.Wrap(op, ErrUserNotFound)
}
if err := a.storeSetPassword(ctx, t.UserID, newHash); err != nil {
return errx.Wrap(op, err)
}
if _, err := a.deps.Users.BumpSessionVersion(ctx, t.UserID); err != nil {
if _, err := a.storeBumpSessionVersion(ctx, t.UserID); err != nil {
return errx.Wrap(op, err)
}
if err := a.deps.Sessions.DeleteUserSessions(ctx, t.UserID); err != nil {
if err := a.storeDeleteUserSessions(ctx, t.UserID); err != nil {
return errx.Wrap(op, err)
}
return nil