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

@ -2,19 +2,50 @@ package authkit
import (
"context"
"errors"
"time"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// IssueServiceKey mints a fresh owner-agnostic service token. ownerKind is a
// consumer-defined namespace label (e.g. "application", "tenant") and ownerID
// is the owning entity's id; authkit makes no assumption about either. The
// plaintext is returned (show-once) and the SHA-256 lookup hash is stored.
// Pass ttl=nil for a non-expiring key.
func (a *Auth) IssueServiceKey(ctx context.Context, ownerKind string, ownerID uuid.UUID, name string, abilities []string, ttl *time.Duration) (string, *ServiceKey, error) {
// IssueServiceKeyParams is the input shape for IssueServiceKey. Abilities
// are slugs that must already exist in authkit_abilities — issue fails with
// ErrAbilityNotFound if any slug is unknown. TTL is optional; nil means
// non-expiring.
type IssueServiceKeyParams struct {
Name string
Abilities []string
TTL *time.Duration
}
// IssueServiceKey mints a fresh service token. Plaintext is returned exactly
// once (show-once); only the SHA-256 hash is persisted. Each ability slug is
// resolved to its row before insertion, so the service key carries a
// well-defined set of abilities even after later slug renames or deletes.
func (a *Auth) IssueServiceKey(ctx context.Context, params IssueServiceKeyParams) (string, *ServiceKey, error) {
const op = "authkit.Auth.IssueServiceKey"
if params.Name == "" {
return "", nil, errx.New(op, "Name is required")
}
abilityIDs := make([]uuid.UUID, 0, len(params.Abilities))
resolved := make([]string, 0, len(params.Abilities))
seen := map[string]struct{}{}
for _, slug := range params.Abilities {
if _, dup := seen[slug]; dup {
continue
}
seen[slug] = struct{}{}
ab, err := a.storeGetAbilityBySlug(ctx, slug)
if err != nil {
if errors.Is(err, ErrAbilityNotFound) {
return "", nil, errx.Wrapf(op, ErrAbilityNotFound, "ability %q is not registered", slug)
}
return "", nil, errx.Wrap(op, err)
}
abilityIDs = append(abilityIDs, ab.ID)
resolved = append(resolved, ab.Slug)
}
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixServiceKey)
if err != nil {
return "", nil, errx.Wrap(op, err)
@ -22,34 +53,29 @@ func (a *Auth) IssueServiceKey(ctx context.Context, ownerKind string, ownerID uu
now := a.now()
k := &ServiceKey{
IDHash: hash,
OwnerID: ownerID,
OwnerKind: ownerKind,
Name: name,
Abilities: append([]string(nil), abilities...),
Name: params.Name,
Abilities: resolved,
CreatedAt: now,
}
if ttl != nil {
exp := now.Add(*ttl)
if params.TTL != nil {
exp := now.Add(*params.TTL)
k.ExpiresAt = &exp
}
if err := a.deps.ServiceKeys.CreateServiceKey(ctx, k); err != nil {
if err := a.storeCreateServiceKey(ctx, k, abilityIDs); err != nil {
return "", nil, errx.Wrap(op, err)
}
return plaintext, k, nil
}
// AuthenticateServiceKey validates a service token, touches last_used_at
// (best-effort), and returns the stored *ServiceKey. Unlike API keys, no
// Principal is returned — service tokens have no owning user, so the
// Principal abstraction does not fit. Consumers needing a Principal can
// build one from the returned key.
// AuthenticateServiceKey validates a service token and returns the stored
// *ServiceKey with its abilities resolved.
func (a *Auth) AuthenticateServiceKey(ctx context.Context, plaintext string) (*ServiceKey, error) {
const op = "authkit.Auth.AuthenticateServiceKey"
hash, ok := ParseOpaqueSecret(prefixServiceKey, plaintext)
if !ok {
return nil, errx.Wrap(op, ErrServiceKeyInvalid)
}
k, err := a.deps.ServiceKeys.GetServiceKey(ctx, hash)
k, err := a.storeGetServiceKey(ctx, hash)
if err != nil {
return nil, errx.Wrap(op, err)
}
@ -60,10 +86,8 @@ func (a *Auth) AuthenticateServiceKey(ctx context.Context, plaintext string) (*S
if k.ExpiresAt != nil && !k.ExpiresAt.After(now) {
return nil, errx.Wrap(op, ErrServiceKeyInvalid)
}
_ = a.deps.ServiceKeys.TouchServiceKey(ctx, hash, now)
out := *k
out.Abilities = append([]string(nil), k.Abilities...)
return &out, nil
_ = a.storeTouchServiceKey(ctx, hash, now)
return k, nil
}
// RevokeServiceKey marks a service token revoked. Idempotent on
@ -74,17 +98,17 @@ func (a *Auth) RevokeServiceKey(ctx context.Context, plaintext string) error {
if !ok {
return errx.Wrap(op, ErrServiceKeyInvalid)
}
if err := a.deps.ServiceKeys.RevokeServiceKey(ctx, hash, a.now()); err != nil {
if err := a.storeRevokeServiceKey(ctx, hash, a.now()); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// ListServiceKeys returns every service token issued for the given
// (ownerKind, ownerID) pair, including revoked and expired keys.
func (a *Auth) ListServiceKeys(ctx context.Context, ownerKind string, ownerID uuid.UUID) ([]*ServiceKey, error) {
// ListServiceKeys returns every service token, including revoked and
// expired ones, ordered by creation time descending.
func (a *Auth) ListServiceKeys(ctx context.Context) ([]*ServiceKey, error) {
const op = "authkit.Auth.ListServiceKeys"
out, err := a.deps.ServiceKeys.ListServiceKeysByOwner(ctx, ownerKind, ownerID)
out, err := a.storeListServiceKeys(ctx)
if err != nil {
return nil, errx.Wrap(op, err)
}