════════════════════════════════════════════════════════════════════════════════ GUIA IMPLEMENTAÇÃO: LOG MASKING EM api.py ════════════════════════════════════════════════════════════════════════════════ 🎯 OBJETIVO: Integrar log_masking.py em api.py para eliminar THINK LEAK ⏱️ TEMPO ESTIMADO: 30 minutos 🔒 CRITICIDADE: ALTA (Segurança) ════════════════════════════════════════════════════════════════════════════════ PASSO 1: ADICIONAR ENV VARIABLE ════════════════════════════════════════════════════════════════════════════════ Arquivo: .env Adicionar: ``` # Log Masking Configuration LOG_MASKING_SALT=seu-salt-secreto-aleatorio-32-caracteres-aqui-123456789abcd ``` Gerar salt seguro: ```bash python3 -c "import secrets; print(secrets.token_urlsafe(32))" ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 2: IMPORTS EM api.py ════════════════════════════════════════════════════════════════════════════════ Localização: Top of api.py, logo após imports existentes Adicionar: ```python from modules.log_masking import SecureLogger, LogMasking ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 3: INICIALIZAR SECURE LOGGER ════════════════════════════════════════════════════════════════════════════════ Localização: Em AkiraAPI.__init__() Adicionar (após init do logger normal): ```python # Inicializar secure logger self.secure_log = SecureLogger(self.logger) self.logger.info("✅ Secure logging initialized") ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 4: PROTEGER THINKING ENGINE LOGS ════════════════════════════════════════════════════════════════════════════════ Localização: em modules/thinking_engine.py ou modules/api.py onde ThinkingEngine é logado ANTES: ```python logger.info(f"🧠 ThinkingEngine: depth={depth}, intent={intent} | 💭 {thinking_content}") ``` DEPOIS: ```python secure_log.thinking(thinking_content, depth=depth, user_id=user_id) ``` Exemplo completo em akira_endpoint(): ```python # Linha ~20:58:47 do log if thinking_content: secure_log.thinking( thinking_content, depth=thinking_depth, user_id=user_info.get('usuario_id') ) ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 5: PROTEGER HTTP REQUESTS ════════════════════════════════════════════════════════════════════════════════ Localização: Em modules/thinking_engine.py onde faz POST para OpenRouter ANTES: ```python logger.info(f"HTTP Request: POST {url} {response.status_code}") ``` DEPOIS: ```python secure_log.provider_request("POST", url, response.status_code) ``` Exemplo em _generate_dynamic_thought(): ```python # Linha ~20:50:50 do log try: response = requests.post( url, headers=headers, json=payload, timeout=30 ) secure_log.provider_request("POST", url, response.status_code) except Exception as e: secure_log.provider_request("POST", url, "ERROR") logger.error(f"Error: {str(e)}") ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 6: PROTEGER EMBEDDING LOGS ════════════════════════════════════════════════════════════════════════════════ Localização: em modules/api.py _worker() ou onde embedding é salvo ANTES: ```python logger.info(f"✅ [EMBEDDING] Resposta (mistral) salva com sucesso. Dim: (384,)") ``` DEPOIS: ```python secure_log.embedding_saved(model_name, embedding_dimension) ``` Exemplo em _worker(): ```python # Linha ~20:50:53 do log try: # Save embedding embedding = model.encode(response_text) secure_log.embedding_saved( model="mistral", # ou pegar do config dimension=len(embedding) ) except Exception as e: logger.error(f"Embedding error: {e}") ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 7: PROTEGER RESPONSE LOGS ════════════════════════════════════════════════════════════════════════════════ Localização: em akira_endpoint() onde retorna resposta ANTES: ```python logger.info(f"📤 [AKIRA RESPONSE] resposta={len(response)}chars | remote_actions=0") ``` DEPOIS: ```python secure_log.response( user_id=usuario_id, content=response, group_id=grupo_id ) ``` Exemplo em akira_endpoint(): ```python # Linha ~20:50:53 do log response_final = generate_response(...) secure_log.response( user_id=user_info.get('usuario_id'), content=response_final, group_id=user_info.get('grupo_id') ) return {"resposta": response_final} ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 8: PROTEGER CHECKPOINT LOGS ════════════════════════════════════════════════════════════════════════════════ Localização: em modules/database.py fazer_checkpoint_hf_sync() ANTES: ```python logger.info(f"✅ Checkpoint Seguro para HF Buckets concluído em: /akira/data/cloud_sync/akira.db") ``` DEPOIS: ```python secure_log.checkpoint("/akira/data/cloud_sync/akira.db") ``` Exemplo em fazer_checkpoint_hf_sync(): ```python # Linha ~22:43:41 do log try: # Do checkpoint self.db.commit() secure_log.checkpoint(checkpoint_path) logger.info("✅ Checkpoint completed") except Exception as e: logger.error(f"Checkpoint error: {e}") ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 9: PROTEGER USER IDS EM TODOS OS LOGS ════════════════════════════════════════════════════════════════════════════════ Localização: Qualquer lugar que printe user_id ANTES: ```python logger.info(f"Stefânio (111596437241877) [Grupo: AKIRA]:") ``` DEPOIS: ```python masked_user = LogMasking.mask_user_id(user_id) logger.info(f"Usuário {masked_user} [Grupo: AKIRA]:") ``` Exemplo em akira_endpoint(): ```python # Linha ~20:50:45 do log masked_user = LogMasking.mask_user_id(user_info['usuario_id']) masked_group = LogMasking.mask_group_id(grupo_id) if grupo_id else "[PV]" logger.info(f"🔄 [REPLY AO BOT] {masked_user} in {masked_group}") ``` ════════════════════════════════════════════════════════════════════════════════ PASSO 10: PROTEGER INTENTS E CLASSIFICAÇÕES ════════════════════════════════════════════════════════════════════════════════ Localização: Qualquer lugar que classifique intent ANTES: ```python logger.info(f"intent=['indefinido', 'pergunta_tecnica']") ``` DEPOIS: ```python masked_intent = LogMasking.mask_intent(intent_list) logger.info(f"intent={masked_intent}") ``` Exemplo em thinking_engine.py: ```python intent_list = classify_intent(text) masked_intent = LogMasking.mask_intent(intent_list) logger.info(f"Intent classified as {masked_intent}") ``` ════════════════════════════════════════════════════════════════════════════════ VERIFICAÇÃO PÓS-IMPLEMENTAÇÃO ════════════════════════════════════════════════════════════════════════════════ Checklist: 1️⃣ Logs antes vs depois ANTES: ``` 20:50:50 | INFO | 🧠 ThinkingEngine: depth=simples, intent=['indefinido'] | 💭 **Análise interna – Stefânio** - parece curioso... ``` DEPOIS: ``` 20:50:50 | INFO | 🧠 ThinkingEngine: [THINK-a7f3c2b1-simples] by [USR-8f2e1c5a] ``` 2️⃣ Procurar por vazamentos restantes ```bash # Verificar em logs públicos grep -i "openrouter\|mistral\|gpt-4" logs/akira.log # Verificar User IDs grep -E "\d{15,}" logs/akira.log # Verificar paths grep "/akira/data" logs/akira.log ``` Resultado esperado: NADA! (todas as ocorrências mascaradas) 3️⃣ Testar masking manualmente ```python from modules.log_masking import LogMasking # Testar User ID print(LogMasking.mask_user_id("111596437241877")) # Output: [USR-a7f3c2b1] # Testar Thinking print(LogMasking.mask_thinking("Stefânio parece curioso")) # Output: [THINK-8f2e1c5a] # Testar Provider print(LogMasking.mask_provider_url("https://openrouter.ai/api/v1/chat/completions")) # Output: [LLM-4d9e2a1f] ``` 4️⃣ Verificar performance Impact esperado: • Hashing: ~1ms por operação • Caching: ~0.1ms em hit • Total overhead: <2% por request ════════════════════════════════════════════════════════════════════════════════ TROUBLESHOOTING ════════════════════════════════════════════════════════════════════════════════ ❌ Problema: "SECRET_SALT not configured" ✅ Solução: Adicionar LOG_MASKING_SALT em .env ❌ Problema: "Still seeing plain text thinking" ✅ Solução: Verificar se secure_log.thinking() é chamado antes de logger.info() ❌ Problema: "Performance degrada" ✅ Solução: Caching está funcionando, use SecureLogger (mais eficiente) ❌ Problema: "Logs ilegíveis" ✅ Solução: ESPERADO! Isto significa proteção funcionando. Use internal logs admin. ════════════════════════════════════════════════════════════════════════════════ RESULTADO FINAL ════════════════════════════════════════════════════════════════════════════════ Antes (INSEGURO): ``` 20:50:50 | INFO | ThinkingEngine: depth=simples, intent=['indefinido'] | 💭 Análise interna – Stefânio - parece curioso ao perguntar "O quê que é SDK..." HTTP Request: POST https://openrouter.ai/api/v1/chat/completions "HTTP/1.1 200 OK" [EMBEDDING] Resposta (mistral) salva com sucesso. Dim: (384,) Checkpoint concluído em: /akira/data/cloud_sync/akira.db Usuario: Stefânio (111596437241877) ``` Depois (SEGURO): ``` 20:50:50 | INFO | 🧠 ThinkingEngine: [THINK-a7f3c2b1-simples] by [USR-8f2e1c5a] 20:50:50 | INFO | 🌐 [HTTP-POST-LLM-4d9e2a1f-200] 20:50:53 | SUCCESS | ✅ [EMBEDDING] [MODEL-8c5f1a3e] salva com sucesso. [EMB-***] 22:43:41 | INFO | ✅ Checkpoint concluído em: [PATH-8f2e1c5a] 20:50:45 | INFO | 🔄 [REPLY AO BOT] [USR-8f2e1c5a] in [GRP-4d9e2a1f] ``` ✅ THINK LEAK ELIMINADO ✅ PROVIDER EXPOSURE ELIMINADO ✅ USER ID PROTEÇÃO ATIVA ✅ LOGS PÚBLICOS SEGUROS ════════════════════════════════════════════════════════════════════════════════ IMPLEMENTAÇÃO PRONTA PARA DEPLOY! 🔒 ════════════════════════════════════════════════════════════════════════════════