Phase 1 Step 3: Authentication Services & Security Infrastructure #92

Closed
opened 2025-09-19 02:24:47 +00:00 by rwachters · 0 comments
rwachters commented 2025-09-19 02:24:47 +00:00 (Migrated from github.com)

Overview

This issue covers implementing the authentication services and security infrastructure for user accounts in the chatbot application. This builds on the database foundation from Steps 1-2 and creates the business logic layer for user authentication, session management, and access control.

Phase 1 - Foundation: Authentication & Private User Space

Goal: Establish the core user system, allowing users to register, log in, and see only their own private chat sessions and groups.

Step 3: Authentication Services & Security

Tasks

  • Implement AuthenticationService for user registration and login
  • Implement SessionService for session lifecycle management
  • Implement PasswordService for secure password handling
  • Implement OwnershipService for resource ownership verification
  • Create security utilities and middleware
  • Add comprehensive error handling with Arrow types

Service Requirements

AuthenticationService

  • registerUser(username, password, email): Either<AuthError, User>
  • authenticateUser(username, password): Either<AuthError, UserSession>
  • validateSession(sessionId): Either<AuthError, User>
  • refreshSession(sessionId): Either<AuthError, UserSession>
  • logout(sessionId): Either<AuthError, Unit>
  • getUserProfile(userId): Either<AuthError, User>

SessionService

  • createSession(userId, duration): Either<SessionError, UserSession>
  • getActiveSession(sessionId): Either<SessionError, UserSession>
  • extendSession(sessionId, duration): Either<SessionError, UserSession>
  • terminateSession(sessionId): Either<SessionError, Unit>
  • terminateAllUserSessions(userId): Either<SessionError, Unit>
  • cleanupExpiredSessions(): Either<SessionError, Int>

PasswordService

  • hashPassword(password): String
  • verifyPassword(password, hash): Boolean
  • generateSecurePassword(): String
  • validatePasswordStrength(password): Either<ValidationError, Unit>

OwnershipService

  • verifyChatSessionOwnership(sessionId, userId): Either<OwnershipError, Unit>
  • verifyChatGroupOwnership(groupId, userId): Either<OwnershipError, Unit>
  • getUserChatSessions(userId): Either<OwnershipError, List<ChatSession>>
  • getUserChatGroups(userId): Either<OwnershipError, List<ChatGroup>>
  • assignOwnership(resourceType, resourceId, userId): Either<OwnershipError, Unit>

Security Infrastructure

Error Types (Using Arrow)

sealed class AuthError {
    data object InvalidCredentials : AuthError()
    data object UserAlreadyExists : AuthError()
    data object SessionExpired : AuthError()
    data object SessionNotFound : AuthError()
    data object UserNotFound : AuthError()
    data class ValidationError(val message: String) : AuthError()
}

sealed class SessionError {
    data object SessionNotFound : SessionError()
    data object SessionExpired : SessionError()
    data object InvalidSession : SessionError()
    data class DatabaseError(val message: String) : SessionError()
}

sealed class OwnershipError {
    data object AccessDenied : OwnershipError()
    data object ResourceNotFound : OwnershipError()
    data object UserNotFound : OwnershipError()
    data class DatabaseError(val message: String) : OwnershipError()
}

Security Utilities

  • SessionToken - Type-safe session token wrapper
  • PasswordHash - Type-safe password hash wrapper
  • SecurityConfig - Configuration for session duration, password requirements
  • TimestampUtils - Utilities for session expiration handling

Authentication Middleware

  • Session validation for protected endpoints
  • User context injection for controllers
  • Automatic session cleanup scheduling

Technical Requirements

Password Security

  • Use bcrypt or Argon2 for password hashing
  • Implement configurable password strength requirements
  • Salt generation and storage
  • Secure password comparison (constant-time)

Session Management

  • Configurable session duration (default: 24 hours)
  • Session extension on activity
  • Secure session token generation (UUID or JWT)
  • Automatic cleanup of expired sessions

Error Handling

  • Use Arrow's Either type for all service methods
  • Implement proper error propagation
  • Log security events (failed logins, expired sessions)
  • Rate limiting considerations (future implementation)

Integration Points

  • Use DAOs from Step 2 for data persistence
  • Integrate with Koin DI container
  • Follow existing service patterns in the project
  • Use kotlinx.datetime for all time operations

File Locations

  • Service interfaces: server/src/main/kotlin/eu/torvian/chatbot/server/services/
  • Service implementations: server/src/main/kotlin/eu/torvian/chatbot/server/services/impl/
  • Security utilities: server/src/main/kotlin/eu/torvian/chatbot/server/security/
  • Error types: server/src/main/kotlin/eu/torvian/chatbot/server/errors/
  • Koin modules: server/src/main/kotlin/eu/torvian/chatbot/server/di/

Implementation Details

Dependencies to Add

// build.gradle.kts additions needed:
implementation("org.springframework.security:spring-security-crypto:6.3.3") // for bcrypt
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1") // already in project

Session Storage Strategy

  • Store sessions in database using UserSessionDao
  • Include session metadata (last accessed, user agent, IP address)
  • Implement session token as secure random UUID
  • Consider Redis for future scalability (not in this step)

User Registration Flow

  1. Validate input (username uniqueness, password strength, email format)
  2. Hash password securely
  3. Create user record with hashed password
  4. Assign default "Standard User" role
  5. Add user to "All Users" group
  6. Create initial session
  7. Return success with session token

Authentication Flow

  1. Validate credentials against database
  2. Verify password hash
  3. Create new session with expiration
  4. Return session token and user profile
  5. Log successful authentication

Integration with Existing Code

  • Services will use existing DAO interfaces from Step 2
  • No changes to existing controllers yet (that's Step 4)
  • Services will be registered in Koin DI container
  • Follow existing error handling patterns in the project

Acceptance Criteria

  • All authentication services are implemented with comprehensive error handling
  • Password hashing uses industry-standard algorithms (bcrypt/Argon2)
  • Session management supports creation, validation, extension, and cleanup
  • Ownership service properly filters resources by user context
  • All service methods use Arrow's Either for error handling
  • Services are properly integrated with Koin DI
  • Comprehensive unit tests cover all service functionality
  • Security logging captures authentication events
  • Session cleanup runs automatically for expired sessions
  • No existing functionality is broken

Dependencies

  • Completion of Issue #91 (Phase 1 Steps 1-2: Database Schema & Core DAOs)
  • Spring Security Crypto library for password hashing
  • Arrow 2.1.2 for error handling (already in project)
  • Koin 4.1.0 for dependency injection (already in project)
  • kotlinx.datetime for time operations (already in project)

Security Considerations

  • Use secure random number generation for session tokens
  • Implement constant-time password comparison
  • Log security events without exposing sensitive data
  • Consider session hijacking prevention measures
  • Validate all user inputs thoroughly
  • Use parameterized queries to prevent SQL injection (Exposed handles this)

Notes

  • This step focuses purely on business logic - no API endpoints yet
  • Services should be stateless and thread-safe
  • Consider future features like password reset, account lockout
  • Session tokens should be treated as sensitive data
  • Default session duration should be configurable
  • Services will be used by REST endpoints in Step 4
  • Depends on: Issue #91 (Phase 1 Steps 1-2: Database Schema & Core DAOs)
  • Epic: NF.E1 - User Accounts and Permissions
  • Next: Phase 1 Step 4 (REST API Endpoints & Authentication Middleware)
  • Documentation: docs/plans/user accounts/User Accounts feature.md
## Overview This issue covers implementing the authentication services and security infrastructure for user accounts in the chatbot application. This builds on the database foundation from Steps 1-2 and creates the business logic layer for user authentication, session management, and access control. ## Phase 1 - Foundation: Authentication & Private User Space **Goal:** Establish the core user system, allowing users to register, log in, and see only their own private chat sessions and groups. ## Step 3: Authentication Services & Security ### Tasks - [ ] Implement `AuthenticationService` for user registration and login - [ ] Implement `SessionService` for session lifecycle management - [ ] Implement `PasswordService` for secure password handling - [ ] Implement `OwnershipService` for resource ownership verification - [ ] Create security utilities and middleware - [ ] Add comprehensive error handling with Arrow types ### Service Requirements #### AuthenticationService - `registerUser(username, password, email): Either<AuthError, User>` - `authenticateUser(username, password): Either<AuthError, UserSession>` - `validateSession(sessionId): Either<AuthError, User>` - `refreshSession(sessionId): Either<AuthError, UserSession>` - `logout(sessionId): Either<AuthError, Unit>` - `getUserProfile(userId): Either<AuthError, User>` #### SessionService - `createSession(userId, duration): Either<SessionError, UserSession>` - `getActiveSession(sessionId): Either<SessionError, UserSession>` - `extendSession(sessionId, duration): Either<SessionError, UserSession>` - `terminateSession(sessionId): Either<SessionError, Unit>` - `terminateAllUserSessions(userId): Either<SessionError, Unit>` - `cleanupExpiredSessions(): Either<SessionError, Int>` #### PasswordService - `hashPassword(password): String` - `verifyPassword(password, hash): Boolean` - `generateSecurePassword(): String` - `validatePasswordStrength(password): Either<ValidationError, Unit>` #### OwnershipService - `verifyChatSessionOwnership(sessionId, userId): Either<OwnershipError, Unit>` - `verifyChatGroupOwnership(groupId, userId): Either<OwnershipError, Unit>` - `getUserChatSessions(userId): Either<OwnershipError, List<ChatSession>>` - `getUserChatGroups(userId): Either<OwnershipError, List<ChatGroup>>` - `assignOwnership(resourceType, resourceId, userId): Either<OwnershipError, Unit>` ### Security Infrastructure #### Error Types (Using Arrow) ```kotlin sealed class AuthError { data object InvalidCredentials : AuthError() data object UserAlreadyExists : AuthError() data object SessionExpired : AuthError() data object SessionNotFound : AuthError() data object UserNotFound : AuthError() data class ValidationError(val message: String) : AuthError() } sealed class SessionError { data object SessionNotFound : SessionError() data object SessionExpired : SessionError() data object InvalidSession : SessionError() data class DatabaseError(val message: String) : SessionError() } sealed class OwnershipError { data object AccessDenied : OwnershipError() data object ResourceNotFound : OwnershipError() data object UserNotFound : OwnershipError() data class DatabaseError(val message: String) : OwnershipError() } ``` #### Security Utilities - `SessionToken` - Type-safe session token wrapper - `PasswordHash` - Type-safe password hash wrapper - `SecurityConfig` - Configuration for session duration, password requirements - `TimestampUtils` - Utilities for session expiration handling #### Authentication Middleware - Session validation for protected endpoints - User context injection for controllers - Automatic session cleanup scheduling ### Technical Requirements #### Password Security - Use bcrypt or Argon2 for password hashing - Implement configurable password strength requirements - Salt generation and storage - Secure password comparison (constant-time) #### Session Management - Configurable session duration (default: 24 hours) - Session extension on activity - Secure session token generation (UUID or JWT) - Automatic cleanup of expired sessions #### Error Handling - Use Arrow's `Either` type for all service methods - Implement proper error propagation - Log security events (failed logins, expired sessions) - Rate limiting considerations (future implementation) #### Integration Points - Use DAOs from Step 2 for data persistence - Integrate with Koin DI container - Follow existing service patterns in the project - Use kotlinx.datetime for all time operations ### File Locations - Service interfaces: `server/src/main/kotlin/eu/torvian/chatbot/server/services/` - Service implementations: `server/src/main/kotlin/eu/torvian/chatbot/server/services/impl/` - Security utilities: `server/src/main/kotlin/eu/torvian/chatbot/server/security/` - Error types: `server/src/main/kotlin/eu/torvian/chatbot/server/errors/` - Koin modules: `server/src/main/kotlin/eu/torvian/chatbot/server/di/` ### Implementation Details #### Dependencies to Add ```kotlin // build.gradle.kts additions needed: implementation("org.springframework.security:spring-security-crypto:6.3.3") // for bcrypt implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1") // already in project ``` #### Session Storage Strategy - Store sessions in database using `UserSessionDao` - Include session metadata (last accessed, user agent, IP address) - Implement session token as secure random UUID - Consider Redis for future scalability (not in this step) #### User Registration Flow 1. Validate input (username uniqueness, password strength, email format) 2. Hash password securely 3. Create user record with hashed password 4. Assign default "Standard User" role 5. Add user to "All Users" group 6. Create initial session 7. Return success with session token #### Authentication Flow 1. Validate credentials against database 2. Verify password hash 3. Create new session with expiration 4. Return session token and user profile 5. Log successful authentication ### Integration with Existing Code - Services will use existing DAO interfaces from Step 2 - No changes to existing controllers yet (that's Step 4) - Services will be registered in Koin DI container - Follow existing error handling patterns in the project ## Acceptance Criteria - [ ] All authentication services are implemented with comprehensive error handling - [ ] Password hashing uses industry-standard algorithms (bcrypt/Argon2) - [ ] Session management supports creation, validation, extension, and cleanup - [ ] Ownership service properly filters resources by user context - [ ] All service methods use Arrow's Either for error handling - [ ] Services are properly integrated with Koin DI - [ ] Comprehensive unit tests cover all service functionality - [ ] Security logging captures authentication events - [ ] Session cleanup runs automatically for expired sessions - [ ] No existing functionality is broken ## Dependencies - Completion of Issue #91 (Phase 1 Steps 1-2: Database Schema & Core DAOs) - Spring Security Crypto library for password hashing - Arrow 2.1.2 for error handling (already in project) - Koin 4.1.0 for dependency injection (already in project) - kotlinx.datetime for time operations (already in project) ## Security Considerations - Use secure random number generation for session tokens - Implement constant-time password comparison - Log security events without exposing sensitive data - Consider session hijacking prevention measures - Validate all user inputs thoroughly - Use parameterized queries to prevent SQL injection (Exposed handles this) ## Notes - This step focuses purely on business logic - no API endpoints yet - Services should be stateless and thread-safe - Consider future features like password reset, account lockout - Session tokens should be treated as sensitive data - Default session duration should be configurable - Services will be used by REST endpoints in Step 4 ## Related - Depends on: Issue #91 (Phase 1 Steps 1-2: Database Schema & Core DAOs) - Epic: NF.E1 - User Accounts and Permissions - Next: Phase 1 Step 4 (REST API Endpoints & Authentication Middleware) - Documentation: `docs/plans/user accounts/User Accounts feature.md`
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Torvian.eu/chatbot#92
No description provided.