Files

327 lines
12 KiB
Go

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
}