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
|
|
@ -14,7 +14,7 @@ import (
|
|||
// 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 := mintSecret(prefixSession, a.cfg.Random)
|
||||
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixSession)
|
||||
if err != nil {
|
||||
return "", nil, errx.Wrap(op, err)
|
||||
}
|
||||
|
|
@ -32,38 +32,35 @@ func (a *Auth) IssueSession(ctx context.Context, userID uuid.UUID, userAgent str
|
|||
LastSeenAt: now,
|
||||
ExpiresAt: expires,
|
||||
}
|
||||
if err := a.deps.Sessions.CreateSession(ctx, s); err != nil {
|
||||
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. Expired or
|
||||
// unknown sessions return ErrSessionInvalid.
|
||||
// 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 := parseSecret(prefixSession, plaintext)
|
||||
hash, ok := ParseOpaqueSecret(prefixSession, plaintext)
|
||||
if !ok {
|
||||
return nil, errx.Wrap(op, ErrSessionInvalid)
|
||||
}
|
||||
s, err := a.deps.Sessions.GetSession(ctx, hash)
|
||||
s, err := a.storeGetSession(ctx, hash)
|
||||
if err != nil {
|
||||
return nil, errx.Wrap(op, err)
|
||||
}
|
||||
now := a.now()
|
||||
if !s.ExpiresAt.After(now) {
|
||||
_ = a.deps.Sessions.DeleteSession(ctx, hash)
|
||||
_ = a.storeDeleteSession(ctx, hash)
|
||||
return nil, errx.Wrap(op, ErrSessionInvalid)
|
||||
}
|
||||
|
||||
// Slide the idle TTL, capped at created_at + AbsoluteTTL so an active
|
||||
// session still expires at the absolute boundary.
|
||||
newExpires := now.Add(a.cfg.SessionIdleTTL)
|
||||
if cap := s.CreatedAt.Add(a.cfg.SessionAbsoluteTTL); newExpires.After(cap) {
|
||||
newExpires = cap
|
||||
}
|
||||
if err := a.deps.Sessions.TouchSession(ctx, hash, now, newExpires); err != nil {
|
||||
if err := a.storeTouchSession(ctx, hash, now, newExpires); err != nil {
|
||||
return nil, errx.Wrap(op, err)
|
||||
}
|
||||
|
||||
|
|
@ -82,73 +79,85 @@ func (a *Auth) AuthenticateSession(ctx context.Context, plaintext string) (*Prin
|
|||
}, nil
|
||||
}
|
||||
|
||||
// RevokeSession deletes a single session by its plaintext id. Idempotent:
|
||||
// missing sessions are not an error (logout twice should not 500).
|
||||
// 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 := parseSecret(prefixSession, plaintext)
|
||||
hash, ok := ParseOpaqueSecret(prefixSession, plaintext)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if err := a.deps.Sessions.DeleteSession(ctx, hash); err != 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
|
||||
// the user's session_version (invalidating outstanding JWT access tokens).
|
||||
// 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.deps.Sessions.DeleteUserSessions(ctx, userID); err != nil {
|
||||
if err := a.storeDeleteUserSessions(ctx, userID); err != nil {
|
||||
return errx.Wrap(op, err)
|
||||
}
|
||||
if _, err := a.deps.Users.BumpSessionVersion(ctx, userID); err != nil {
|
||||
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; pass the matching ExpiresAt from the
|
||||
// returned *Session as `expires`. To clear a cookie at logout, pass an empty
|
||||
// plaintext and a past expiry.
|
||||
// plaintext returned by IssueSession and the matching ExpiresAt from the
|
||||
// returned *Session.
|
||||
func (a *Auth) SessionCookie(plaintext string, expires time.Time) *http.Cookie {
|
||||
c := &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,
|
||||
Secure: *a.cfg.SessionCookieSecure,
|
||||
HttpOnly: *a.cfg.SessionCookieHTTPOnly,
|
||||
SameSite: a.cfg.SessionCookieSameSite,
|
||||
Expires: expires,
|
||||
}
|
||||
if plaintext == "" {
|
||||
c.MaxAge = -1
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// resolveRolesAndPermissions fetches the user's role names and the union of
|
||||
// their permission names. Both are returned as flat string slices for cheap
|
||||
// containment checks on the Principal.
|
||||
func (a *Auth) resolveRolesAndPermissions(ctx context.Context, userID uuid.UUID) ([]string, []string, error) {
|
||||
roles, err := a.deps.Roles.GetUserRoles(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
// 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,
|
||||
}
|
||||
perms, err := a.deps.Permissions.GetUserPermissions(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
rNames := make([]string, len(roles))
|
||||
for i, r := range roles {
|
||||
rNames[i] = r.Name
|
||||
}
|
||||
pNames := make([]string, len(perms))
|
||||
for i, p := range perms {
|
||||
pNames[i] = p.Name
|
||||
}
|
||||
return rNames, pNames, nil
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue