AKIRA-SOFTEDGE / GUIA_IMPLEMENTACAO_LOG_MASKING.md
akra35567's picture
Upload 190 files
b259a65 verified
|
Raw
History Blame Contribute Delete
15.4 kB

════════════════════════════════════════════════════════════════════════════════ 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:

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:

from modules.log_masking import SecureLogger, LogMasking

════════════════════════════════════════════════════════════════════════════════ PASSO 3: INICIALIZAR SECURE LOGGER ════════════════════════════════════════════════════════════════════════════════

LocalizaΓ§Γ£o: Em AkiraAPI.init()

Adicionar (apΓ³s init do logger normal):

# 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:

logger.info(f"🧠 ThinkingEngine: depth={depth}, intent={intent} | πŸ’­ {thinking_content}")

DEPOIS:

secure_log.thinking(thinking_content, depth=depth, user_id=user_id)

Exemplo completo em akira_endpoint():

# 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:

logger.info(f"HTTP Request: POST {url} {response.status_code}")

DEPOIS:

secure_log.provider_request("POST", url, response.status_code)

Exemplo em _generate_dynamic_thought():

# 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:

logger.info(f"βœ… [EMBEDDING] Resposta (mistral) salva com sucesso. Dim: (384,)")

DEPOIS:

secure_log.embedding_saved(model_name, embedding_dimension)

Exemplo em _worker():

# 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:

logger.info(f"πŸ“€ [AKIRA RESPONSE] resposta={len(response)}chars | remote_actions=0")

DEPOIS:

secure_log.response(
    user_id=usuario_id,
    content=response,
    group_id=grupo_id
)

Exemplo em akira_endpoint():

# 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:

logger.info(f"βœ… Checkpoint Seguro para HF Buckets concluΓ­do em: /akira/data/cloud_sync/akira.db")

DEPOIS:

secure_log.checkpoint("/akira/data/cloud_sync/akira.db")

Exemplo em fazer_checkpoint_hf_sync():

# 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:

logger.info(f"StefΓ’nio (111596437241877) [Grupo: AKIRA]:")

DEPOIS:

masked_user = LogMasking.mask_user_id(user_id)
logger.info(f"UsuΓ‘rio {masked_user} [Grupo: AKIRA]:")

Exemplo em akira_endpoint():

# 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:

logger.info(f"intent=['indefinido', 'pergunta_tecnica']")

DEPOIS:

masked_intent = LogMasking.mask_intent(intent_list)
logger.info(f"intent={masked_intent}")

Exemplo em thinking_engine.py:

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

# 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

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! πŸ”’ ════════════════════════════════════════════════════════════════════════════════