feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
@@ -3,12 +3,16 @@ package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
//nolint:gosec // G101: this fixed value is only used for dummy Argon2 work and never authenticates an account.
|
||||
const dummyLoginPassword = "lincodex-login-dummy-password"
|
||||
|
||||
// Credentials applies the password rules in the order that keeps hashing
|
||||
// bounded: the cheap length and encoding checks first, the expensive KDF only
|
||||
// for a password that passes them.
|
||||
@@ -52,3 +56,18 @@ func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw str
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyDummyLoginPassword spends the same password-hash work for an unknown
|
||||
// account as VerifyLoginPassword does for a known one. The result is always a
|
||||
// mismatch unless the hasher fails for an operational reason.
|
||||
func (credentials *Credentials) VerifyDummyLoginPassword(ctx context.Context, raw string) error {
|
||||
password, err := domain.ParseLoginPassword(raw)
|
||||
if err != nil {
|
||||
password, _ = domain.ParseLoginPassword(dummyLoginPassword)
|
||||
}
|
||||
err = credentials.hasher.VerifyDummy(ctx, password)
|
||||
if errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return outbound.ErrPasswordMismatch
|
||||
}
|
||||
return fmt.Errorf("Credentials.VerifyDummyLoginPassword - verify dummy hash: %w", err)
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type countingHasher struct {
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
verifyCalls int
|
||||
dummyCalls int
|
||||
verified domain.Password
|
||||
stored domain.PasswordHash
|
||||
verifyErr error
|
||||
@@ -39,7 +40,8 @@ func (hasher *countingHasher) Verify(_ context.Context, password domain.Password
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
return errors.New("countingHasher.VerifyDummy - not used")
|
||||
hasher.dummyCalls++
|
||||
return outbound.ErrPasswordMismatch
|
||||
}
|
||||
|
||||
var _ outbound.PasswordHasher = (*countingHasher)(nil)
|
||||
@@ -116,3 +118,16 @@ func TestVerifyLoginPasswordRejectsEmptyInputBeforeKDF(t *testing.T) {
|
||||
t.Fatalf("VerifyLoginPassword(empty) = %v after %d verify calls, want ErrInvalidPassword before KDF", err, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDummyLoginPasswordAlwaysRunsDummyHashWork(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
credentials := NewCredentials(hasher)
|
||||
for _, password := range []string{"correct horse battery staple", ""} {
|
||||
if err := credentials.VerifyDummyLoginPassword(context.Background(), password); !errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
t.Fatalf("VerifyDummyLoginPassword() error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
if hasher.dummyCalls != 2 || hasher.verifyCalls != 0 {
|
||||
t.Fatalf("dummy calls=%d normal calls=%d, want two dummy calls", hasher.dummyCalls, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,18 @@ var (
|
||||
// ErrVerificationTokenExpired reports an email verification token past its
|
||||
// expiry time.
|
||||
ErrVerificationTokenExpired = errors.New("verification token expired")
|
||||
|
||||
// ErrInvalidCredentials represents an unknown account or an incorrect
|
||||
// password with one public outcome.
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
|
||||
// ErrEmailNotVerified reports correct credentials for an unverified
|
||||
// account. It never creates a session.
|
||||
ErrEmailNotVerified = errors.New("email not verified")
|
||||
|
||||
// ErrUnauthenticated reports a missing, invalid, expired, idle, or revoked
|
||||
// server session.
|
||||
ErrUnauthenticated = errors.New("unauthenticated")
|
||||
)
|
||||
|
||||
// RateLimitedError carries how long the caller waits before a repeat can be
|
||||
|
||||
@@ -3,9 +3,11 @@ package identity
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
@@ -20,6 +22,7 @@ const (
|
||||
labelEmailBucket = "lincodex/identity/email-bucket/v1"
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -33,6 +36,7 @@ type Keyring struct {
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
sessionCSRFKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -46,6 +50,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
sessionCSRFKey: derive(secret, labelSessionCSRF),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -99,3 +104,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
|
||||
mac.Write([]byte(rawToken))
|
||||
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// SessionCSRF derives a synchronizer token for exactly one session. The
|
||||
// purpose key and message are both domain-separated from every other keyring
|
||||
// use, and only the encoded result is returned to the HTTP adapter.
|
||||
func (keyring *Keyring) SessionCSRF(token domain.SecretToken) string {
|
||||
if token.IsZero() {
|
||||
return ""
|
||||
}
|
||||
mac := hmac.New(sha256.New, keyring.sessionCSRFKey)
|
||||
mac.Write([]byte(labelSessionCSRF))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write([]byte(token.Reveal()))
|
||||
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerifySessionCSRF compares the supplied synchronizer token in constant
|
||||
// time with the token bound to this session.
|
||||
func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied string) bool {
|
||||
if token.IsZero() {
|
||||
return false
|
||||
}
|
||||
return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied))
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// SessionSettings bounds login attempts and the life of a server-side
|
||||
// session. Session expiry is enforced by PostgreSQL on every lookup.
|
||||
type SessionSettings struct {
|
||||
ClientHourlyLimit int64
|
||||
EmailHourlyLimit int64
|
||||
IdleTimeout time.Duration
|
||||
AbsoluteLifetime time.Duration
|
||||
}
|
||||
|
||||
// SessionDependencies are the collaborators of SessionService. Metrics and
|
||||
// logger are optional; all other dependencies are required.
|
||||
type SessionDependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Users outbound.UserRepository
|
||||
Sessions outbound.SessionRepository
|
||||
Credentials *Credentials
|
||||
Limiter outbound.RateLimiter
|
||||
Keyring *Keyring
|
||||
Clock func() time.Time
|
||||
Metrics RateLimitMetrics
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// SessionService authenticates accounts and manages their server-side
|
||||
// sessions. It keeps no mutable per-request state.
|
||||
type SessionService struct {
|
||||
deps SessionDependencies
|
||||
settings SessionSettings
|
||||
}
|
||||
|
||||
func NewSessionService(deps SessionDependencies, settings SessionSettings) (*SessionService, error) {
|
||||
switch {
|
||||
case deps.Transactor == nil, deps.Users == nil, deps.Sessions == nil, deps.Credentials == nil,
|
||||
deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
|
||||
return nil, errors.New("identity.NewSessionService - every dependency must be set")
|
||||
case settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1,
|
||||
settings.IdleTimeout <= 0, settings.AbsoluteLifetime <= 0,
|
||||
settings.IdleTimeout > settings.AbsoluteLifetime:
|
||||
return nil, errors.New("identity.NewSessionService - invalid session settings")
|
||||
}
|
||||
if deps.Logger == nil {
|
||||
deps.Logger = slog.Default()
|
||||
}
|
||||
return &SessionService{deps: deps, settings: settings}, nil
|
||||
}
|
||||
|
||||
// LoginCommand is the content of an unvalidated login request.
|
||||
type LoginCommand struct {
|
||||
Email string
|
||||
Password string
|
||||
ClientKey string
|
||||
Incoming domain.SecretToken
|
||||
}
|
||||
|
||||
// LoginResult contains the user-facing session response and the raw cookie
|
||||
// token. The token is redacted by domain.SecretToken and must only be revealed
|
||||
// by the HTTP adapter when it writes Set-Cookie.
|
||||
type LoginResult struct {
|
||||
User domain.User
|
||||
Session domain.Session
|
||||
Token domain.SecretToken
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// AuthenticatedSession is the server-side identity resolved from a cookie.
|
||||
// It contains no raw session token or credential material.
|
||||
type AuthenticatedSession struct {
|
||||
User domain.User
|
||||
SessionID uuid.UUID
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// Login checks both rate limits before password verification. Unknown
|
||||
// addresses receive the dummy password-hash work; an invalid stored hash is
|
||||
// logged without account details and follows the same public failure path.
|
||||
func (service *SessionService) Login(ctx context.Context, command LoginCommand) (LoginResult, error) {
|
||||
const location = "SessionService.Login"
|
||||
email, err := domain.NewEmailAddress(command.Email)
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err))
|
||||
}
|
||||
if err := service.takeLoginAttempt(ctx, email, command.ClientKey); err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - limit login: %w", location, err)
|
||||
}
|
||||
user, err := service.loginUser(ctx, email, command.Password)
|
||||
if err != nil {
|
||||
return LoginResult{}, err
|
||||
}
|
||||
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - create session token: %w", location, err)
|
||||
}
|
||||
authenticatedUser, created, err := service.createLoginSession(ctx, user, command.Incoming, token)
|
||||
if err != nil {
|
||||
return LoginResult{}, fmt.Errorf("%s - rotate session: %w", location, err)
|
||||
}
|
||||
return LoginResult{
|
||||
User: authenticatedUser,
|
||||
Session: created,
|
||||
Token: token,
|
||||
CSRFToken: service.deps.Keyring.SessionCSRF(token),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *SessionService) loginUser(ctx context.Context, email domain.EmailAddress, password string) (domain.User, error) {
|
||||
user, err := service.deps.Users.GetByEmail(ctx, email)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil {
|
||||
return domain.User{}, dummyErr
|
||||
}
|
||||
return domain.User{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("SessionService.Login - read account: %w", err)
|
||||
}
|
||||
if err := service.verifyLoginPassword(ctx, password, user.PasswordHash); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return domain.User{}, ErrEmailNotVerified
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (service *SessionService) verifyLoginPassword(ctx context.Context, password string, passwordHash domain.PasswordHash) error {
|
||||
err := service.deps.Credentials.VerifyLoginPassword(ctx, password, passwordHash)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
if errors.Is(err, domain.ErrInvalidPassword) || errors.Is(err, outbound.ErrPasswordHashCorrupt) ||
|
||||
errors.Is(err, domain.ErrInvalidPasswordHash) {
|
||||
if errors.Is(err, outbound.ErrPasswordHashCorrupt) || errors.Is(err, domain.ErrInvalidPasswordHash) {
|
||||
service.deps.Logger.ErrorContext(ctx, "login rejected because the stored password hash is invalid")
|
||||
}
|
||||
if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil {
|
||||
return dummyErr
|
||||
}
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
return fmt.Errorf("SessionService.Login - verify password: %w", err)
|
||||
}
|
||||
|
||||
func (service *SessionService) verifyDummyLoginPassword(ctx context.Context, password string) error {
|
||||
err := service.deps.Credentials.VerifyDummyLoginPassword(ctx, password)
|
||||
if err == nil || errors.Is(err, outbound.ErrPasswordMismatch) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("SessionService.Login - verify dummy password: %w", err)
|
||||
}
|
||||
|
||||
func (service *SessionService) createLoginSession(
|
||||
ctx context.Context,
|
||||
loginSnapshot domain.User,
|
||||
incoming, token domain.SecretToken,
|
||||
) (domain.User, domain.Session, error) {
|
||||
startedAt := service.deps.Clock()
|
||||
var authenticatedUser domain.User
|
||||
var created domain.Session
|
||||
err := service.deps.Transactor.WithinTransaction(ctx, func(tx context.Context, unit outbound.UnitOfWork) error {
|
||||
user, session, err := service.createLoginSessionInTransaction(tx, unit, loginSnapshot, incoming, token, startedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
authenticatedUser = user
|
||||
created = session
|
||||
return nil
|
||||
})
|
||||
return authenticatedUser, created, err
|
||||
}
|
||||
|
||||
func (service *SessionService) createLoginSessionInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
loginSnapshot domain.User,
|
||||
incoming, token domain.SecretToken,
|
||||
startedAt time.Time,
|
||||
) (domain.User, domain.Session, error) {
|
||||
const location = "SessionService.Login"
|
||||
user, err := unit.Users().GetByID(ctx, loginSnapshot.ID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return domain.User{}, domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - recheck account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return domain.User{}, domain.Session{}, ErrEmailNotVerified
|
||||
}
|
||||
if !sameLoginCredentials(loginSnapshot, user) {
|
||||
return domain.User{}, domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
if err := service.revokeIncomingSession(ctx, unit.Sessions(), incoming, startedAt); err != nil {
|
||||
return domain.User{}, domain.Session{}, err
|
||||
}
|
||||
session, err := domain.NewSession(domain.NewSessionInput{
|
||||
UserID: user.ID,
|
||||
TokenHash: token.Hash(),
|
||||
StartedAt: startedAt,
|
||||
AbsoluteLifetime: service.settings.AbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - build session: %w", location, err)
|
||||
}
|
||||
if err := unit.Sessions().Create(ctx, session); err != nil {
|
||||
return domain.User{}, domain.Session{}, fmt.Errorf("%s - create session: %w", location, err)
|
||||
}
|
||||
return user, session, nil
|
||||
}
|
||||
|
||||
func sameLoginCredentials(snapshot, current domain.User) bool {
|
||||
return snapshot.RegistrationVersion == current.RegistrationVersion &&
|
||||
snapshot.PasswordHash.PHC() == current.PasswordHash.PHC()
|
||||
}
|
||||
|
||||
func (service *SessionService) revokeIncomingSession(
|
||||
ctx context.Context,
|
||||
sessions outbound.SessionRepository,
|
||||
incoming domain.SecretToken,
|
||||
now time.Time,
|
||||
) error {
|
||||
if incoming.IsZero() {
|
||||
return nil
|
||||
}
|
||||
old, err := sessions.FindActive(ctx, incoming.Hash(), now, service.settings.IdleTimeout)
|
||||
if errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("SessionService.Login - read incoming session: %w", err)
|
||||
}
|
||||
if err := sessions.Revoke(ctx, old.ID, now); err != nil && !errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return fmt.Errorf("SessionService.Login - revoke incoming session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Authenticate validates the cookie against PostgreSQL, checks the account
|
||||
// remains verified, and records activity subject to the session idle timeout.
|
||||
func (service *SessionService) Authenticate(ctx context.Context, rawToken string) (AuthenticatedSession, error) {
|
||||
const location = "SessionService.Authenticate"
|
||||
token, err := domain.ParseSecretToken(rawToken)
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
now := service.deps.Clock()
|
||||
session, err := service.deps.Sessions.FindActive(ctx, token.Hash(), now, service.settings.IdleTimeout)
|
||||
if errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - read session: %w", location, err)
|
||||
}
|
||||
user, err := service.deps.Users.GetByID(ctx, session.UserID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) || err == nil && !user.EmailVerified() {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if err := service.deps.Sessions.Touch(ctx, session.ID, now, service.settings.IdleTimeout); errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return AuthenticatedSession{}, ErrUnauthenticated
|
||||
} else if err != nil {
|
||||
return AuthenticatedSession{}, fmt.Errorf("%s - record activity: %w", location, err)
|
||||
}
|
||||
return AuthenticatedSession{
|
||||
User: user,
|
||||
SessionID: session.ID,
|
||||
CSRFToken: service.deps.Keyring.SessionCSRF(token),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Logout revokes the session ID placed in context by authentication. A
|
||||
// repeated logout is treated as an unauthenticated stale session.
|
||||
func (service *SessionService) Logout(ctx context.Context, sessionID uuid.UUID) error {
|
||||
if sessionID == uuid.Nil {
|
||||
return ErrUnauthenticated
|
||||
}
|
||||
if err := service.deps.Sessions.Revoke(ctx, sessionID, service.deps.Clock()); errors.Is(err, outbound.ErrSessionNotFound) {
|
||||
return ErrUnauthenticated
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("SessionService.Logout - revoke session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *SessionService) takeLoginAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error {
|
||||
if clientKey != "" {
|
||||
if err := service.take(ctx, ScopeClient, service.deps.Keyring.ClientBucket(clientKey), service.settings.ClientHourlyLimit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return service.take(ctx, ScopeAddress, service.deps.Keyring.EmailBucket(email.Normalized()), service.settings.EmailHourlyLimit)
|
||||
}
|
||||
|
||||
func (service *SessionService) take(ctx context.Context, scope, bucket string, limit int64) error {
|
||||
decision, err := service.deps.Limiter.Take(ctx, bucket, outbound.RateLimitRule{Window: time.Hour, Limit: limit})
|
||||
if err != nil {
|
||||
return fmt.Errorf("take %s login limit: %w", scope, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
if service.deps.Metrics != nil {
|
||||
service.deps.Metrics.ObserveIdentityRateLimited(scope)
|
||||
}
|
||||
return &RateLimitedError{RetryAfter: decision.RetryAfter}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
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)
|
||||
Reference in new issue
Block a user