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:
parent
7f1db871bc
commit
d3c5367492
80 changed files with 5605 additions and 4565 deletions
89
testdb_test.go
Normal file
89
testdb_test.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package authkit
|
||||
|
||||
// Integration test infrastructure. Skipped when AUTHKIT_TEST_DATABASE_URL is
|
||||
// unset so the unit-test suite remains usable without a database.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.juancwu.dev/juancwu/authkit/hasher"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// noIP returns the zero-value netip.Addr — used by tests that don't care
|
||||
// about the originating IP.
|
||||
func noIP() netip.Addr { return netip.Addr{} }
|
||||
|
||||
func dbURL(t *testing.T) string {
|
||||
t.Helper()
|
||||
url := os.Getenv("AUTHKIT_TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("AUTHKIT_TEST_DATABASE_URL not set; skipping integration test")
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
// freshAuth returns a fully-initialized *Auth bound to a clean database.
|
||||
// All authkit_* tables are dropped before Migrate runs, so each test sees
|
||||
// an empty schema.
|
||||
func freshAuth(t *testing.T) *Auth {
|
||||
t.Helper()
|
||||
url := dbURL(t)
|
||||
db, err := sql.Open("pgx", url)
|
||||
if err != nil {
|
||||
t.Fatalf("sql.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
if err := db.PingContext(context.Background()); err != nil {
|
||||
t.Fatalf("ping: %v", err)
|
||||
}
|
||||
|
||||
dropAllAuthkitTables(t, db, DefaultSchema())
|
||||
t.Cleanup(func() { dropAllAuthkitTables(t, db, DefaultSchema()) })
|
||||
|
||||
a, err := New(context.Background(), Deps{
|
||||
DB: db,
|
||||
Hasher: hasher.NewArgon2id(hasher.DefaultArgon2idParams(), nil),
|
||||
}, Config{
|
||||
JWTSecret: []byte("integration-secret-thirty-two!!!"),
|
||||
JWTIssuer: "authkit-int",
|
||||
AccessTokenTTL: 2 * time.Minute,
|
||||
RefreshTokenTTL: time.Hour,
|
||||
SessionIdleTTL: time.Hour,
|
||||
SessionAbsoluteTTL: 24 * time.Hour,
|
||||
EmailVerifyTTL: time.Hour,
|
||||
PasswordResetTTL: time.Hour,
|
||||
MagicLinkTTL: time.Minute,
|
||||
EmailOTPTTL: time.Minute,
|
||||
EmailOTPMaxAttempts: 3,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("authkit.New: %v", err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func dropAllAuthkitTables(t *testing.T, db *sql.DB, s Schema) {
|
||||
t.Helper()
|
||||
tables := []string{
|
||||
s.Tables.ServiceKeyAbilities, s.Tables.UserPermissions,
|
||||
s.Tables.UserRoles, s.Tables.RolePermissions,
|
||||
s.Tables.ServiceKeys, s.Tables.Abilities,
|
||||
s.Tables.Roles, s.Tables.Permissions,
|
||||
s.Tables.Tokens, s.Tables.Sessions, s.Tables.Users,
|
||||
s.Tables.SchemaMigrations,
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
for _, name := range tables {
|
||||
_, _ = db.ExecContext(ctx,
|
||||
fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE", name))
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue