# Design Document ## Overview Ce document décrit la solution pour résoudre le problème d'authentification entre l'agent v0 et le serveur API. Le problème actuel est que tous les uploads échouent avec une erreur HTTP 401 "unauthorized", empêchant la remontée des sessions capturées vers le serveur. ## Architecture ### Composants impliqués 1. **Agent v0** (`agent_v0/uploader.py`) - Responsable de l'upload des sessions 2. **Serveur API** (`server/api_upload.py`) - Endpoint qui reçoit les uploads 3. **Configuration** (`agent_v0/config.py`) - Gestion des paramètres d'authentification 4. **Diagnostic Tool** - Nouvel outil pour tester l'authentification ### Flux d'authentification ```mermaid sequenceDiagram participant Agent as Agent v0 participant Config as Configuration participant API as API Server Agent->>Config: Charger token d'authentification Config-->>Agent: Token ou erreur Agent->>API: Upload avec token dans headers API->>API: Valider token alt Token valide API-->>Agent: 200 OK Agent->>Agent: Marquer upload comme réussi else Token invalide API-->>Agent: 401 Unauthorized Agent->>Agent: Conserver session en queue Agent->>Agent: Logger erreur détaillée end ``` ## Components and Interfaces ### 1. Authentication Manager Nouveau composant pour gérer l'authentification : ```python class AuthenticationManager: def __init__(self, config_path: str): self.config_path = config_path self.token = None self.api_url = None def load_config(self) -> bool: """Charge la configuration d'authentification""" pass def get_auth_headers(self) -> Dict[str, str]: """Retourne les headers d'authentification""" pass def validate_token(self) -> bool: """Valide le token auprès du serveur""" pass ``` ### 2. Diagnostic Tool Outil de diagnostic pour tester l'authentification : ```python class AuthDiagnostic: def __init__(self, auth_manager: AuthenticationManager): self.auth_manager = auth_manager def run_full_diagnostic(self) -> DiagnosticResult: """Lance un diagnostic complet""" pass def test_network_connectivity(self) -> bool: """Teste la connectivité réseau""" pass def test_authentication(self) -> bool: """Teste l'authentification""" pass def test_upload_endpoint(self) -> bool: """Teste l'endpoint d'upload avec un fichier factice""" pass ``` ### 3. Enhanced Uploader Amélioration de l'uploader existant : ```python class EnhancedUploader: def __init__(self, auth_manager: AuthenticationManager): self.auth_manager = auth_manager self.upload_stats = UploadStats() def upload_session(self, session_path: str) -> UploadResult: """Upload une session avec authentification""" pass def retry_failed_uploads(self) -> List[UploadResult]: """Relance les uploads échoués""" pass def get_upload_stats(self) -> UploadStats: """Retourne les statistiques d'upload""" pass ``` ## Data Models ### Configuration d'authentification ```python @dataclass class AuthConfig: api_url: str auth_token: Optional[str] max_retries: int = 3 timeout: int = 30 @classmethod def from_file(cls, config_path: str) -> 'AuthConfig': """Charge la configuration depuis un fichier""" pass def save_to_file(self, config_path: str) -> None: """Sauvegarde la configuration dans un fichier""" pass ``` ### Résultat de diagnostic ```python @dataclass class DiagnosticResult: network_ok: bool auth_token_valid: bool upload_endpoint_ok: bool error_messages: List[str] recommendations: List[str] def is_healthy(self) -> bool: """Retourne True si tout fonctionne""" return self.network_ok and self.auth_token_valid and self.upload_endpoint_ok ``` ### Statistiques d'upload ```python @dataclass class UploadStats: total_attempts: int = 0 successful_uploads: int = 0 failed_uploads: int = 0 pending_uploads: int = 0 last_success: Optional[datetime] = None last_failure: Optional[datetime] = None def success_rate(self) -> float: """Calcule le taux de succès""" if self.total_attempts == 0: return 0.0 return self.successful_uploads / self.total_attempts ``` ## Correctness Properties *A property is a characteristic or behavior that should hold true across all valid executions of a system-essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.* ### Property 1: Authentication logging completeness *For any* upload attempt, the system should log authentication details including token presence and server response **Validates: Requirements 1.1, 1.2** ### Property 2: Diagnostic tool functionality *For any* diagnostic execution, the tool should verify both agent and server authentication configuration and test network connectivity **Validates: Requirements 1.3, 1.4, 1.5** ### Property 3: Token-based authentication *For any* valid authentication token, uploads should succeed, and for missing tokens, the system should use defaults or request configuration **Validates: Requirements 2.1, 2.2** ### Property 4: Configuration management *For any* configuration change to API URL or authentication token, the system should allow the change and reload authentication parameters **Validates: Requirements 2.3, 2.4, 2.5** ### Property 5: Session preservation on auth failure *For any* upload that fails with HTTP 401, the session should be preserved locally and retry attempts should be limited per session **Validates: Requirements 3.1, 3.3** ### Property 6: Authentication recovery *For any* corrected authentication configuration, the system should resume uploading queued sessions and allow manual retry of failed uploads **Validates: Requirements 3.2, 3.5** ### Property 7: User notification on failure *For any* session that exhausts all retry attempts, the system should notify the user of the authentication problem **Validates: Requirements 3.4** ### Property 8: Authentication validation testing *For any* authentication test execution, the system should verify token validity and test complete upload functionality with appropriate success/failure feedback **Validates: Requirements 4.2, 4.3, 4.4, 4.5** ### Property 9: Upload monitoring and statistics *For any* upload attempt, the system should log the attempt with status, maintain accurate success/failure counts, and alert when failure rate exceeds threshold **Validates: Requirements 5.1, 5.2, 5.3** ### Property 10: Batch retry functionality *For any* collection of failed uploads, the system should allow batch retry operations **Validates: Requirements 5.5** ## Error Handling ### Types d'erreurs d'authentification 1. **Token manquant** - Utiliser un token par défaut ou demander configuration 2. **Token invalide** - Logger l'erreur et conserver la session pour retry 3. **Serveur inaccessible** - Distinguer les erreurs réseau des erreurs d'auth 4. **Timeout** - Traiter comme une erreur temporaire, permettre retry ### Stratégies de récupération 1. **Retry avec backoff exponentiel** pour les erreurs temporaires 2. **Conservation locale** des sessions en cas d'échec d'authentification 3. **Notification utilisateur** pour les problèmes persistants 4. **Diagnostic automatique** en cas d'échecs répétés ## Testing Strategy ### Tests unitaires - Test de chargement de configuration d'authentification - Test de génération des headers d'authentification - Test de validation de token - Test de gestion des erreurs HTTP 401 - Test de conservation des sessions échouées ### Tests d'intégration - Test d'authentification complète agent → serveur - Test de retry automatique après correction d'authentification - Test de diagnostic complet - Test de monitoring des uploads ### Tests de propriétés Chaque propriété de correctness sera implémentée comme un test basé sur les propriétés avec un minimum de 100 itérations. Les tests utiliseront le framework pytest avec hypothesis pour la génération de données de test. Format des tags de test : **Feature: agent-authentication-fix, Property {number}: {property_text}** ### Configuration des tests - Tests de propriétés : minimum 100 itérations par test - Tests d'intégration : utilisation d'un serveur de test local - Tests unitaires : mocking des appels réseau - Tests de diagnostic : simulation de différents états de configuration