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

109
cmd/abilities/main.go Normal file
View file

@ -0,0 +1,109 @@
// Command abilities is the seeding CLI for service-token abilities.
//
// abilities create <slug> [--label "..."]
// abilities list
// abilities delete <slug>
package main
import (
"context"
"errors"
"fmt"
"os"
"git.juancwu.dev/juancwu/authkit/cmd/internal/clihelp"
)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
sub := os.Args[1]
args := os.Args[2:]
switch sub {
case "create":
runCreate(args)
case "list":
runList(args)
case "delete", "rm":
runDelete(args)
case "-h", "--help", "help":
usage()
default:
fmt.Fprintf(os.Stderr, "unknown subcommand %q\n\n", sub)
usage()
os.Exit(2)
}
}
func usage() {
fmt.Fprintln(os.Stderr, `usage: abilities <subcommand> [args]
Subcommands:
create <slug> [--label "..."] create an ability
list list every ability
delete <slug> delete an ability
Common flags:
--dsn PostgreSQL DSN (defaults to $AUTHKIT_DATABASE_URL)`)
}
func runCreate(args []string) {
fs, dsn := clihelp.DSNFlag("abilities create")
label := fs.String("label", "", "optional human label")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("create takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
ab, err := a.CreateAbility(ctx, rest[0], *label)
if err != nil {
clihelp.Fail(err)
}
fmt.Printf("created ability %s (id=%s, label=%q)\n", ab.Slug, ab.ID, ab.Label)
}
func runList(args []string) {
fs, dsn := clihelp.DSNFlag("abilities list")
_ = fs.Parse(args)
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
abilities, err := a.ListAbilities(ctx)
if err != nil {
clihelp.Fail(err)
}
for _, ab := range abilities {
fmt.Printf("%s\t%s\n", ab.Slug, ab.Label)
}
}
func runDelete(args []string) {
fs, dsn := clihelp.DSNFlag("abilities delete")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("delete takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
if err := a.DeleteAbility(ctx, rest[0]); err != nil {
clihelp.Fail(err)
}
fmt.Printf("deleted ability %s\n", rest[0])
}

View file

@ -0,0 +1,70 @@
// Package clihelp is a small helper used by the cmd/perms, cmd/roles, and
// cmd/abilities seeding CLIs to dial Postgres, build an *authkit.Auth, and
// share argument-parsing scaffolding.
package clihelp
import (
"context"
"database/sql"
"errors"
"flag"
"fmt"
"os"
"git.juancwu.dev/juancwu/authkit"
"git.juancwu.dev/juancwu/authkit/hasher"
_ "github.com/jackc/pgx/v5/stdlib"
)
// DSNFlag returns a flag.FlagSet pre-populated with --dsn. Callers add their
// own flags and call Parse on it.
func DSNFlag(name string) (*flag.FlagSet, *string) {
fs := flag.NewFlagSet(name, flag.ExitOnError)
dsn := fs.String("dsn", "", "PostgreSQL DSN (defaults to $AUTHKIT_DATABASE_URL)")
return fs, dsn
}
// Dial opens a database connection using either the supplied DSN or the
// AUTHKIT_DATABASE_URL env var, then constructs an *authkit.Auth ready to
// run seed operations. Migrations and schema verification both run as part
// of New.
//
// The CLIs never sign JWTs or hash passwords, but Auth.New requires a JWT
// secret and a hasher — we supply a dummy secret and the default Argon2id
// hasher so the constructor passes.
func Dial(ctx context.Context, dsn string) (*authkit.Auth, *sql.DB, error) {
if dsn == "" {
dsn = os.Getenv("AUTHKIT_DATABASE_URL")
}
if dsn == "" {
return nil, nil, errors.New("no DSN: pass --dsn or set AUTHKIT_DATABASE_URL")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, nil, fmt.Errorf("sql.Open: %w", err)
}
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, nil, fmt.Errorf("ping: %w", err)
}
a, err := authkit.New(ctx, authkit.Deps{
DB: db,
Hasher: hasher.NewArgon2id(hasher.DefaultArgon2idParams(), nil),
}, authkit.Config{
// JWT secret is unused by seed flows but required by New.
JWTSecret: []byte("authkit-cli-not-used-for-anything-real"),
})
if err != nil {
_ = db.Close()
return nil, nil, err
}
return a, db, nil
}
// Fail prints err to stderr and exits with status 1. Used by every CLI's
// top-level dispatch.
func Fail(err error) {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}

114
cmd/perms/main.go Normal file
View file

@ -0,0 +1,114 @@
// Command perms is the seeding CLI for authkit permissions.
//
// perms create <slug> [--label "..."]
// perms list
// perms delete <slug>
//
// Database connection comes from --dsn or $AUTHKIT_DATABASE_URL.
package main
import (
"context"
"errors"
"fmt"
"os"
"git.juancwu.dev/juancwu/authkit/cmd/internal/clihelp"
)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
sub := os.Args[1]
args := os.Args[2:]
switch sub {
case "create":
runCreate(args)
case "list":
runList(args)
case "delete", "rm":
runDelete(args)
case "-h", "--help", "help":
usage()
default:
fmt.Fprintf(os.Stderr, "unknown subcommand %q\n\n", sub)
usage()
os.Exit(2)
}
}
func usage() {
fmt.Fprintln(os.Stderr, `usage: perms <subcommand> [args]
Subcommands:
create <slug> [--label "..."] create a permission
list list every permission
delete <slug> delete a permission
Common flags:
--dsn PostgreSQL DSN (defaults to $AUTHKIT_DATABASE_URL)`)
}
func runCreate(args []string) {
fs, dsn := clihelp.DSNFlag("perms create")
label := fs.String("label", "", "optional human label")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("create takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
p, err := a.CreatePermission(ctx, rest[0], *label)
if err != nil {
clihelp.Fail(err)
}
fmt.Printf("created permission %s (id=%s, label=%q)\n", p.Slug, p.ID, p.Label)
}
func runList(args []string) {
fs, dsn := clihelp.DSNFlag("perms list")
_ = fs.Parse(args)
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
perms, err := a.ListPermissions(ctx)
if err != nil {
clihelp.Fail(err)
}
for _, p := range perms {
fmt.Printf("%s\t%s\n", p.Slug, p.Label)
}
}
func runDelete(args []string) {
fs, dsn := clihelp.DSNFlag("perms delete")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("delete takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
if err := a.DeletePermission(ctx, rest[0]); err != nil {
clihelp.Fail(err)
}
fmt.Printf("deleted permission %s\n", rest[0])
}

182
cmd/roles/main.go Normal file
View file

@ -0,0 +1,182 @@
// Command roles is the seeding CLI for authkit roles, plus role↔permission
// linking.
//
// roles create <slug> [--label "..."]
// roles list
// roles delete <slug>
// roles grant <role-slug> <perm-slug>
// roles revoke <role-slug> <perm-slug>
// roles permissions <role-slug>
package main
import (
"context"
"errors"
"fmt"
"os"
"git.juancwu.dev/juancwu/authkit/cmd/internal/clihelp"
)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
sub := os.Args[1]
args := os.Args[2:]
switch sub {
case "create":
runCreate(args)
case "list":
runList(args)
case "delete", "rm":
runDelete(args)
case "grant":
runGrant(args)
case "revoke":
runRevoke(args)
case "permissions", "perms":
runPermissions(args)
case "-h", "--help", "help":
usage()
default:
fmt.Fprintf(os.Stderr, "unknown subcommand %q\n\n", sub)
usage()
os.Exit(2)
}
}
func usage() {
fmt.Fprintln(os.Stderr, `usage: roles <subcommand> [args]
Subcommands:
create <slug> [--label "..."] create a role
list list every role
delete <slug> delete a role
grant <role-slug> <perm-slug> grant a permission to a role
revoke <role-slug> <perm-slug> revoke a permission from a role
permissions <role-slug> list permissions granted to a role
Common flags:
--dsn PostgreSQL DSN (defaults to $AUTHKIT_DATABASE_URL)`)
}
func runCreate(args []string) {
fs, dsn := clihelp.DSNFlag("roles create")
label := fs.String("label", "", "optional human label")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("create takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
r, err := a.CreateRole(ctx, rest[0], *label)
if err != nil {
clihelp.Fail(err)
}
fmt.Printf("created role %s (id=%s, label=%q)\n", r.Slug, r.ID, r.Label)
}
func runList(args []string) {
fs, dsn := clihelp.DSNFlag("roles list")
_ = fs.Parse(args)
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
roles, err := a.ListRoles(ctx)
if err != nil {
clihelp.Fail(err)
}
for _, r := range roles {
fmt.Printf("%s\t%s\n", r.Slug, r.Label)
}
}
func runDelete(args []string) {
fs, dsn := clihelp.DSNFlag("roles delete")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("delete takes exactly one slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
if err := a.DeleteRole(ctx, rest[0]); err != nil {
clihelp.Fail(err)
}
fmt.Printf("deleted role %s\n", rest[0])
}
func runGrant(args []string) {
fs, dsn := clihelp.DSNFlag("roles grant")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 2 {
clihelp.Fail(errors.New("grant takes <role-slug> <perm-slug>"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
if err := a.GrantPermissionToRole(ctx, rest[0], rest[1]); err != nil {
clihelp.Fail(err)
}
fmt.Printf("granted %s to role %s\n", rest[1], rest[0])
}
func runRevoke(args []string) {
fs, dsn := clihelp.DSNFlag("roles revoke")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 2 {
clihelp.Fail(errors.New("revoke takes <role-slug> <perm-slug>"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
if err := a.RevokePermissionFromRole(ctx, rest[0], rest[1]); err != nil {
clihelp.Fail(err)
}
fmt.Printf("revoked %s from role %s\n", rest[1], rest[0])
}
func runPermissions(args []string) {
fs, dsn := clihelp.DSNFlag("roles permissions")
_ = fs.Parse(args)
rest := fs.Args()
if len(rest) != 1 {
clihelp.Fail(errors.New("permissions takes exactly one role-slug argument"))
}
ctx := context.Background()
a, db, err := clihelp.Dial(ctx, *dsn)
if err != nil {
clihelp.Fail(err)
}
defer db.Close()
perms, err := a.ListRolePermissions(ctx, rest[0])
if err != nil {
clihelp.Fail(err)
}
for _, p := range perms {
fmt.Printf("%s\t%s\n", p.Slug, p.Label)
}
}