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

86
extractor_test.go Normal file
View file

@ -0,0 +1,86 @@
package authkit
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestBearerExtractor(t *testing.T) {
ex := BearerExtractor()
cases := []struct {
name string
header string
want string
ok bool
}{
{"plain bearer", "Bearer abc", "abc", true},
{"lowercase bearer", "bearer abc", "abc", true},
{"mixed case", "BeArEr abc", "abc", true},
{"no header", "", "", false},
{"non-bearer scheme", "Basic abc", "", false},
{"bearer with no token", "Bearer ", "", false},
{"bearer with whitespace", "Bearer abc ", "abc", true},
{"too short", "Bearer", "", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
if c.header != "" {
r.Header.Set("Authorization", c.header)
}
got, ok := ex(r)
if ok != c.ok || got != c.want {
t.Fatalf("got (%q, %v), want (%q, %v)", got, ok, c.want, c.ok)
}
})
}
}
func TestCookieExtractor(t *testing.T) {
ex := CookieExtractor("session")
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.AddCookie(&http.Cookie{Name: "session", Value: "abc"})
got, ok := ex(r)
if !ok || got != "abc" {
t.Fatalf("got (%q, %v), want (\"abc\", true)", got, ok)
}
r2 := httptest.NewRequest(http.MethodGet, "/", nil)
if _, ok := ex(r2); ok {
t.Fatalf("missing cookie should not extract")
}
r3 := httptest.NewRequest(http.MethodGet, "/", nil)
r3.AddCookie(&http.Cookie{Name: "session", Value: ""})
if _, ok := ex(r3); ok {
t.Fatalf("empty cookie value should not extract")
}
}
func TestHeaderExtractor(t *testing.T) {
ex := HeaderExtractor("X-API-Token")
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set("X-API-Token", " abc ")
got, ok := ex(r)
if !ok || got != "abc" {
t.Fatalf("got (%q, %v), want (\"abc\", true)", got, ok)
}
}
func TestChainExtractors(t *testing.T) {
a := func(r *http.Request) (string, bool) { return "", false }
b := func(r *http.Request) (string, bool) { return "from-b", true }
c := func(r *http.Request) (string, bool) { return "from-c", true }
chain := ChainExtractors(a, b, c)
r := httptest.NewRequest(http.MethodGet, "/", nil)
got, ok := chain(r)
if !ok || got != "from-b" {
t.Fatalf("chain should return first hit; got (%q, %v)", got, ok)
}
none := ChainExtractors(a, a)
if _, ok := none(r); ok {
t.Fatalf("chain of misses should not extract")
}
}