Implements pansy's local (email + password) authentication and the session layer that OIDC (#5) will also reuse. - store: users.go (create/get-by-id/get-by-email/count) and sessions.go (create/get/touch/delete/delete-expired), scanning the existing 0001 schema. - service: the business-logic seam. auth.go (Register/Login/session lifecycle/Providers) + password.go (argon2id, 64 MiB/1/4, PHC-encoded, constant-time verify) + service.go (Service, clock injection, token hashing). First user is admin; closed registration still allows the bootstrap user; unknown-email and wrong-password are indistinguishable (same error, same argon2 work via a dummy hash). - api: POST /auth/register|login|logout, GET /auth/me|providers, plus a requireAuth middleware that resolves the HttpOnly session cookie (SameSite=Lax, Secure under https) to the actor. Handlers stay thin. - main: wires the service and a periodic expired-session sweep; sessions are also dropped lazily on access. Sliding 30-day expiry. - tests: service (register/login/expiry/renewal/cleanup, password) and api (cookie flow, middleware, validation, providers). Verified end-to-end via curl: register -> me -> restart -> session persists -> logout -> 401. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
77 lines
2.8 KiB
Go
77 lines
2.8 KiB
Go
// Package service is pansy's business-logic seam: every operation is a method on
|
|
// *Service taking (ctx, actor, args), and all permission checks and invariants
|
|
// live here rather than in the HTTP handlers. REST handlers (internal/api) and,
|
|
// later, agent tools (internal/agent) are thin adapters over these methods, so
|
|
// both inherit the same rules. This file holds the shared plumbing; feature
|
|
// methods live alongside it (auth.go, and gardens/objects/… in later issues).
|
|
package service
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/store"
|
|
)
|
|
|
|
// timeLayout is the ISO-8601 UTC format used for every timestamp pansy stores.
|
|
// It matches the schema's strftime('%Y-%m-%dT%H:%M:%SZ') so string comparison
|
|
// (e.g. session expiry) is equivalent to time comparison.
|
|
const timeLayout = "2006-01-02T15:04:05Z"
|
|
|
|
// sessionTTL is how long a session lives from its last use (sliding expiry).
|
|
const sessionTTL = 30 * 24 * time.Hour
|
|
|
|
// Service holds the dependencies shared by every operation.
|
|
type Service struct {
|
|
store *store.DB
|
|
cfg *config.Config
|
|
// now is the clock, injectable so tests can advance time (session expiry).
|
|
now func() time.Time
|
|
// dummyHash is a valid argon2id hash of a throwaway password. Login verifies
|
|
// against it when an email is unknown so the response time doesn't reveal
|
|
// whether an account exists.
|
|
dummyHash string
|
|
}
|
|
|
|
// New constructs a Service. It precomputes a dummy password hash used to
|
|
// equalize login timing; if that fails (it shouldn't), login still works but
|
|
// loses the timing defense.
|
|
func New(st *store.DB, cfg *config.Config) *Service {
|
|
s := &Service{store: st, cfg: cfg, now: time.Now}
|
|
if h, err := hashPassword("pansy-timing-equalizer-not-a-real-password"); err != nil {
|
|
slog.Warn("service: could not precompute login timing hash", "error", err)
|
|
} else {
|
|
s.dummyHash = h
|
|
}
|
|
return s
|
|
}
|
|
|
|
// formatTime renders a time as pansy's canonical UTC string.
|
|
func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) }
|
|
|
|
// parseTime parses a canonical pansy timestamp.
|
|
func parseTime(s string) (time.Time, error) { return time.Parse(timeLayout, s) }
|
|
|
|
// newSessionToken returns a fresh URL-safe random bearer token (32 bytes of
|
|
// entropy). The raw token goes in the cookie; only its hash is persisted.
|
|
func newSessionToken() (string, error) {
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", fmt.Errorf("service: generate session token: %w", err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
|
}
|
|
|
|
// hashToken maps a raw bearer token to the hex sha256 stored as the session's
|
|
// primary key.
|
|
func hashToken(raw string) string {
|
|
sum := sha256.Sum256([]byte(raw))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|