package identity import ( "context" "errors" "log/slog" "strings" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) type sessionTestUserRepository struct { outbound.UserRepository users map[uuid.UUID]domain.User byEmail map[string]domain.User getByEmailCalls int afterGetByEmail func() } func (repository *sessionTestUserRepository) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { user, ok := repository.users[id] if !ok { return domain.User{}, outbound.ErrUserNotFound } return user, nil } func (repository *sessionTestUserRepository) GetByEmail(_ context.Context, email domain.EmailAddress) (domain.User, error) { repository.getByEmailCalls++ user, ok := repository.byEmail[email.Normalized()] if !ok { return domain.User{}, outbound.ErrUserNotFound } if repository.afterGetByEmail != nil { repository.afterGetByEmail() } return user, nil } type sessionTestSessionRepository struct { outbound.SessionRepository active map[domain.SecretTokenHash]domain.Session created []domain.Session revoked []uuid.UUID touched []uuid.UUID } func (repository *sessionTestSessionRepository) Create(_ context.Context, session domain.Session) error { repository.active[session.TokenHash] = session repository.created = append(repository.created, session) return nil } func (repository *sessionTestSessionRepository) FindActive( _ context.Context, hash domain.SecretTokenHash, at time.Time, idleTimeout time.Duration, ) (domain.Session, error) { session, ok := repository.active[hash] if !ok || session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) { return domain.Session{}, outbound.ErrSessionNotFound } return session, nil } func (repository *sessionTestSessionRepository) Touch(_ context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error { for hash, session := range repository.active { if session.ID != id { continue } if session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) { return outbound.ErrSessionNotFound } session.LastSeenAt = at repository.active[hash] = session repository.touched = append(repository.touched, id) return nil } return outbound.ErrSessionNotFound } func (repository *sessionTestSessionRepository) Revoke(_ context.Context, id uuid.UUID, at time.Time) error { for hash, session := range repository.active { if session.ID != id { continue } if session.RevokedAt != nil { return outbound.ErrSessionNotFound } session.RevokedAt = &at repository.active[hash] = session repository.revoked = append(repository.revoked, id) return nil } return outbound.ErrSessionNotFound } type sessionTestUnit struct { outbound.UnitOfWork users outbound.UserRepository sessions outbound.SessionRepository } func (unit sessionTestUnit) Users() outbound.UserRepository { return unit.users } func (unit sessionTestUnit) Sessions() outbound.SessionRepository { return unit.sessions } type sessionTestTransactor struct{ unit outbound.UnitOfWork } func (transactor sessionTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error { return fn(ctx, transactor.unit) } type sessionTestLimiter struct { decision outbound.RateLimitDecision keys []string } func (limiter *sessionTestLimiter) Take(_ context.Context, key string, _ ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) { limiter.keys = append(limiter.keys, key) return limiter.decision, nil } type sessionTestHasher struct { verifyErr error dummyErr error verifyCalls int dummyCalls int } func (*sessionTestHasher) Hash(context.Context, domain.Password) (domain.PasswordHash, error) { return domain.NewPasswordHash(testPasswordPHC) } func (hasher *sessionTestHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) { hasher.verifyCalls++ return false, hasher.verifyErr } func (hasher *sessionTestHasher) VerifyDummy(context.Context, domain.Password) error { hasher.dummyCalls++ if hasher.dummyErr != nil { return hasher.dummyErr } return outbound.ErrPasswordMismatch } type sessionTestFixture struct { service *SessionService users *sessionTestUserRepository sessions *sessionTestSessionRepository limiter *sessionTestLimiter hasher *sessionTestHasher keyring *Keyring now time.Time } func newSessionTestFixture(t *testing.T, user domain.User, limiterDecision outbound.RateLimitDecision, verifyErr error) sessionTestFixture { t.Helper() now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) users := &sessionTestUserRepository{ users: map[uuid.UUID]domain.User{user.ID: user}, byEmail: map[string]domain.User{user.Email.Normalized(): user}, } sessions := &sessionTestSessionRepository{active: make(map[domain.SecretTokenHash]domain.Session)} unit := sessionTestUnit{users: users, sessions: sessions} transactor := sessionTestTransactor{unit: unit} limiter := &sessionTestLimiter{decision: limiterDecision} hasher := &sessionTestHasher{verifyErr: verifyErr} keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes))) if err != nil { t.Fatal(err) } service, err := NewSessionService(SessionDependencies{ Transactor: transactor, Users: users, Sessions: sessions, Credentials: NewCredentials(hasher), Limiter: limiter, Keyring: keyring, Clock: func() time.Time { return now }, Logger: slog.New(slog.NewTextHandler(&strings.Builder{}, nil)), }, SessionSettings{ ClientHourlyLimit: 30, EmailHourlyLimit: 10, IdleTimeout: 24 * time.Hour, AbsoluteLifetime: 7 * 24 * time.Hour, }) if err != nil { t.Fatal(err) } return sessionTestFixture{service: service, users: users, sessions: sessions, limiter: limiter, hasher: hasher, keyring: keyring, now: now} } func sessionTestUser(t *testing.T, address string, verified bool, at time.Time) domain.User { t.Helper() email, err := domain.NewEmailAddress(address) if err != nil { t.Fatal(err) } hash, err := domain.NewPasswordHash(testPasswordPHC) if err != nil { t.Fatal(err) } user, err := domain.NewUser(domain.Registration{ Email: email, PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: at, }) if err != nil { t.Fatal(err) } if verified { verifiedAt := at user.EmailVerifiedAt = &verifiedAt } return user } func TestSessionServiceLoginRotatesIncomingSessionAtomically(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) user := sessionTestUser(t, "person@example.com", true, now) fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) incoming, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } old, err := domain.NewSession(domain.NewSessionInput{ UserID: user.ID, TokenHash: incoming.Hash(), StartedAt: now.Add(-time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour, }) if err != nil { t.Fatal(err) } fixture.sessions.active[old.TokenHash] = old result, err := fixture.service.Login(context.Background(), LoginCommand{ Email: "PERSON@example.com", Password: "correct horse battery staple", ClientKey: "client-address", Incoming: incoming, }) if err != nil { t.Fatalf("Login() error = %v", err) } if len(fixture.sessions.created) != 1 || len(fixture.sessions.revoked) != 1 || fixture.sessions.revoked[0] != old.ID { t.Fatalf("rotation created %d sessions and revoked %v", len(fixture.sessions.created), fixture.sessions.revoked) } if result.Session.TokenHash == incoming.Hash() || result.Session.UserID != user.ID || !result.Session.ExpiresAt.Equal(now.Add(7*24*time.Hour)) { t.Fatalf("new session = %+v, want a fresh token for the verified user with the configured deadline", result.Session) } if result.Token.Hash() != result.Session.TokenHash || !fixture.keyring.VerifySessionCSRF(result.Token, result.CSRFToken) { t.Fatal("login result did not bind the cookie token, database hash, and CSRF token") } if fixture.hasher.verifyCalls != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-address") || fixture.limiter.keys[1] != fixture.keyring.EmailBucket(user.Email.Normalized()) { t.Fatalf("login checks: hash calls=%d, limiter keys=%v", fixture.hasher.verifyCalls, fixture.limiter.keys) } } func TestSessionServiceLoginKeepsUnknownAndWrongCredentialsIndistinguishable(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) for _, test := range []struct { name string user *domain.User verifyErr error wantDummy int }{ {name: "unknown account", wantDummy: 1}, {name: "wrong password", verifyErr: outbound.ErrPasswordMismatch}, } { t.Run(test.name, func(t *testing.T) { var user domain.User if test.user != nil { user = *test.user } else if test.verifyErr != nil { user = sessionTestUser(t, "person@example.com", true, now) } fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, test.verifyErr) _, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "not the password"}) if !errors.Is(err, ErrInvalidCredentials) || fixture.hasher.dummyCalls != test.wantDummy || len(fixture.sessions.created) != 0 { t.Fatalf("Login() error=%v dummy=%d sessions=%d", err, fixture.hasher.dummyCalls, len(fixture.sessions.created)) } }) } } func TestSessionServiceLoginDoesNotCreateOrRotateForUnverifiedAccount(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) user := sessionTestUser(t, "pending@example.com", false, now) fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) incoming, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } old, err := domain.NewSession(domain.NewSessionInput{ UserID: user.ID, TokenHash: incoming.Hash(), StartedAt: now.Add(-time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour, }) if err != nil { t.Fatal(err) } fixture.sessions.active[old.TokenHash] = old _, err = fixture.service.Login(context.Background(), LoginCommand{ Email: "pending@example.com", Password: "correct horse battery staple", Incoming: incoming, }) if !errors.Is(err, ErrEmailNotVerified) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 { t.Fatalf("Login() error=%v created=%d revoked=%v", err, len(fixture.sessions.created), fixture.sessions.revoked) } } func TestSessionServiceLoginRejectsChangedCredentialSnapshot(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) changedPasswordHash, err := domain.NewPasswordHash(strings.Replace(testPasswordPHC, "aGFza", "bGFza", 1)) if err != nil { t.Fatal(err) } for _, test := range []struct { name string change func(domain.User) domain.User }{ { name: "registration version", change: func(user domain.User) domain.User { user.RegistrationVersion++ return user }, }, { name: "password hash", change: func(user domain.User) domain.User { user.PasswordHash = changedPasswordHash return user }, }, } { t.Run(test.name, func(t *testing.T) { user := sessionTestUser(t, "person@example.com", true, now) fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) fixture.users.afterGetByEmail = func() { changed := fixture.users.users[user.ID] fixture.users.users[user.ID] = test.change(changed) } _, err := fixture.service.Login(context.Background(), LoginCommand{ Email: "person@example.com", Password: "correct horse battery staple", }) if !errors.Is(err, ErrInvalidCredentials) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 { t.Fatalf("Login() error=%v created=%d revoked=%v, want changed snapshot rejected without session writes", err, len(fixture.sessions.created), fixture.sessions.revoked) } }) } } func TestSessionServiceLoginAppliesEmailLimitBeforeAccountLookup(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) user := sessionTestUser(t, "person@example.com", true, now) fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil) _, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "correct horse battery staple"}) var limited *RateLimitedError if !errors.As(err, &limited) || limited.RetryAfter != time.Minute || fixture.users.getByEmailCalls != 0 || fixture.hasher.verifyCalls != 0 { t.Fatalf("Login() error=%v, lookups=%d, verifies=%d", err, fixture.users.getByEmailCalls, fixture.hasher.verifyCalls) } } func TestSessionServiceAuthenticateUsesDatabaseSessionState(t *testing.T) { now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) user := sessionTestUser(t, "person@example.com", true, now) fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) token, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } session, err := domain.NewSession(domain.NewSessionInput{ UserID: user.ID, TokenHash: token.Hash(), StartedAt: now.Add(-time.Minute), AbsoluteLifetime: 7 * 24 * time.Hour, }) if err != nil { t.Fatal(err) } fixture.sessions.active[session.TokenHash] = session authenticated, err := fixture.service.Authenticate(context.Background(), token.Reveal()) if err != nil || authenticated.SessionID != session.ID || authenticated.User.ID != user.ID || len(fixture.sessions.touched) != 1 { t.Fatalf("Authenticate() = %+v, %v, touches=%v", authenticated, err, fixture.sessions.touched) } if !fixture.keyring.VerifySessionCSRF(token, authenticated.CSRFToken) { t.Fatal("authenticated session returned a CSRF token for a different session") } if _, err := fixture.service.Authenticate(context.Background(), "bad"); !errors.Is(err, ErrUnauthenticated) { t.Fatalf("Authenticate(malformed) error = %v, want ErrUnauthenticated", err) } expired, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } expiredSession, err := domain.NewSession(domain.NewSessionInput{ UserID: user.ID, TokenHash: expired.Hash(), StartedAt: now.Add(-8 * 24 * time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour, }) if err != nil { t.Fatal(err) } fixture.sessions.active[expiredSession.TokenHash] = expiredSession if _, err := fixture.service.Authenticate(context.Background(), expired.Reveal()); !errors.Is(err, ErrUnauthenticated) { t.Fatalf("Authenticate(expired) error = %v, want ErrUnauthenticated", err) } } func TestKeyringSessionCSRFIsDomainSeparatedAndFailsClosed(t *testing.T) { keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes))) if err != nil { t.Fatal(err) } first, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } second, err := domain.NewSecretToken() if err != nil { t.Fatal(err) } csrf := keyring.SessionCSRF(first) if len(csrf) != 43 || !keyring.VerifySessionCSRF(first, csrf) || keyring.VerifySessionCSRF(second, csrf) || keyring.VerifySessionCSRF(domain.SecretToken{}, "") { t.Fatal("session CSRF derivation did not stay bound to a valid session token") } } var _ outbound.UserRepository = (*sessionTestUserRepository)(nil) var _ outbound.SessionRepository = (*sessionTestSessionRepository)(nil) var _ outbound.UnitOfWork = sessionTestUnit{} var _ outbound.Transactor = sessionTestTransactor{} var _ outbound.RateLimiter = (*sessionTestLimiter)(nil) var _ outbound.PasswordHasher = (*sessionTestHasher)(nil)