rmi-backend/app/_archive/legacy_2026_07/safe_imports.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

168 lines
5.6 KiB
Python

"""
Safe Module Importer - Handles stub fallbacks for security_intel router
========================================================================
This module wraps security feature imports with graceful fallbacks to stubs
if dependencies aren't available, preventing full router import failures.
"""
import logging
from typing import Any
logger = logging.getLogger(__name__)
def safe_import(name: str, fallback_to_stub: bool = True) -> Any | None:
"""
Safely import a module, optionally falling back to stub implementation.
Args:
name: Module path (e.g., 'web3' or 'app.contract_deepscan')
fallback_to_stub: If True, returns stub module on ImportError
Returns:
Imported module, stub fallback, or None
"""
try:
module = __import__(name, fromlist=[""])
logger.info(f"✓ Loaded: {name}")
return module
except ImportError:
if fallback_to_stub:
logger.warning(f"{name} not available, using stub fallback")
return None
raise
# ─── STUB CLASSES FOR CRITICAL DEPENDENCIES ───────────────────────
class StubContractDeepscan:
"""Stub contract scanning module."""
def deep_scan_contract(self, address: str, chain: str = "base") -> dict[str, Any]:
return {
"address": address,
"chain": chain,
"scanned": False,
"vulnerabilities": [],
"checks": [],
"status": "stub_mode",
}
def batch_deep_scan(self, addresses: list[str], chain: str = "base") -> dict[str, Any]:
results = [self.deep_scan_contract(addr, chain) for addr in addresses]
return {"contracts": results, "total": len(results)}
class StubCrossChainCorrelator:
"""Stub cross-chain correlation module."""
class ChainFingerprint:
def __init__(self, address: str, chain: str):
self.address = address
self.chain = chain
def get_hash(self) -> str:
return f"{self.chain}:{self.address}"
class CrossChainCorrelator:
def link_wallets(self, addresses: list[str], chains: list[str]) -> dict[str, Any]:
return {"linked": True, "wallets": addresses, "chains": chains}
def find_correlations(self, address: str, limit: int = 10) -> dict[str, Any]:
return {"address": address, "correlations": [], "count": 0}
class StubCryptoGuard:
"""Stub crypto guard module."""
def check_wallet_reputation(self, address: str) -> dict[str, Any]:
return {"address": address, "reputation": "unknown", "risk_score": 0, "flags": []}
def rate_limit_by_tier(self, tier: str) -> dict[str, int]:
tiers = {"FREE": {"requests_per_hour": 10, "requests_per_day": 100}}
return tiers.get(tier, {"requests_per_hour": 100, "requests_per_day": 1000})
def require_crypto_auth(self, request: Any) -> dict[str, Any]:
return {"authenticated": True}
# ─── STUB INSTANCES ───────────────────────────────────────────────
_stub_deepscan = StubContractDeepscan()
_stub_correlator = StubCrossChainCorrelator()
_stub_correlator_corr = _stub_correlator.CrossChainCorrelator()
_stub_crypto_guard = StubCryptoGuard()
# ─── FALLBACK LOADERS ─────────────────────────────────────────────
def get_contract_deepscan():
"""Load contract deepscan with fallback to stub."""
try:
from app.contract_deepscan import batch_deep_scan, deep_scan_contract
return deep_scan_contract, batch_deep_scan
except ImportError:
logger.warning("contract_deepscan not available, using stub")
return (_stub_deepscan.deep_scan_contract, _stub_deepscan.batch_deep_scan)
def get_cross_chain_correlator():
"""Load cross-chain correlator with fallback to stub."""
try:
from app.cross_chain_correlator import CrossChainCorrelator
return CrossChainCorrelator
except ImportError:
logger.warning("cross_chain_correlator not available, using stub")
return _stub_correlator_corr
def get_crypto_guard():
"""Load crypto guard with fallback to stub."""
try:
from app.crypto_guard import (
check_wallet_reputation,
rate_limit_by_tier,
)
return check_wallet_reputation, rate_limit_by_tier
except ImportError:
logger.warning("crypto_guard not available, using stub")
return (_stub_crypto_guard.check_wallet_reputation, _stub_crypto_guard.rate_limit_by_tier)
def get_sentinel_manager():
"""Load mempool sentinel with fallback to stub."""
try:
from app.mempool_sentinel import SentinelManager
return SentinelManager
except ImportError:
logger.warning("mempool_sentinel not available, using stub")
return lambda: None
def get_wallet_anomaly_detector():
"""Load wallet anomaly detector with fallback to stub."""
try:
from app.ml_anomaly import WalletAnomalyDetector
return WalletAnomalyDetector
except ImportError:
logger.warning("ml_anomaly not available, using stub")
return lambda: None
def get_token_anomaly_detector():
"""Load token anomaly detector with fallback to stub."""
try:
from app.ml_anomaly import TokenMetricAnomalyDetector
return TokenMetricAnomalyDetector
except ImportError:
logger.warning("ml_anomaly not available, using stub")
return lambda: None