Phase 1: Authentication Infrastructure #95

Closed
opened 2025-09-22 12:31:53 +00:00 by rwachters · 0 comments
rwachters commented 2025-09-22 12:31:53 +00:00 (Migrated from github.com)

Phase 1: Authentication Infrastructure

Overview

Implement the core authentication infrastructure for the Kotlin/Compose chatbot application. This phase establishes the foundation for secure token management, authenticated HTTP communication, and authentication state management without requiring UI changes.

Task Breakdown

Task 1: Token Management Infrastructure (2-3 days)

1.1 Platform-Agnostic Token Storage Interface

  • File: app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/auth/TokenStorage.kt
  • Description: Create interface for secure token storage with JWT expiration validation
  • Acceptance Criteria:
    • Interface compiles and follows existing codebase patterns
    • All methods are properly documented with KDoc
    • Token expiration logic handles JWT format correctly
    • Interface supports both access and refresh token operations

1.2 Desktop Token Storage Implementation

  • File: app/src/desktopMain/kotlin/eu/torvian/chatbot/app/service/auth/DesktopTokenStorage.kt
  • Description: File-based encrypted token storage in user home directory (.chatbot/tokens.enc)
  • Acceptance Criteria:
    • Tokens are encrypted before storage
    • File permissions are set appropriately (600)
    • Directory creation is handled gracefully
    • Error handling for disk space, permissions, etc.
    • Unit tests cover all storage scenarios

1.3 Web Token Storage Implementation

  • File: app/src/wasmJsMain/kotlin/eu/torvian/chatbot/app/service/auth/WebTokenStorage.kt
  • Description: localStorage-based token storage with client-side encryption
  • Acceptance Criteria:
    • Tokens are encrypted before localStorage storage
    • localStorage quota limits are handled
    • Fallback to sessionStorage if localStorage unavailable
    • Unit tests using MockK for localStorage

Task 2: Authenticated HTTP Client (3-4 days)

2.1 Authentication-Aware HTTP Client

  • File: app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/auth/AuthenticatedHttpClient.kt
  • Description: HTTP client wrapper with automatic token injection and refresh
  • Key Features:
    • Automatic token injection via Authorization header
    • Token refresh logic when access token expires
    • Automatic logout on 401 responses
    • Integration with existing safeApiCall pattern
  • Acceptance Criteria:
    • Authorization header is automatically added to requests
    • Token refresh is triggered before expiration
    • 401 responses trigger automatic logout
    • Integrates seamlessly with existing API clients
    • Comprehensive error handling for auth failures
    • Unit tests cover all authentication scenarios

2.2 HTTP Client Factory Updates

  • File: app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/ktor/createHttpClient.kt
  • Description: Add factory method for authenticated HTTP client while maintaining backward compatibility
  • Acceptance Criteria:
    • New factory method creates authenticated client
    • Existing factory method remains unchanged
    • Both clients share common configuration
    • No breaking changes to existing API clients

Task 3: Authentication API Client (2 days)

3.1 Authentication API Client Implementation

  • Files:
    • app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/AuthApi.kt (interface)
    • app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/ktor/KtorAuthApiClient.kt
  • Description: API client for authentication endpoints following existing patterns
  • Endpoints:
    • Login, Register, Refresh Token, Logout, Logout All, Get Current User
  • Acceptance Criteria:
    • All authentication endpoints are implemented
    • Follows existing API client patterns
    • Uses safeApiCall for error handling
    • Proper request/response serialization
    • Unit tests for all endpoints
    • Integration tests with mock server

Task 4: Authentication Repository (3 days)

4.1 Authentication Repository Implementation

  • Files:
    • app/src/commonMain/kotlin/eu/torvian/chatbot/app/repository/AuthRepository.kt (interface)
    • app/src/commonMain/kotlin/eu/torvian/chatbot/app/repository/impl/DefaultAuthRepository.kt
  • Description: Repository with reactive authentication state management
  • Features:
    • Reactive authentication state using StateFlow
    • Token management integration
    • Automatic token refresh
    • Comprehensive error handling
  • Acceptance Criteria:
    • Reactive authentication state management
    • Automatic token refresh before expiration
    • Proper error handling and mapping
    • Integration with TokenStorage
    • Unit tests with MockK
    • Follows existing repository patterns

Implementation Order & Dependencies

Recommended Implementation Sequence:

  1. Week 1: Task 1 (Token Management) - All subtasks in parallel
  2. Week 2: Task 2 (Authenticated HTTP Client) - Sequential implementation
  3. Week 3: Task 3 (Auth API Client) + Task 4 (Auth Repository) - Can be done in parallel
  4. Week 4: Integration, testing, and refinement

Dependencies:

  • Task 2 depends on Task 1 (TokenStorage)
  • Task 4 depends on Task 1 (TokenStorage) and Task 3 (AuthApi)

Platform Considerations

Desktop Platform

  • Token Storage: Encrypted file in ~/.chatbot/tokens.enc
  • Security: File permissions (600), directory creation
  • Dependencies: File I/O, basic encryption utilities

Web Platform (WASM)

  • Token Storage: localStorage with client-side encryption
  • Security: XSS protection, secure token handling
  • Dependencies: Browser APIs, localStorage availability

Common Considerations

  • JWT Handling: Token parsing and expiration validation
  • Error Recovery: Network failures, token corruption
  • Performance: Minimal overhead for token operations

Testing Strategy

Unit Tests Required

  • Token Storage Tests: Secure storage, retrieval, JWT expiration validation
  • Authenticated HTTP Client Tests: Header injection, token refresh, 401 handling
  • Repository Tests: State management, login/logout flows, error handling

Integration Tests Required

  • End-to-end authentication flow
  • Token refresh scenarios
  • Logout and session cleanup
  • Error handling and recovery
  • Platform-specific storage behavior

Technical Notes

  • Follow existing codebase patterns using Kotlin 2.2.0, Ktor 3.2.3, and Arrow 2.1.2
  • Use kotlinx.datetime instead of java.time
  • Error return types should be logical errors, not technical errors
  • Integrate with existing Koin DI setup
  • Maintain compatibility with current HTTP client configuration

Definition of Done

  • All tasks completed with acceptance criteria met
  • Unit tests written and passing
  • Integration tests implemented
  • Code follows existing patterns and conventions
  • Documentation updated (KDoc)
  • No breaking changes to existing functionality
  • Cross-platform compatibility verified (Desktop + Web)

Estimated Total Effort: 10-12 days
Priority: High - Foundation for user authentication feature

# Phase 1: Authentication Infrastructure ## Overview Implement the core authentication infrastructure for the Kotlin/Compose chatbot application. This phase establishes the foundation for secure token management, authenticated HTTP communication, and authentication state management without requiring UI changes. ## Task Breakdown ### Task 1: Token Management Infrastructure (2-3 days) #### 1.1 Platform-Agnostic Token Storage Interface - **File**: `app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/auth/TokenStorage.kt` - **Description**: Create interface for secure token storage with JWT expiration validation - **Acceptance Criteria**: - [ ] Interface compiles and follows existing codebase patterns - [ ] All methods are properly documented with KDoc - [ ] Token expiration logic handles JWT format correctly - [ ] Interface supports both access and refresh token operations #### 1.2 Desktop Token Storage Implementation - **File**: `app/src/desktopMain/kotlin/eu/torvian/chatbot/app/service/auth/DesktopTokenStorage.kt` - **Description**: File-based encrypted token storage in user home directory (`.chatbot/tokens.enc`) - **Acceptance Criteria**: - [ ] Tokens are encrypted before storage - [ ] File permissions are set appropriately (600) - [ ] Directory creation is handled gracefully - [ ] Error handling for disk space, permissions, etc. - [ ] Unit tests cover all storage scenarios #### 1.3 Web Token Storage Implementation - **File**: `app/src/wasmJsMain/kotlin/eu/torvian/chatbot/app/service/auth/WebTokenStorage.kt` - **Description**: localStorage-based token storage with client-side encryption - **Acceptance Criteria**: - [ ] Tokens are encrypted before localStorage storage - [ ] localStorage quota limits are handled - [ ] Fallback to sessionStorage if localStorage unavailable - [ ] Unit tests using MockK for localStorage ### Task 2: Authenticated HTTP Client (3-4 days) #### 2.1 Authentication-Aware HTTP Client - **File**: `app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/auth/AuthenticatedHttpClient.kt` - **Description**: HTTP client wrapper with automatic token injection and refresh - **Key Features**: - Automatic token injection via Authorization header - Token refresh logic when access token expires - Automatic logout on 401 responses - Integration with existing `safeApiCall` pattern - **Acceptance Criteria**: - [ ] Authorization header is automatically added to requests - [ ] Token refresh is triggered before expiration - [ ] 401 responses trigger automatic logout - [ ] Integrates seamlessly with existing API clients - [ ] Comprehensive error handling for auth failures - [ ] Unit tests cover all authentication scenarios #### 2.2 HTTP Client Factory Updates - **File**: `app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/ktor/createHttpClient.kt` - **Description**: Add factory method for authenticated HTTP client while maintaining backward compatibility - **Acceptance Criteria**: - [ ] New factory method creates authenticated client - [ ] Existing factory method remains unchanged - [ ] Both clients share common configuration - [ ] No breaking changes to existing API clients ### Task 3: Authentication API Client (2 days) #### 3.1 Authentication API Client Implementation - **Files**: - `app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/AuthApi.kt` (interface) - `app/src/commonMain/kotlin/eu/torvian/chatbot/app/service/api/ktor/KtorAuthApiClient.kt` - **Description**: API client for authentication endpoints following existing patterns - **Endpoints**: - Login, Register, Refresh Token, Logout, Logout All, Get Current User - **Acceptance Criteria**: - [ ] All authentication endpoints are implemented - [ ] Follows existing API client patterns - [ ] Uses `safeApiCall` for error handling - [ ] Proper request/response serialization - [ ] Unit tests for all endpoints - [ ] Integration tests with mock server ### Task 4: Authentication Repository (3 days) #### 4.1 Authentication Repository Implementation - **Files**: - `app/src/commonMain/kotlin/eu/torvian/chatbot/app/repository/AuthRepository.kt` (interface) - `app/src/commonMain/kotlin/eu/torvian/chatbot/app/repository/impl/DefaultAuthRepository.kt` - **Description**: Repository with reactive authentication state management - **Features**: - Reactive authentication state using StateFlow - Token management integration - Automatic token refresh - Comprehensive error handling - **Acceptance Criteria**: - [ ] Reactive authentication state management - [ ] Automatic token refresh before expiration - [ ] Proper error handling and mapping - [ ] Integration with TokenStorage - [ ] Unit tests with MockK - [ ] Follows existing repository patterns ## Implementation Order & Dependencies **Recommended Implementation Sequence:** 1. **Week 1**: Task 1 (Token Management) - All subtasks in parallel 2. **Week 2**: Task 2 (Authenticated HTTP Client) - Sequential implementation 3. **Week 3**: Task 3 (Auth API Client) + Task 4 (Auth Repository) - Can be done in parallel 4. **Week 4**: Integration, testing, and refinement **Dependencies:** - Task 2 depends on Task 1 (TokenStorage) - Task 4 depends on Task 1 (TokenStorage) and Task 3 (AuthApi) ## Platform Considerations ### Desktop Platform - **Token Storage**: Encrypted file in `~/.chatbot/tokens.enc` - **Security**: File permissions (600), directory creation - **Dependencies**: File I/O, basic encryption utilities ### Web Platform (WASM) - **Token Storage**: localStorage with client-side encryption - **Security**: XSS protection, secure token handling - **Dependencies**: Browser APIs, localStorage availability ### Common Considerations - **JWT Handling**: Token parsing and expiration validation - **Error Recovery**: Network failures, token corruption - **Performance**: Minimal overhead for token operations ## Testing Strategy ### Unit Tests Required - **Token Storage Tests**: Secure storage, retrieval, JWT expiration validation - **Authenticated HTTP Client Tests**: Header injection, token refresh, 401 handling - **Repository Tests**: State management, login/logout flows, error handling ### Integration Tests Required - End-to-end authentication flow - Token refresh scenarios - Logout and session cleanup - Error handling and recovery - Platform-specific storage behavior ## Technical Notes - Follow existing codebase patterns using Kotlin 2.2.0, Ktor 3.2.3, and Arrow 2.1.2 - Use kotlinx.datetime instead of java.time - Error return types should be logical errors, not technical errors - Integrate with existing Koin DI setup - Maintain compatibility with current HTTP client configuration ## Definition of Done - [ ] All tasks completed with acceptance criteria met - [ ] Unit tests written and passing - [ ] Integration tests implemented - [ ] Code follows existing patterns and conventions - [ ] Documentation updated (KDoc) - [ ] No breaking changes to existing functionality - [ ] Cross-platform compatibility verified (Desktop + Web) **Estimated Total Effort**: 10-12 days **Priority**: High - Foundation for user authentication feature
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#95
No description provided.