π΅οΈββοΈ (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(cli): safely append to existing json reports and write atomically (#694)
Kaifc1da59a1a92f
diff --git a/tests/test_export.py b/tests/test_export.pynew file mode 100644index 0000000..77df5a7--- /dev/null+++ b/tests/test_export.py@@ -0,0 +1,107 @@+import contextlib+import io+import json+import sys+import pytest++from user_scanner.core.result import Result+import user_scanner.__main__ as cli+++def test_json_export_new_file(monkeypatch, tmp_path):+ output = tmp_path / "new_report.json"+ monkeypatch.setattr(+ sys, "argv", ["user-scanner", "-u", "audit", "-f", "json", "-o", str(output)]+ )+ monkeypatch.setattr(cli, "check_for_updates", lambda: None)+ monkeypatch.setattr(cli, "print_banner", lambda: None)+ monkeypatch.setattr(+ cli, "run_user_full", lambda *args: [Result.taken(username="audit", site_name="Example")]+ )++ with contextlib.redirect_stdout(io.StringIO()) as captured:+ cli.main()++ assert output.exists()+ data = json.loads(output.read_text(encoding="utf-8"))+ assert len(data) == 1+ assert data[0]["username"] == "audit"+ assert "JSON Results saved" in captured.getvalue()+++def test_json_export_append_valid_existing(monkeypatch, tmp_path):+ output = tmp_path / "report.json"+ initial_data = [{"username": "prior_user", "site_name": "PriorSite"}]+ output.write_text(json.dumps(initial_data), encoding="utf-8")++ monkeypatch.setattr(+ sys, "argv", ["user-scanner", "-u", "audit", "-f", "json", "-o", str(output)]+ )+ monkeypatch.setattr(cli, "check_for_updates", lambda: None)+ monkeypatch.setattr(cli, "print_banner", lambda: None)+ monkeypatch.setattr(+ cli, "run_user_full", lambda *args: [Result.taken(username="audit", site_name="Example")]+ )++ with contextlib.redirect_stdout(io.StringIO()) as captured:+ cli.main()++ data = json.loads(output.read_text(encoding="utf-8"))+ assert len(data) == 2+ assert data[0]["username"] == "prior_user"+ assert data[1]["username"] == "audit"+ assert "JSON Results saved" in captured.getvalue()+++ "corrupt_content",+ [+ '[{"prior": "truncated"}',+ '{"prior": "valid_object_not_list"}',+ '"string_not_list"',+ '42',+ ],+)+def test_json_export_preserves_corrupt_existing_file(monkeypatch, tmp_path, corrupt_content):+ output = tmp_path / "report.json"+ output.write_text(corrupt_content, encoding="utf-8")++ monkeypatch.setattr(+ sys, "argv", ["user-scanner", "-u", "audit", "-f", "json", "-o", str(output)]+ )+ monkeypatch.setattr(cli, "check_for_updates", lambda: None)+ monkeypatch.setattr(cli, "print_banner", lambda: None)+ monkeypatch.setattr(+ cli, "run_user_full", lambda *args: [Result.taken(username="audit", site_name="Example")]+ )++ with contextlib.redirect_stdout(io.StringIO()) as captured:+ cli.main()++ # Original corrupt file bytes must remain untouched+ assert output.read_text(encoding="utf-8") == corrupt_content+ stdout = captured.getvalue()+ assert "Failed to append to existing JSON file" in stdout+ assert "JSON Results saved" not in stdout+++def test_json_export_empty_existing_file(monkeypatch, tmp_path):+ output = tmp_path / "empty_report.json"+ output.write_text("", encoding="utf-8")++ monkeypatch.setattr(+ sys, "argv", ["user-scanner", "-u", "audit", "-f", "json", "-o", str(output)]+ )+ monkeypatch.setattr(cli, "check_for_updates", lambda: None)+ monkeypatch.setattr(cli, "print_banner", lambda: None)+ monkeypatch.setattr(+ cli, "run_user_full", lambda *args: [Result.taken(username="audit", site_name="Example")]+ )++ with contextlib.redirect_stdout(io.StringIO()) as captured:+ cli.main()++ data = json.loads(output.read_text(encoding="utf-8"))+ assert len(data) == 1+ assert data[0]["username"] == "audit"+ assert "JSON Results saved" in captured.getvalue()diff --git a/user_scanner/__main__.py b/user_scanner/__main__.pyindex d425e42..fc7f2f4 100644--- a/user_scanner/__main__.py+++ b/user_scanner/__main__.py@@ -2,6 +2,7 @@ import argparseimport jsonimport sysimport os+import tempfileimport timefrom colorama import Fore, Style@@ -737,16 +738,36 @@ def main():if os.path.exists(t_output):try:with open(t_output, "r", encoding="utf-8") as f:- old = json.load(f)- if isinstance(old, list):+ content = f.read().strip()+ if content:+ old = json.loads(content)+ if not isinstance(old, list):+ raise ValueError(+ f"Expected JSON array, got {type(old).__name__}"+ )data = old- except (json.JSONDecodeError, Exception):- pass+ except Exception as e:+ print(f"\n{R}[β] Failed to append to existing JSON file at {t_output}: {e}{X}")+ continuedata.extend(new_items)- with open(t_output, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, ensure_ascii=False)- print(G + f"\n[+] JSON Results saved to {t_output}" + Style.RESET_ALL)+ try:+ dir_name = os.path.dirname(os.path.abspath(t_output))+ os.makedirs(dir_name, exist_ok=True)+ temp_file = tempfile.NamedTemporaryFile(+ "w", dir=dir_name, delete=False, encoding="utf-8"+ )+ try:+ with temp_file as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ os.replace(temp_file.name, t_output)+ except Exception:+ if os.path.exists(temp_file.name):+ os.remove(temp_file.name)+ raise+ print(G + f"\n[+] JSON Results saved to {t_output}" + Style.RESET_ALL)+ except Exception as e:+ print(f"\n{R}[β] Failed to save JSON report to {t_output}: {e}{X}")elif args.format == "csv":try: