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

163 lines
4.8 KiB
Go

package authkit
import (
"context"
"net/http"
"net/netip"
"time"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// IssueSession mints an opaque session ID, persists the session record, and
// returns the plaintext (for the cookie) plus the stored Session.
func (a *Auth) IssueSession(ctx context.Context, userID uuid.UUID, userAgent string, ip netip.Addr) (string, *Session, error) {
const op = "authkit.Auth.IssueSession"
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixSession)
if err != nil {
return "", nil, errx.Wrap(op, err)
}
now := a.now()
expires := now.Add(a.cfg.SessionIdleTTL)
if cap := now.Add(a.cfg.SessionAbsoluteTTL); expires.After(cap) {
expires = cap
}
s := &Session{
IDHash: hash,
UserID: userID,
UserAgent: userAgent,
IP: ip,
CreatedAt: now,
LastSeenAt: now,
ExpiresAt: expires,
}
if err := a.storeCreateSession(ctx, s); err != nil {
return "", nil, errx.Wrap(op, err)
}
return plaintext, s, nil
}
// AuthenticateSession validates an opaque session string, slides the TTL,
// resolves the user's roles+permissions, and returns a Principal.
func (a *Auth) AuthenticateSession(ctx context.Context, plaintext string) (*Principal, error) {
const op = "authkit.Auth.AuthenticateSession"
hash, ok := ParseOpaqueSecret(prefixSession, plaintext)
if !ok {
return nil, errx.Wrap(op, ErrSessionInvalid)
}
s, err := a.storeGetSession(ctx, hash)
if err != nil {
return nil, errx.Wrap(op, err)
}
now := a.now()
if !s.ExpiresAt.After(now) {
_ = a.storeDeleteSession(ctx, hash)
return nil, errx.Wrap(op, ErrSessionInvalid)
}
newExpires := now.Add(a.cfg.SessionIdleTTL)
if cap := s.CreatedAt.Add(a.cfg.SessionAbsoluteTTL); newExpires.After(cap) {
newExpires = cap
}
if err := a.storeTouchSession(ctx, hash, now, newExpires); err != nil {
return nil, errx.Wrap(op, err)
}
roles, perms, err := a.resolveRolesAndPermissions(ctx, s.UserID)
if err != nil {
return nil, errx.Wrap(op, err)
}
return &Principal{
UserID: s.UserID,
Method: AuthMethodSession,
SessionID: hash,
Roles: roles,
Permissions: perms,
IssuedAt: s.CreatedAt,
ExpiresAt: newExpires,
}, nil
}
// RevokeSession deletes a single session by its plaintext id. Idempotent —
// missing sessions are not an error.
func (a *Auth) RevokeSession(ctx context.Context, plaintext string) error {
const op = "authkit.Auth.RevokeSession"
hash, ok := ParseOpaqueSecret(prefixSession, plaintext)
if !ok {
return nil
}
if err := a.storeDeleteSession(ctx, hash); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RevokeAllUserSessions kills every active session for the user and bumps
// session_version (invalidating outstanding JWT access tokens).
func (a *Auth) RevokeAllUserSessions(ctx context.Context, userID uuid.UUID) error {
const op = "authkit.Auth.RevokeAllUserSessions"
if err := a.storeDeleteUserSessions(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
if _, err := a.storeBumpSessionVersion(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// SessionCookie builds an *http.Cookie pre-configured from Config. Pass the
// plaintext returned by IssueSession and the matching ExpiresAt from the
// returned *Session.
func (a *Auth) SessionCookie(plaintext string, expires time.Time) *http.Cookie {
return &http.Cookie{
Name: a.cfg.SessionCookieName,
Value: plaintext,
Path: a.cfg.SessionCookiePath,
Domain: a.cfg.SessionCookieDomain,
Secure: *a.cfg.SessionCookieSecure,
HttpOnly: *a.cfg.SessionCookieHTTPOnly,
SameSite: a.cfg.SessionCookieSameSite,
Expires: expires,
}
}
// ClearSessionCookie returns a cookie that, when set on the response, tells
// the browser to delete the session cookie. Use on logout.
func (a *Auth) ClearSessionCookie() *http.Cookie {
return &http.Cookie{
Name: a.cfg.SessionCookieName,
Value: "",
Path: a.cfg.SessionCookiePath,
Domain: a.cfg.SessionCookieDomain,
Secure: *a.cfg.SessionCookieSecure,
HttpOnly: *a.cfg.SessionCookieHTTPOnly,
SameSite: a.cfg.SessionCookieSameSite,
MaxAge: -1,
}
}
// SessionCookieName returns the configured cookie name. Useful for callers
// wiring extractors without reaching into Config.
func (a *Auth) SessionCookieName() string { return a.cfg.SessionCookieName }
// resolveRolesAndPermissions fetches the user's role and permission slugs.
func (a *Auth) resolveRolesAndPermissions(ctx context.Context, userID uuid.UUID) ([]string, []string, error) {
roles, err := a.storeGetUserRoles(ctx, userID)
if err != nil {
return nil, nil, err
}
perms, err := a.storeGetUserPermissions(ctx, userID)
if err != nil {
return nil, nil, err
}
rSlugs := make([]string, len(roles))
for i, r := range roles {
rSlugs[i] = r.Slug
}
pSlugs := make([]string, len(perms))
for i, p := range perms {
pSlugs[i] = p.Slug
}
return rSlugs, pSlugs, nil
}