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
|
|
@ -2,183 +2,123 @@ package authkit
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestServiceKeyRoundtrip(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
appID := uuid.New()
|
||||
plaintext, k, err := a.IssueServiceKey(context.Background(),
|
||||
"application", appID, "events-ingest",
|
||||
[]string{"events:write", "events:read"}, nil)
|
||||
func TestIntegration_ServiceKeyRoundtrip(t *testing.T) {
|
||||
a := freshAuth(t)
|
||||
ctx := context.Background()
|
||||
if _, err := a.CreateAbility(ctx, "events:write", "Write events"); err != nil {
|
||||
t.Fatalf("CreateAbility events:write: %v", err)
|
||||
}
|
||||
if _, err := a.CreateAbility(ctx, "events:read", "Read events"); err != nil {
|
||||
t.Fatalf("CreateAbility events:read: %v", err)
|
||||
}
|
||||
|
||||
plain, k, err := a.IssueServiceKey(ctx, IssueServiceKeyParams{
|
||||
Name: "events-ingest",
|
||||
Abilities: []string{"events:write", "events:read"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
if plaintext == "" || k == nil {
|
||||
t.Fatalf("missing plaintext or key")
|
||||
if !strings.HasPrefix(plain, "sk_") {
|
||||
t.Fatalf("plaintext should start with sk_: %q", plain)
|
||||
}
|
||||
got, err := a.AuthenticateServiceKey(context.Background(), plaintext)
|
||||
if k.Name != "events-ingest" {
|
||||
t.Fatalf("name mismatch: %q", k.Name)
|
||||
}
|
||||
if len(k.Abilities) != 2 {
|
||||
t.Fatalf("expected 2 abilities, got %v", k.Abilities)
|
||||
}
|
||||
|
||||
got, err := a.AuthenticateServiceKey(ctx, plain)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthenticateServiceKey: %v", err)
|
||||
}
|
||||
if got.OwnerKind != "application" || got.OwnerID != appID {
|
||||
t.Fatalf("owner mismatch: kind=%q id=%v", got.OwnerKind, got.OwnerID)
|
||||
}
|
||||
if got.Name != "events-ingest" {
|
||||
t.Fatalf("name mismatch: %q", got.Name)
|
||||
}
|
||||
if len(got.Abilities) != 2 || got.Abilities[0] != "events:write" || got.Abilities[1] != "events:read" {
|
||||
t.Fatalf("abilities mismatch: %+v", got.Abilities)
|
||||
}
|
||||
got.Abilities[0] = "tampered"
|
||||
again, err := a.AuthenticateServiceKey(context.Background(), plaintext)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthenticateServiceKey (re-auth): %v", err)
|
||||
}
|
||||
if again.Abilities[0] != "events:write" {
|
||||
t.Fatalf("returned slice was not deep-copied; saw mutation: %+v", again.Abilities)
|
||||
if !got.HasAbility("events:write") || !got.HasAbility("events:read") {
|
||||
t.Fatalf("missing expected abilities: %+v", got.Abilities)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyPlaintextShape(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
plaintext, _, err := a.IssueServiceKey(context.Background(),
|
||||
"application", uuid.New(), "name", nil, nil)
|
||||
func TestIntegration_ServiceKeyRejectsUnknownAbility(t *testing.T) {
|
||||
a := freshAuth(t)
|
||||
ctx := context.Background()
|
||||
_, _, err := a.IssueServiceKey(ctx, IssueServiceKeyParams{
|
||||
Name: "x",
|
||||
Abilities: []string{"never-registered"},
|
||||
})
|
||||
if !errors.Is(err, ErrAbilityNotFound) {
|
||||
t.Fatalf("expected ErrAbilityNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegration_ServiceKeyRevoke(t *testing.T) {
|
||||
a := freshAuth(t)
|
||||
ctx := context.Background()
|
||||
if _, err := a.CreateAbility(ctx, "ops", ""); err != nil {
|
||||
t.Fatalf("CreateAbility: %v", err)
|
||||
}
|
||||
plain, _, err := a.IssueServiceKey(ctx, IssueServiceKeyParams{
|
||||
Name: "ci",
|
||||
Abilities: []string{"ops"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(plaintext, "sk_") {
|
||||
t.Fatalf("plaintext missing sk_ prefix: %q", plaintext)
|
||||
}
|
||||
body := strings.TrimPrefix(plaintext, "sk_")
|
||||
raw, err := base64.RawURLEncoding.DecodeString(body)
|
||||
if err != nil {
|
||||
t.Fatalf("base64 decode: %v", err)
|
||||
}
|
||||
if len(raw) != 32 {
|
||||
t.Fatalf("body decoded to %d bytes, want 32", len(raw))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyWrongPrefix(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
_, err := a.AuthenticateServiceKey(context.Background(), "ak_not-a-service-key")
|
||||
if !errors.Is(err, ErrServiceKeyInvalid) {
|
||||
t.Fatalf("expected ErrServiceKeyInvalid for wrong prefix, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyAfterRevoke(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
plaintext, _, err := a.IssueServiceKey(context.Background(),
|
||||
"application", uuid.New(), "ci", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
if err := a.RevokeServiceKey(context.Background(), plaintext); err != nil {
|
||||
if err := a.RevokeServiceKey(ctx, plain); err != nil {
|
||||
t.Fatalf("RevokeServiceKey: %v", err)
|
||||
}
|
||||
if _, err := a.AuthenticateServiceKey(context.Background(), plaintext); !errors.Is(err, ErrServiceKeyInvalid) {
|
||||
if _, err := a.AuthenticateServiceKey(ctx, plain); !errors.Is(err, ErrServiceKeyInvalid) {
|
||||
t.Fatalf("expected ErrServiceKeyInvalid post-revoke, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyAfterExpiry(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
func TestIntegration_ServiceKeyExpiry(t *testing.T) {
|
||||
a := freshAuth(t)
|
||||
ctx := context.Background()
|
||||
if _, err := a.CreateAbility(ctx, "ops", ""); err != nil {
|
||||
t.Fatalf("CreateAbility: %v", err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
a.cfg.Clock = func() time.Time { return now }
|
||||
ttl := time.Minute
|
||||
plaintext, _, err := a.IssueServiceKey(context.Background(),
|
||||
"application", uuid.New(), "ephemeral", nil, &ttl)
|
||||
plain, _, err := a.IssueServiceKey(ctx, IssueServiceKeyParams{
|
||||
Name: "ephemeral",
|
||||
Abilities: []string{"ops"},
|
||||
TTL: &ttl,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
a.cfg.Clock = func() time.Time { return now.Add(2 * time.Minute) }
|
||||
if _, err := a.AuthenticateServiceKey(context.Background(), plaintext); !errors.Is(err, ErrServiceKeyInvalid) {
|
||||
if _, err := a.AuthenticateServiceKey(ctx, plain); !errors.Is(err, ErrServiceKeyInvalid) {
|
||||
t.Fatalf("expected ErrServiceKeyInvalid post-expiry, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyListByOwner(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
appA := uuid.New()
|
||||
appB := uuid.New()
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, _, err := a.IssueServiceKey(context.Background(), "application", appA, "k", nil, nil); err != nil {
|
||||
t.Fatalf("Issue appA #%d: %v", i, err)
|
||||
func TestIntegration_ServiceKeyList(t *testing.T) {
|
||||
a := freshAuth(t)
|
||||
ctx := context.Background()
|
||||
if _, err := a.CreateAbility(ctx, "ops", ""); err != nil {
|
||||
t.Fatalf("CreateAbility: %v", err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, _, err := a.IssueServiceKey(ctx, IssueServiceKeyParams{
|
||||
Name: "k",
|
||||
Abilities: []string{"ops"},
|
||||
}); err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
}
|
||||
if _, _, err := a.IssueServiceKey(context.Background(), "application", appB, "k", nil, nil); err != nil {
|
||||
t.Fatalf("Issue appB: %v", err)
|
||||
}
|
||||
gotA, err := a.ListServiceKeys(context.Background(), "application", appA)
|
||||
out, err := a.ListServiceKeys(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListServiceKeys appA: %v", err)
|
||||
t.Fatalf("ListServiceKeys: %v", err)
|
||||
}
|
||||
if len(gotA) != 2 {
|
||||
t.Fatalf("ListServiceKeys appA = %d keys, want 2", len(gotA))
|
||||
}
|
||||
gotB, err := a.ListServiceKeys(context.Background(), "application", appB)
|
||||
if err != nil {
|
||||
t.Fatalf("ListServiceKeys appB: %v", err)
|
||||
}
|
||||
if len(gotB) != 1 {
|
||||
t.Fatalf("ListServiceKeys appB = %d keys, want 1", len(gotB))
|
||||
}
|
||||
gotTenantA, err := a.ListServiceKeys(context.Background(), "tenant", appA)
|
||||
if err != nil {
|
||||
t.Fatalf("ListServiceKeys tenant/appA: %v", err)
|
||||
}
|
||||
if len(gotTenantA) != 0 {
|
||||
t.Fatalf("ListServiceKeys tenant/appA = %d, want 0 (different owner_kind)", len(gotTenantA))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyHasAbility(t *testing.T) {
|
||||
k := &ServiceKey{Abilities: []string{"events:write", "events:read"}}
|
||||
if !k.HasAbility("events:write") {
|
||||
t.Fatalf("expected HasAbility(events:write) = true")
|
||||
}
|
||||
if !k.HasAbility("events:read") {
|
||||
t.Fatalf("expected HasAbility(events:read) = true")
|
||||
}
|
||||
if k.HasAbility("admin:nuke") {
|
||||
t.Fatalf("expected HasAbility(admin:nuke) = false")
|
||||
}
|
||||
empty := &ServiceKey{}
|
||||
if empty.HasAbility("anything") {
|
||||
t.Fatalf("HasAbility on empty Abilities must be false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceKeyTouchUpdatesLastUsedAt(t *testing.T) {
|
||||
a := newTestAuth(t)
|
||||
appID := uuid.New()
|
||||
plaintext, _, err := a.IssueServiceKey(context.Background(), "application", appID, "k", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueServiceKey: %v", err)
|
||||
}
|
||||
keys, err := a.ListServiceKeys(context.Background(), "application", appID)
|
||||
if err != nil || len(keys) != 1 {
|
||||
t.Fatalf("pre-touch list: err=%v len=%d", err, len(keys))
|
||||
}
|
||||
if keys[0].LastUsedAt != nil {
|
||||
t.Fatalf("expected LastUsedAt=nil before authenticate, got %v", *keys[0].LastUsedAt)
|
||||
}
|
||||
if _, err := a.AuthenticateServiceKey(context.Background(), plaintext); err != nil {
|
||||
t.Fatalf("AuthenticateServiceKey: %v", err)
|
||||
}
|
||||
keys, err = a.ListServiceKeys(context.Background(), "application", appID)
|
||||
if err != nil || len(keys) != 1 {
|
||||
t.Fatalf("post-touch list: err=%v len=%d", err, len(keys))
|
||||
}
|
||||
if keys[0].LastUsedAt == nil {
|
||||
t.Fatalf("expected LastUsedAt to be set after authenticate")
|
||||
if len(out) != 3 {
|
||||
t.Fatalf("expected 3 keys, got %d", len(out))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue