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
273 lines
9.1 KiB
Go
273 lines
9.1 KiB
Go
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")
|
|
}
|
|
}
|