authkit/service_authz.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

128 lines
3.7 KiB
Go

package authkit
import (
"context"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// AssignRole assigns roleSlug to userID. Idempotent — a duplicate insert
// is a no-op via ON CONFLICT.
func (a *Auth) AssignRole(ctx context.Context, userID uuid.UUID, roleSlug string) error {
const op = "authkit.Auth.AssignRole"
r, err := a.storeGetRoleBySlug(ctx, roleSlug)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeAssignRoleToUser(ctx, userID, r.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RemoveRole removes roleSlug from userID. Idempotent on missing
// assignments.
func (a *Auth) RemoveRole(ctx context.Context, userID uuid.UUID, roleSlug string) error {
const op = "authkit.Auth.RemoveRole"
r, err := a.storeGetRoleBySlug(ctx, roleSlug)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeRemoveRoleFromUser(ctx, userID, r.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// UserRoles returns the role slugs assigned to a user.
func (a *Auth) UserRoles(ctx context.Context, userID uuid.UUID) ([]string, error) {
const op = "authkit.Auth.UserRoles"
roles, err := a.storeGetUserRoles(ctx, userID)
if err != nil {
return nil, errx.Wrap(op, err)
}
out := make([]string, len(roles))
for i, r := range roles {
out[i] = r.Slug
}
return out, nil
}
// HasRole reports whether the user holds the named role.
func (a *Auth) HasRole(ctx context.Context, userID uuid.UUID, slug string) (bool, error) {
const op = "authkit.Auth.HasRole"
ok, err := a.storeHasAnyRole(ctx, userID, []string{slug})
if err != nil {
return false, errx.Wrap(op, err)
}
return ok, nil
}
// HasAnyRole reports whether the user holds at least one of the named roles.
func (a *Auth) HasAnyRole(ctx context.Context, userID uuid.UUID, slugs []string) (bool, error) {
const op = "authkit.Auth.HasAnyRole"
ok, err := a.storeHasAnyRole(ctx, userID, slugs)
if err != nil {
return false, errx.Wrap(op, err)
}
return ok, nil
}
// GrantPermissionToUser adds a direct permission grant (not through any
// role). Idempotent.
func (a *Auth) GrantPermissionToUser(ctx context.Context, userID uuid.UUID, permSlug string) error {
const op = "authkit.Auth.GrantPermissionToUser"
p, err := a.storeGetPermissionBySlug(ctx, permSlug)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeGrantPermissionToUser(ctx, userID, p.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RevokePermissionFromUser removes a direct permission grant.
func (a *Auth) RevokePermissionFromUser(ctx context.Context, userID uuid.UUID, permSlug string) error {
const op = "authkit.Auth.RevokePermissionFromUser"
p, err := a.storeGetPermissionBySlug(ctx, permSlug)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeRevokePermissionFromUser(ctx, userID, p.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// UserPermissions returns the union of permission slugs the user holds via
// roles and direct grants.
func (a *Auth) UserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error) {
const op = "authkit.Auth.UserPermissions"
perms, err := a.storeGetUserPermissions(ctx, userID)
if err != nil {
return nil, errx.Wrap(op, err)
}
out := make([]string, len(perms))
for i, p := range perms {
out[i] = p.Slug
}
return out, nil
}
// HasPermission reports whether the user holds the named permission, via
// any combination of role-derived and direct grants.
func (a *Auth) HasPermission(ctx context.Context, userID uuid.UUID, permSlug string) (bool, error) {
const op = "authkit.Auth.HasPermission"
perms, err := a.UserPermissions(ctx, userID)
if err != nil {
return false, errx.Wrap(op, err)
}
for _, p := range perms {
if p == permSlug {
return true, nil
}
}
return false, nil
}