package service import ( "context" "errors" "strings" "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, "a@example.com", "Alice", "password123") if !first.IsAdmin { t.Error("first user should be admin") } second := mustRegister(t, s, "b@example.com", "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, "Alice@Example.com", "Alice", "password123") // Stored normalized (lowercased). u, err := s.store.GetUserByEmail(context.Background(), "alice@example.com") if err != nil { t.Fatalf("lookup normalized email: %v", err) } if u.Email != "alice@example.com" { t.Errorf("stored email = %q, want lowercased", u.Email) } // A different-cased duplicate is rejected. _, err = s.Register(context.Background(), RegisterInput{Email: "ALICE@example.com", 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, "admin@example.com", "Admin", "password123") if !first.IsAdmin { t.Error("bootstrap user should be admin") } // Subsequent signups are blocked. _, err := s.Register(context.Background(), RegisterInput{Email: "b@example.com", DisplayName: "Bob", Password: "password123"}) if !errors.Is(err, domain.ErrRegistrationClosed) { t.Errorf("closed register err = %v, want ErrRegistrationClosed", err) } } func TestRejectsOverlongPassword(t *testing.T) { s := newTestService(t, openConfig()) long := strings.Repeat("a", maxPasswordLen+1) if _, err := s.Register(context.Background(), RegisterInput{Email: "a@example.com", DisplayName: "A", Password: long}); !errors.Is(err, domain.ErrInvalidInput) { t.Errorf("register overlong err = %v, want ErrInvalidInput", err) } mustRegister(t, s, "b@example.com", "Bob", "password123") if _, err := s.Login(context.Background(), "b@example.com", long); !errors.Is(err, domain.ErrInvalidCredentials) { t.Errorf("login overlong err = %v, want ErrInvalidCredentials", err) } } func TestLocalAuthDisabledRejectsRegisterAndLogin(t *testing.T) { cfg := openConfig() cfg.LocalAuth = false s := newTestService(t, cfg) if _, err := s.Register(context.Background(), RegisterInput{Email: "a@example.com", DisplayName: "A", Password: "password123"}); !errors.Is(err, domain.ErrLocalAuthDisabled) { t.Errorf("register err = %v, want ErrLocalAuthDisabled", err) } if _, err := s.Login(context.Background(), "a@example.com", "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, "a@example.com", "Alice", "correct-horse") // Correct credentials (case-insensitive email). u, err := s.Login(context.Background(), "A@example.com", "correct-horse") if err != nil { t.Fatalf("login correct: %v", err) } if u.Email != "a@example.com" { t.Errorf("logged-in user = %q", u.Email) } // Wrong password and unknown email both yield the same sentinel. if _, err := s.Login(context.Background(), "a@example.com", "wrong"); !errors.Is(err, domain.ErrInvalidCredentials) { t.Errorf("wrong-password err = %v, want ErrInvalidCredentials", err) } if _, err := s.Login(context.Background(), "nobody@example.com", "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: "oidc@example.com", DisplayName: "O", OIDCIssuer: &iss, OIDCSubject: &sub, }, true); err != nil { t.Fatalf("seed oidc user: %v", err) } if _, err := s.Login(context.Background(), "oidc@example.com", "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, "a@example.com", "Alice", "password123") token, _, err := s.CreateSession(context.Background(), u.ID) if err != nil { t.Fatalf("CreateSession: %v", err) } got, exp, 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) } if !exp.After(s.now()) { t.Errorf("resolved expiry %v is not in the future", exp) } // 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, "a@example.com", "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, "a@example.com", "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) } _, resolvedExp, err := s.ResolveSession(context.Background(), token) if err != nil { t.Fatalf("ResolveSession: %v", err) } if !resolvedExp.After(firstExp) { t.Errorf("returned expiry did not slide: %v not after %v", resolvedExp, firstExp) } 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, "a@example.com", "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) { // No OIDC configured → local only. s := newTestService(t, openConfig()) p := s.Providers() if !p.Local || p.OIDC { t.Errorf("providers = %+v, want local=true oidc=false", p) } // OIDC configured with a base URL → reported ready. ready := openConfig() ready.BaseURL = "https://pansy.example.com" ready.OIDC = config.OIDCConfig{Issuer: testOIDCIssuer, ClientID: "cid", ButtonLabel: "Sign in with Authentik"} if got := newTestService(t, ready).Providers(); !got.OIDC || got.OIDCLabel != "Sign in with Authentik" { t.Errorf("providers = %+v, want oidc=true with Authentik label", got) } // OIDC configured but no base URL → not ready (can't build a redirect URI). noBase := openConfig() noBase.OIDC = config.OIDCConfig{Issuer: "https://idp.example", ClientID: "cid"} if got := newTestService(t, noBase).Providers(); got.OIDC { t.Error("OIDC should be false without a base URL") } } // testOIDCIssuer is the issuer URL used across the OIDC service tests. const testOIDCIssuer = "https://idp.example" func oidcIdentity(sub, email, name string, verified bool) OIDCIdentity { return OIDCIdentity{Issuer: testOIDCIssuer, Subject: sub, Email: email, EmailVerified: verified, Name: name} } func TestLoginOIDCJITProvisionsThenReturnsSameUser(t *testing.T) { s := newTestService(t, openConfig()) u, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-1", "alice@example.com", "Alice", true)) if err != nil { t.Fatalf("LoginOIDC create: %v", err) } if !u.IsAdmin { t.Error("first provisioned OIDC user should be admin") } if u.OIDCSubject == nil || *u.OIDCSubject != "sub-1" { t.Errorf("oidc subject not stamped: %+v", u.OIDCSubject) } // A second login with the same identity returns the same user (no duplicate). again, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-1", "alice@example.com", "Alice", true)) if err != nil { t.Fatalf("LoginOIDC repeat: %v", err) } if again.ID != u.ID { t.Errorf("repeat login made a new user: %d vs %d", again.ID, u.ID) } } func TestLoginOIDCLinksExistingLocalAccount(t *testing.T) { s := newTestService(t, openConfig()) local := mustRegister(t, s, "bob@example.com", "Bob", "password123") linked, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-2", "Bob@Example.com", "Bob", true)) if err != nil { t.Fatalf("LoginOIDC link: %v", err) } if linked.ID != local.ID { t.Errorf("linked to a new user %d, want existing %d", linked.ID, local.ID) } if linked.OIDCSubject == nil || *linked.OIDCSubject != "sub-2" { t.Error("existing account was not stamped with the oidc identity") } // Local password still works after linking (one account, two methods). if _, err := s.Login(context.Background(), "bob@example.com", "password123"); err != nil { t.Errorf("local login after linking failed: %v", err) } } func TestLoginOIDCRefusesUnverifiedEmail(t *testing.T) { s := newTestService(t, openConfig()) // Unverified email colliding with an existing account is refused (takeover). mustRegister(t, s, "carol@example.com", "Carol", "password123") if _, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-3", "carol@example.com", "Carol", false)); !errors.Is(err, domain.ErrOIDCEmailUnverified) { t.Errorf("unverified collision err = %v, want ErrOIDCEmailUnverified", err) } // Unverified email with NO collision is also refused (can't JIT-provision on // an unverified email — it could squat an address a real user later owns, and // could make an unverified identity the first admin). if _, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-3b", "fresh@example.com", "Fresh", false)); !errors.Is(err, domain.ErrOIDCEmailUnverified) { t.Errorf("unverified JIT err = %v, want ErrOIDCEmailUnverified", err) } } func TestLoginOIDCRefusesOverwritingDifferentIdentity(t *testing.T) { s := newTestService(t, openConfig()) // A user links identity A. first, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-A", "dana@example.com", "Dana", true)) if err != nil { t.Fatalf("initial link: %v", err) } // A different identity asserting the same verified email must NOT overwrite // the stored identity (that would hijack/lock out the account). _, err = s.LoginOIDC(context.Background(), oidcIdentity("sub-B", "dana@example.com", "Dana", true)) if !errors.Is(err, domain.ErrOIDCIdentityConflict) { t.Fatalf("overwrite attempt err = %v, want ErrOIDCIdentityConflict", err) } // The original identity still works and still points at the same account. again, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-A", "dana@example.com", "Dana", true)) if err != nil || again.ID != first.ID { t.Errorf("original identity broken: user=%v err=%v", again, err) } if again.OIDCSubject == nil || *again.OIDCSubject != "sub-A" { t.Errorf("stored identity was overwritten: %v", again.OIDCSubject) } } func TestLoginOIDCRequiresEmail(t *testing.T) { s := newTestService(t, openConfig()) _, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-4", "", "No Email", true)) if !errors.Is(err, domain.ErrOIDCNoEmail) { t.Errorf("no-email err = %v, want ErrOIDCNoEmail", err) } } func TestLoginOIDCFallsBackToEmailLocalPartForName(t *testing.T) { s := newTestService(t, openConfig()) u, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-5", "dave@example.com", "", true)) if err != nil { t.Fatalf("LoginOIDC: %v", err) } if u.DisplayName != "dave" { t.Errorf("display name = %q, want %q", u.DisplayName, "dave") } } func TestLocalAuthDisabledDoesNotBlockOIDC(t *testing.T) { cfg := openConfig() cfg.LocalAuth = false s := newTestService(t, cfg) // OIDC provisioning must work even when local auth is off (pure-Authentik). if _, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-6", "erin@example.com", "Erin", true)); err != nil { t.Errorf("LoginOIDC with local auth disabled: %v", err) } }