Add local auth: users, sessions, register/login/logout/me (#4)
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
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
)
|
||||
|
||||
// RegisterInput is the payload for local self-service signup.
|
||||
type RegisterInput struct {
|
||||
Email string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
// Providers reports which login methods the server offers, so the login page
|
||||
// (#6) can render the right controls. OIDCLabel is only meaningful when OIDC is
|
||||
// true.
|
||||
type Providers struct {
|
||||
Local bool `json:"local"`
|
||||
OIDC bool `json:"oidc"`
|
||||
OIDCLabel string `json:"oidcLabel"`
|
||||
}
|
||||
|
||||
// Providers returns the enabled auth methods. OIDC is always false until #5
|
||||
// wires the endpoints; advertising it before then would point the UI at routes
|
||||
// that don't exist.
|
||||
func (s *Service) Providers() Providers {
|
||||
return Providers{
|
||||
Local: s.cfg.LocalAuth,
|
||||
OIDC: false,
|
||||
OIDCLabel: s.cfg.OIDC.ButtonLabel,
|
||||
}
|
||||
}
|
||||
|
||||
// Register creates a local (password) account and returns it. The first user on
|
||||
// a fresh instance becomes admin and may always register (bootstrap), even when
|
||||
// PANSY_REGISTRATION=closed; afterward, closed registration is enforced.
|
||||
func (s *Service) Register(ctx context.Context, in RegisterInput) (*domain.User, error) {
|
||||
if !s.cfg.LocalAuth {
|
||||
return nil, domain.ErrLocalAuthDisabled
|
||||
}
|
||||
|
||||
email := normalizeEmail(in.Email)
|
||||
displayName := strings.TrimSpace(in.DisplayName)
|
||||
if email == "" || displayName == "" || in.Password == "" {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
count, err := s.store.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Closed registration still allows the very first account so a locked-down
|
||||
// instance can be bootstrapped without editing config.
|
||||
if count > 0 && !s.cfg.RegistrationOpen() {
|
||||
return nil, domain.ErrRegistrationClosed
|
||||
}
|
||||
|
||||
// Friendly duplicate check. The UNIQUE index is the real guard against a
|
||||
// race; that path surfaces as a generic insert error (500), acceptable at
|
||||
// household scale.
|
||||
if _, err := s.store.GetUserByEmail(ctx, email); err == nil {
|
||||
return nil, domain.ErrEmailTaken
|
||||
} else if !errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hash, err := hashPassword(in.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.store.CreateUser(ctx, &domain.User{
|
||||
Email: email,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: &hash,
|
||||
IsAdmin: count == 0,
|
||||
})
|
||||
}
|
||||
|
||||
// Login verifies an email/password pair and returns the user. Unknown-email and
|
||||
// wrong-password both return domain.ErrInvalidCredentials, and both spend the
|
||||
// same argon2 work, so neither the error nor the timing reveals which failed.
|
||||
func (s *Service) Login(ctx context.Context, email, password string) (*domain.User, error) {
|
||||
if !s.cfg.LocalAuth {
|
||||
return nil, domain.ErrLocalAuthDisabled
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByEmail(ctx, normalizeEmail(email))
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
// Spend comparable time so timing can't distinguish a missing account.
|
||||
_, _ = verifyPassword(s.dummyHash, password)
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case u.PasswordHash == nil:
|
||||
// OIDC-only account: no local password to check, but equalize timing.
|
||||
_, _ = verifyPassword(s.dummyHash, password)
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
}
|
||||
|
||||
ok, err := verifyPassword(*u.PasswordHash, password)
|
||||
if err != nil || !ok {
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// CreateSession issues a new session for a user and returns the raw bearer token
|
||||
// (to place in the cookie) and its expiry.
|
||||
func (s *Service) CreateSession(ctx context.Context, userID int64) (token string, expiresAt time.Time, err error) {
|
||||
raw, err := newSessionToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
exp := s.now().Add(sessionTTL)
|
||||
if err := s.store.CreateSession(ctx, &domain.Session{
|
||||
TokenHash: hashToken(raw),
|
||||
UserID: userID,
|
||||
ExpiresAt: formatTime(exp),
|
||||
}); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return raw, exp, nil
|
||||
}
|
||||
|
||||
// ResolveSession validates a raw bearer token and returns its user. An expired
|
||||
// session is deleted and treated as absent (domain.ErrNotFound). A still-valid
|
||||
// session has its expiry slid forward, but only when that moves it by more than
|
||||
// an hour, so a busy client doesn't write on every request.
|
||||
func (s *Service) ResolveSession(ctx context.Context, rawToken string) (*domain.User, error) {
|
||||
if rawToken == "" {
|
||||
return nil, domain.ErrNotFound
|
||||
}
|
||||
hash := hashToken(rawToken)
|
||||
sess, err := s.store.GetSession(ctx, hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exp, err := parseTime(sess.ExpiresAt)
|
||||
if err != nil {
|
||||
// A corrupt expiry means we can't trust the session; drop it.
|
||||
_ = s.store.DeleteSession(ctx, hash)
|
||||
return nil, domain.ErrNotFound
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
if !now.Before(exp) {
|
||||
_ = s.store.DeleteSession(ctx, hash)
|
||||
return nil, domain.ErrNotFound
|
||||
}
|
||||
|
||||
if newExp := now.Add(sessionTTL); newExp.Sub(exp) > time.Hour {
|
||||
_ = s.store.TouchSession(ctx, hash, formatTime(newExp))
|
||||
}
|
||||
|
||||
return s.store.GetUserByID(ctx, sess.UserID)
|
||||
}
|
||||
|
||||
// Logout deletes the session behind a raw bearer token. It is idempotent.
|
||||
func (s *Service) Logout(ctx context.Context, rawToken string) error {
|
||||
if rawToken == "" {
|
||||
return nil
|
||||
}
|
||||
return s.store.DeleteSession(ctx, hashToken(rawToken))
|
||||
}
|
||||
|
||||
// CleanupExpiredSessions deletes all sessions that have passed their expiry and
|
||||
// returns the count. Called periodically; expired sessions are also dropped
|
||||
// lazily on access by ResolveSession.
|
||||
func (s *Service) CleanupExpiredSessions(ctx context.Context) (int64, error) {
|
||||
return s.store.DeleteExpiredSessions(ctx, formatTime(s.now()))
|
||||
}
|
||||
|
||||
// normalizeEmail trims and lowercases an email for consistent storage and
|
||||
// lookup. (The users.email column is also NOCASE, so lookups are robust either
|
||||
// way; normalizing keeps stored values tidy.)
|
||||
func normalizeEmail(email string) string {
|
||||
return strings.ToLower(strings.TrimSpace(email))
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/store"
|
||||
)
|
||||
|
||||
// newTestService builds a Service over a fresh in-memory database.
|
||||
func newTestService(t *testing.T, cfg *config.Config) *Service {
|
||||
t.Helper()
|
||||
db, err := store.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("store.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
if err := db.Migrate(context.Background()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return New(db, cfg)
|
||||
}
|
||||
|
||||
func openConfig() *config.Config {
|
||||
return &config.Config{Registration: config.RegistrationOpen, LocalAuth: true}
|
||||
}
|
||||
|
||||
func mustRegister(t *testing.T, s *Service, email, name, pw string) *domain.User {
|
||||
t.Helper()
|
||||
u, err := s.Register(context.Background(), RegisterInput{Email: email, DisplayName: name, Password: pw})
|
||||
if err != nil {
|
||||
t.Fatalf("Register(%s): %v", email, err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func TestRegisterFirstUserIsAdmin(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
|
||||
first := mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
if !first.IsAdmin {
|
||||
t.Error("first user should be admin")
|
||||
}
|
||||
|
||||
second := mustRegister(t, s, "[email protected]", "Bob", "password123")
|
||||
if second.IsAdmin {
|
||||
t.Error("second user should not be admin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterNormalizesAndRejectsDuplicateEmail(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
|
||||
// Stored normalized (lowercased).
|
||||
u, err := s.store.GetUserByEmail(context.Background(), "[email protected]")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup normalized email: %v", err)
|
||||
}
|
||||
if u.Email != "[email protected]" {
|
||||
t.Errorf("stored email = %q, want lowercased", u.Email)
|
||||
}
|
||||
|
||||
// A different-cased duplicate is rejected.
|
||||
_, err = s.Register(context.Background(), RegisterInput{Email: "[email protected]", DisplayName: "A2", Password: "password123"})
|
||||
if !errors.Is(err, domain.ErrEmailTaken) {
|
||||
t.Errorf("duplicate register err = %v, want ErrEmailTaken", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterRejectsBlankFields(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
_, err := s.Register(context.Background(), RegisterInput{Email: " ", DisplayName: "", Password: ""})
|
||||
if !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("blank register err = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationClosedAllowsBootstrapThenBlocks(t *testing.T) {
|
||||
cfg := openConfig()
|
||||
cfg.Registration = config.RegistrationClosed
|
||||
s := newTestService(t, cfg)
|
||||
|
||||
// The very first user may register even when closed (bootstrap).
|
||||
first := mustRegister(t, s, "[email protected]", "Admin", "password123")
|
||||
if !first.IsAdmin {
|
||||
t.Error("bootstrap user should be admin")
|
||||
}
|
||||
|
||||
// Subsequent signups are blocked.
|
||||
_, err := s.Register(context.Background(), RegisterInput{Email: "[email protected]", DisplayName: "Bob", Password: "password123"})
|
||||
if !errors.Is(err, domain.ErrRegistrationClosed) {
|
||||
t.Errorf("closed register err = %v, want ErrRegistrationClosed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalAuthDisabledRejectsRegisterAndLogin(t *testing.T) {
|
||||
cfg := openConfig()
|
||||
cfg.LocalAuth = false
|
||||
s := newTestService(t, cfg)
|
||||
|
||||
if _, err := s.Register(context.Background(), RegisterInput{Email: "[email protected]", DisplayName: "A", Password: "password123"}); !errors.Is(err, domain.ErrLocalAuthDisabled) {
|
||||
t.Errorf("register err = %v, want ErrLocalAuthDisabled", err)
|
||||
}
|
||||
if _, err := s.Login(context.Background(), "[email protected]", "password123"); !errors.Is(err, domain.ErrLocalAuthDisabled) {
|
||||
t.Errorf("login err = %v, want ErrLocalAuthDisabled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSucceedsAndFailsIndistinguishably(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
mustRegister(t, s, "[email protected]", "Alice", "correct-horse")
|
||||
|
||||
// Correct credentials (case-insensitive email).
|
||||
u, err := s.Login(context.Background(), "[email protected]", "correct-horse")
|
||||
if err != nil {
|
||||
t.Fatalf("login correct: %v", err)
|
||||
}
|
||||
if u.Email != "[email protected]" {
|
||||
t.Errorf("logged-in user = %q", u.Email)
|
||||
}
|
||||
|
||||
// Wrong password and unknown email both yield the same sentinel.
|
||||
if _, err := s.Login(context.Background(), "[email protected]", "wrong"); !errors.Is(err, domain.ErrInvalidCredentials) {
|
||||
t.Errorf("wrong-password err = %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
if _, err := s.Login(context.Background(), "[email protected]", "whatever"); !errors.Is(err, domain.ErrInvalidCredentials) {
|
||||
t.Errorf("unknown-email err = %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRejectsOIDCOnlyUser(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
// Simulate an OIDC-only account (no password hash) directly in the store.
|
||||
iss, sub := "https://idp.example", "subject-1"
|
||||
if _, err := s.store.CreateUser(context.Background(), &domain.User{
|
||||
Email: "[email protected]", DisplayName: "O", OIDCIssuer: &iss, OIDCSubject: &sub,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed oidc user: %v", err)
|
||||
}
|
||||
if _, err := s.Login(context.Background(), "[email protected]", "anything"); !errors.Is(err, domain.ErrInvalidCredentials) {
|
||||
t.Errorf("oidc-only login err = %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
u := mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
|
||||
token, _, err := s.CreateSession(context.Background(), u.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
got, err := s.ResolveSession(context.Background(), token)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveSession: %v", err)
|
||||
}
|
||||
if got.ID != u.ID {
|
||||
t.Errorf("resolved user %d, want %d", got.ID, u.ID)
|
||||
}
|
||||
|
||||
// Logout invalidates it.
|
||||
if err := s.Logout(context.Background(), token); err != nil {
|
||||
t.Fatalf("Logout: %v", err)
|
||||
}
|
||||
if _, err := s.ResolveSession(context.Background(), token); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("resolve after logout err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSessionRejectsGarbageToken(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
if _, err := s.ResolveSession(context.Background(), "not-a-real-token"); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("garbage token err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if _, err := s.ResolveSession(context.Background(), ""); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("empty token err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiryAndLazyDeletion(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
u := mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
|
||||
base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
s.now = func() time.Time { return base }
|
||||
|
||||
token, _, err := s.CreateSession(context.Background(), u.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
// Jump past the 30-day TTL: the session must be treated as gone...
|
||||
s.now = func() time.Time { return base.Add(sessionTTL + time.Hour) }
|
||||
if _, err := s.ResolveSession(context.Background(), token); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Fatalf("expired resolve err = %v, want ErrNotFound", err)
|
||||
}
|
||||
// ...and lazily deleted from the store.
|
||||
if _, err := s.store.GetSession(context.Background(), hashToken(token)); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("expired session row still present: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionSlidingRenewal(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
u := mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
|
||||
base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
s.now = func() time.Time { return base }
|
||||
token, firstExp, err := s.CreateSession(context.Background(), u.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
// Use it 10 days later; expiry should slide forward.
|
||||
s.now = func() time.Time { return base.Add(10 * 24 * time.Hour) }
|
||||
if _, err := s.ResolveSession(context.Background(), token); err != nil {
|
||||
t.Fatalf("ResolveSession: %v", err)
|
||||
}
|
||||
sess, err := s.store.GetSession(context.Background(), hashToken(token))
|
||||
if err != nil {
|
||||
t.Fatalf("GetSession: %v", err)
|
||||
}
|
||||
newExp, err := parseTime(sess.ExpiresAt)
|
||||
if err != nil {
|
||||
t.Fatalf("parse expiry: %v", err)
|
||||
}
|
||||
if !newExp.After(firstExp) {
|
||||
t.Errorf("expiry did not slide: new %v not after first %v", newExp, firstExp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupExpiredSessions(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
u := mustRegister(t, s, "[email protected]", "Alice", "password123")
|
||||
|
||||
base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
s.now = func() time.Time { return base }
|
||||
if _, _, err := s.CreateSession(context.Background(), u.ID); err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
// Before expiry: nothing to clean.
|
||||
if n, err := s.CleanupExpiredSessions(context.Background()); err != nil || n != 0 {
|
||||
t.Fatalf("early cleanup = (%d, %v), want (0, nil)", n, err)
|
||||
}
|
||||
|
||||
// After expiry: the one session is purged.
|
||||
s.now = func() time.Time { return base.Add(sessionTTL + time.Hour) }
|
||||
if n, err := s.CleanupExpiredSessions(context.Background()); err != nil || n != 1 {
|
||||
t.Fatalf("late cleanup = (%d, %v), want (1, nil)", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvidersReflectsConfig(t *testing.T) {
|
||||
cfg := openConfig()
|
||||
cfg.OIDC.ButtonLabel = "Sign in with Authentik"
|
||||
s := newTestService(t, cfg)
|
||||
|
||||
p := s.Providers()
|
||||
if !p.Local {
|
||||
t.Error("expected local=true")
|
||||
}
|
||||
if p.OIDC {
|
||||
t.Error("OIDC must be false until #5 wires it")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// argon2id parameters. ~64 MiB memory / 1 pass / 4 lanes is the interactive
|
||||
// profile recommended by the argon2 authors and is comfortable on a
|
||||
// self-hosted box. They are encoded into every stored hash, so raising them
|
||||
// later leaves old hashes verifiable.
|
||||
const (
|
||||
argonMemKiB = 64 * 1024 // 64 MiB
|
||||
argonTime = 1
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// errBadHash marks a stored hash string that could not be parsed — a data or
|
||||
// programming error, not a wrong password. Callers treat it as an auth failure
|
||||
// but should log it.
|
||||
var errBadHash = errors.New("service: malformed password hash")
|
||||
|
||||
// b64 is the padding-free base64 used inside the PHC-style hash string.
|
||||
var b64 = base64.RawStdEncoding
|
||||
|
||||
// hashPassword returns a self-describing argon2id hash in the PHC string format
|
||||
// "$argon2id$v=19$m=...,t=...,p=...$salt$hash" (all base64, no padding).
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("service: generate salt: %w", err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemKiB, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemKiB, argonTime, argonThreads,
|
||||
b64.EncodeToString(salt), b64.EncodeToString(key),
|
||||
), nil
|
||||
}
|
||||
|
||||
// verifyPassword reports whether password matches the encoded argon2id hash. The
|
||||
// comparison is constant-time. A malformed encoded value returns errBadHash.
|
||||
func verifyPassword(encoded, password string) (bool, error) {
|
||||
mem, t, threads, salt, want, err := decodeHash(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, t, mem, threads, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
// decodeHash parses a PHC-format argon2id string into its parameters, salt, and
|
||||
// derived key.
|
||||
func decodeHash(encoded string) (mem, t uint32, threads uint8, salt, key []byte, err error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// ["", "argon2id", "v=19", "m=..,t=..,p=..", "<salt>", "<hash>"]
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return 0, 0, 0, nil, nil, errBadHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return 0, 0, 0, nil, nil, errBadHash
|
||||
}
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &t, &threads); err != nil {
|
||||
return 0, 0, 0, nil, nil, errBadHash
|
||||
}
|
||||
if salt, err = b64.DecodeString(parts[4]); err != nil {
|
||||
return 0, 0, 0, nil, nil, errBadHash
|
||||
}
|
||||
if key, err = b64.DecodeString(parts[5]); err != nil || len(key) == 0 {
|
||||
return 0, 0, 0, nil, nil, errBadHash
|
||||
}
|
||||
return mem, t, threads, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashAndVerifyPassword(t *testing.T) {
|
||||
hash, err := hashPassword("correct-horse-battery-staple")
|
||||
if err != nil {
|
||||
t.Fatalf("hashPassword: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(hash, "$argon2id$v=19$") {
|
||||
t.Errorf("hash %q lacks argon2id PHC prefix", hash)
|
||||
}
|
||||
|
||||
ok, err := verifyPassword(hash, "correct-horse-battery-staple")
|
||||
if err != nil || !ok {
|
||||
t.Errorf("verify correct = (%v, %v), want (true, nil)", ok, err)
|
||||
}
|
||||
|
||||
ok, err = verifyPassword(hash, "wrong-password")
|
||||
if err != nil || ok {
|
||||
t.Errorf("verify wrong = (%v, %v), want (false, nil)", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordIsSalted(t *testing.T) {
|
||||
// Two hashes of the same password must differ (random salt), yet both verify.
|
||||
h1, _ := hashPassword("same-password")
|
||||
h2, _ := hashPassword("same-password")
|
||||
if h1 == h2 {
|
||||
t.Error("two hashes of the same password are identical; salt not random")
|
||||
}
|
||||
for _, h := range []string{h1, h2} {
|
||||
if ok, err := verifyPassword(h, "same-password"); err != nil || !ok {
|
||||
t.Errorf("verify(%q) = (%v, %v), want (true, nil)", h, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRejectsMalformedHash(t *testing.T) {
|
||||
for _, bad := range []string{
|
||||
"",
|
||||
"not-a-hash",
|
||||
"$argon2id$v=19$m=65536,t=1,p=4$onlyfourparts",
|
||||
"$argon2i$v=19$m=65536,t=1,p=4$c2FsdA$aGFzaA", // wrong variant
|
||||
"$argon2id$v=1$m=65536,t=1,p=4$c2FsdA$aGFzaA", // wrong version
|
||||
} {
|
||||
if _, err := verifyPassword(bad, "whatever"); err == nil {
|
||||
t.Errorf("verifyPassword(%q) err = nil, want errBadHash", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// 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[:])
|
||||
}
|
||||
Reference in New Issue
Block a user