authkit/service_service_key.go
juancwu d3c5367492 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>
2026-04-26 23:27:30 +00:00

116 lines
3.5 KiB
Go

package authkit
import (
"context"
"errors"
"time"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// 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)
}
now := a.now()
k := &ServiceKey{
IDHash: hash,
Name: params.Name,
Abilities: resolved,
CreatedAt: now,
}
if params.TTL != nil {
exp := now.Add(*params.TTL)
k.ExpiresAt = &exp
}
if err := a.storeCreateServiceKey(ctx, k, abilityIDs); err != nil {
return "", nil, errx.Wrap(op, err)
}
return plaintext, k, nil
}
// 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.storeGetServiceKey(ctx, hash)
if err != nil {
return nil, errx.Wrap(op, err)
}
now := a.now()
if k.RevokedAt != nil {
return nil, errx.Wrap(op, ErrServiceKeyInvalid)
}
if k.ExpiresAt != nil && !k.ExpiresAt.After(now) {
return nil, errx.Wrap(op, ErrServiceKeyInvalid)
}
_ = a.storeTouchServiceKey(ctx, hash, now)
return k, nil
}
// RevokeServiceKey marks a service token revoked. Idempotent on
// already-revoked keys.
func (a *Auth) RevokeServiceKey(ctx context.Context, plaintext string) error {
const op = "authkit.Auth.RevokeServiceKey"
hash, ok := ParseOpaqueSecret(prefixServiceKey, plaintext)
if !ok {
return errx.Wrap(op, ErrServiceKeyInvalid)
}
if err := a.storeRevokeServiceKey(ctx, hash, a.now()); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// 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.storeListServiceKeys(ctx)
if err != nil {
return nil, errx.Wrap(op, err)
}
return out, nil
}