🕵️♂️ (2-in-1) Email & Username OSINT suite featuring native MCP support for deep data extraction just from a single Email/Username. Analyzes 2720+ actively maintained scan vectors (210+ email / 2510+ username) for security research, investigations, and digital footprinting.
Python cybersecuritycybersecurity-toolsemail-osintethical-hackingethical-hacking-toolsidentificationinfosecosintosint-emailosint-toolosint-toolsosint-usernamepentestingpythonredteam-toolsredteamingthreat-intelligence
fix(mcp): defer cleanup until scan worker threads terminate on cancellation (#693)
Kaif0b3a28793a00
diff --git a/tests/test_mcp_handlers.py b/tests/test_mcp_handlers.pyindex 241257f..5216684 100644--- a/tests/test_mcp_handlers.py+++ b/tests/test_mcp_handlers.py@@ -125,3 +125,125 @@ async def test_execute_scan_cross_scan_runs_off_event_loop(mock_run_scan, mock_cawait execute_scan({"username": "testuser", "cross_scan": True}, is_email=False)assert seen["thread"] != loop_thread+++async def test_cancelling_mcp_scan_defers_cleanup_until_worker_terminates(monkeypatch):+ import asyncio+ import sys+ import threading+ from user_scanner.core import helpers+ from user_scanner.mcp import handlers++ started = threading.Event()+ release = threading.Event()+ finished = threading.Event()+ observations = {}+ original_stdout = sys.stdout++ def worker(*args):+ observations["initial_proxy"] = helpers.get_proxy()+ started.set()+ try:+ assert release.wait(5)+ observations["late_proxy"] = helpers.get_proxy()+ observations["stdout_restored"] = sys.stdout is original_stdout+ return []+ finally:+ finished.set()++ monkeypatch.setattr(handlers, "_run_scan", worker)++ handlers._scan_lock = asyncio.Lock()+ task = asyncio.create_task(+ handlers.execute_scan(+ {"username": "audit", "proxies": ["http://127.0.0.1:12345"]},+ is_email=False,+ )+ )++ assert await asyncio.to_thread(started.wait, 5)+ task.cancel()++ await asyncio.sleep(0.05)+ assert not finished.is_set(), "Worker should still be alive"+ assert handlers._scan_lock.locked(), "Lock must remain held while worker is alive"+ assert helpers.get_proxy() == "http://127.0.0.1:12345", "Proxy must not be cleared while worker is alive"++ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert finished.is_set()+ assert not handlers._scan_lock.locked()+ assert helpers.get_proxy() is None+ assert observations == {+ "initial_proxy": "http://127.0.0.1:12345",+ "late_proxy": "http://127.0.0.1:12345",+ "stdout_restored": False,+ }+++async def test_cancelling_mcp_cross_scan_defers_cleanup(monkeypatch):+ import asyncio+ import sys+ import threading+ from user_scanner.core import helpers+ from user_scanner.mcp import handlers++ started = threading.Event()+ release = threading.Event()+ finished = threading.Event()+ observations = {}+ original_stdout = sys.stdout++ def fake_run_scan(*args):+ return [Result.taken()]++ def fake_cross_scan(*args):+ observations["initial_proxy"] = helpers.get_proxy()+ started.set()+ try:+ assert release.wait(5)+ observations["late_proxy"] = helpers.get_proxy()+ observations["stdout_restored"] = sys.stdout is original_stdout+ return []+ finally:+ finished.set()++ monkeypatch.setattr(handlers, "_run_scan", fake_run_scan)+ monkeypatch.setattr(handlers, "run_cross_scan", fake_cross_scan)++ handlers._scan_lock = asyncio.Lock()+ task = asyncio.create_task(+ handlers.execute_scan(+ {+ "username": "audit",+ "cross_scan": True,+ "proxies": ["http://127.0.0.1:12345"],+ },+ is_email=False,+ )+ )++ assert await asyncio.to_thread(started.wait, 5)+ task.cancel()++ await asyncio.sleep(0.05)+ assert not finished.is_set(), "Cross-scan worker should still be alive"+ assert handlers._scan_lock.locked(), "Lock must remain held during cross-scan cancellation"+ assert helpers.get_proxy() == "http://127.0.0.1:12345"++ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert finished.is_set()+ assert not handlers._scan_lock.locked()+ assert helpers.get_proxy() is None+ assert observations == {+ "initial_proxy": "http://127.0.0.1:12345",+ "late_proxy": "http://127.0.0.1:12345",+ "stdout_restored": False,+ }diff --git a/user_scanner/mcp/handlers.py b/user_scanner/mcp/handlers.pyindex 7b3326f..19595ab 100644--- a/user_scanner/mcp/handlers.py+++ b/user_scanner/mcp/handlers.py@@ -41,6 +41,32 @@ _DEFAULT_EMAIL_CONCURRENCY = 25_scan_lock = asyncio.Lock()+async def _run_in_thread(func: Any, *args: Any) -> Any:+ """Run a synchronous callable in a thread, shielding execution from cancellation.++ If the calling asyncio task is cancelled while the thread is running,+ this awaits the thread to completion before propagating CancelledError.+ This guarantees that the thread finishes while context managers+ (stdout redirection) and scan settings (proxies, locks) remain active.+ """+ loop = asyncio.get_running_loop()+ fut = loop.run_in_executor(None, func, *args)+ cancelled = False+ while True:+ try:+ res = await asyncio.shield(fut)+ if cancelled:+ raise asyncio.CancelledError()+ return res+ except asyncio.CancelledError:+ cancelled = True+ task = asyncio.current_task()+ if task and hasattr(task, "uncancel"):+ task.uncancel()+ if fut.done():+ raise++async def execute_scan(arguments: dict, is_email: bool) -> list[types.TextContent]:target_key = "email" if is_email else "username"target = arguments.get(target_key)@@ -97,7 +123,7 @@ async def execute_scan(arguments: dict, is_email: bool) -> list[types.TextConten# Redirect stdout to stderr so orchestrator print() calls# don't corrupt the JSON-RPC stdio streamwith contextlib.redirect_stdout(sys.stderr):- results = await asyncio.to_thread(+ results = await _run_in_thread(_run_scan, target, config, is_email, category, module_name)@@ -113,7 +139,7 @@ async def execute_scan(arguments: dict, is_email: bool) -> list[types.TextContenmodules=(module_name,) if module_name else (),categories=(category,) if category else (),)- cross_results = await asyncio.to_thread(+ cross_results = await _run_in_thread(run_cross_scan, results, config, cross_configs)results.extend(cross_results)