rmi-backend/app/_archive/legacy_2026_07/protection_api.py
cryptorugmunch 628c1d2a10
Some checks failed
CI / build (push) Failing after 3s
refactor(rmi-backend,audit): mount Wave 3 + archive 136 dead-code files (P2.3)
PHASE 2.3 (AUDIT-2026-Q3.md):

Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
  - app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
    POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
    Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
    with the v1 /api/v1/scanner/ stub.
  - app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
    library module consumed by unified_scanner_router via get_wallet_scanner()).
  - app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
    /api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).

Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
  - 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
  - 63 flat app/*.py (domain modules never imported by live code).
  - 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
    tests/unit/test_bridge_health.py which directly imports it; reach graph
    considered tests/ only as transitive reach — to be patched in next cycle).

Forced-LIVE (NOT archived per user directive):
  - app/ai_pipeline_v3.py  (3 importers in audit window, importers themselves DEAD)
  - app/splade_bm25.py       (LIVE via app.rag_service)
  - app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
  - app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)

Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
  - imports = 348 app.* modules
  - reached = 194 files reachable from roots
  - archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
  - Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)

pyproject.toml updates:
  - setuptools.packages.find: added exclude for app._archive*
  - ruff.extend-exclude: added "app/_archive/"
  - mypy.exclude: added "app/_archive/"

Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).

Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.

Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
2026-07-06 20:52:31 +02:00

123 lines
4 KiB
Python

# Protection API endpoints for RMI
# Core detection API that all protection modules call
#
# NOTE: This module is a stub. The underlying services (RAGService class,
# Scanner, WalletLabels, EntityIntel, Blocklist) have not been implemented
# as importable classes yet. The rag_service module uses standalone async
# functions, not a RAGService class. We wrap imports in try/except so the
# app doesn't crash on startup.
import logging
from fastapi import APIRouter
from pydantic import BaseModel
logger = logging.getLogger(__name__)
# Attempt imports - these are stubs and may not exist
try:
from app.rag_service import detect_scam_patterns, search_similar
except ImportError:
detect_scam_patterns = None
search_similar = None
try:
from app.url_scam_detector import check_url_safety
except ImportError:
check_url_safety = None
try:
from app.wallet_persona import analyze_wallet
except ImportError:
analyze_wallet = None
router = APIRouter(prefix="/api/v1/protect", tags=["protection"])
class UrlCheckRequest(BaseModel):
url: str
class WalletCheckRequest(BaseModel):
address: str
chain: str
class TokenCheckRequest(BaseModel):
address: str
chain: str
@router.post("/check-url")
async def check_url(request: UrlCheckRequest):
"""Check URL safety against scam patterns and blocklist"""
try:
# Use detect_scam_patterns from rag_service (standalone function)
if detect_scam_patterns:
rag_result = await detect_scam_patterns(request.url)
if rag_result and rag_result.get("is_scam"):
return {
"safe": False,
"risk": rag_result.get("risk_level", "high"),
"reason": rag_result.get("reason", "Known scam pattern"),
"source": "rag",
}
# Use URL scam detector if available
if check_url_safety:
scan_result = await check_url_safety(request.url)
if scan_result and not scan_result.get("safe", True):
return {
"safe": False,
"risk": scan_result.get("risk", "high"),
"reason": scan_result.get("reason", "Suspicious URL"),
"source": "scanner",
}
return {"safe": True, "risk": "low", "reason": "No known risks found", "source": "scanner"}
except Exception as e:
logger.error(f"URL check failed: {e}")
return {"safe": True, "error": "service_unavailable", "reason": str(e)}
@router.post("/check-wallet")
async def check_wallet(request: WalletCheckRequest):
"""Check wallet safety against labels and analysis"""
try:
if analyze_wallet:
result = await analyze_wallet(request.address, request.chain)
if result and result.get("risk_score", 0) > 70:
return {
"safe": False,
"risk": "high",
"reason": result.get("risk_reasons", ["High risk wallet"]),
"source": "analysis",
}
return {"safe": True, "risk": "low", "reason": "No known risks found", "source": "analysis"}
except Exception as e:
logger.error(f"Wallet check failed: {e}")
return {"safe": True, "error": "service_unavailable", "reason": str(e)}
@router.post("/check-token")
async def check_token(request: TokenCheckRequest):
"""Check token safety - delegates to x402-tools risk_scan for full analysis"""
return {
"safe": True,
"note": "Use /api/v1/x402-tools/risk_scan for full token security analysis",
"address": request.address,
"chain": request.chain,
}
@router.get("/health")
async def protection_health():
"""Health check for protection services"""
services = {
"rag_scam_detection": detect_scam_patterns is not None,
"url_safety_check": check_url_safety is not None,
"wallet_analysis": analyze_wallet is not None,
}
all_ok = all(services.values())
return {"status": "ok" if all_ok else "partial", "services": services}